在 lua 中的 table 中检查字符串值
Check for a string value in a table in lua
我正在尝试创建一个函数,用于检查 table 中的字符串值。
如果我像这样声明一个变量:
local table = "blue"
我的函数:
function check(color)
if color == "blue" then
return true
end
return false
end
当我使用 check(table)
和 returns true
时,它可以正常工作,但是当变量是具有字符串值的 table 时:
local table = {"blue", "yellow", "red"}
当我尝试使用函数时 check(table)
然后我的函数不起作用,我得到错误:
cannot convert a table to a clr type System.String
知道为什么会发生这种情况以及如何解决它吗?
首先,如果要检查是否相等,必须使用 == 而不是 =。
与许多其他编程语言一样,= 是赋值运算符,== 是逻辑运算符
如果你想检查 table 是否包含字符串 "blue",你必须将它的元素与 "blue" 进行比较,而不是 table 本身!
你在这里所做的就像试图找出桶中是否有苹果或香蕉。所以你检查桶看起来是否像香蕉。
试试这个:
function check(colours)
for i,v in ipairs(colours)
if v == "blue" then
return true
end
end
end
您的代码表明您对 Lua 的基础知识相当缺乏。
我建议阅读 Lua 参考手册和 Lua 中的免费电子书编程。
我正在尝试创建一个函数,用于检查 table 中的字符串值。
如果我像这样声明一个变量:
local table = "blue"
我的函数:
function check(color)
if color == "blue" then
return true
end
return false
end
当我使用 check(table)
和 returns true
时,它可以正常工作,但是当变量是具有字符串值的 table 时:
local table = {"blue", "yellow", "red"}
当我尝试使用函数时 check(table)
然后我的函数不起作用,我得到错误:
cannot convert a table to a clr type System.String
知道为什么会发生这种情况以及如何解决它吗?
首先,如果要检查是否相等,必须使用 == 而不是 =。 与许多其他编程语言一样,= 是赋值运算符,== 是逻辑运算符 如果你想检查 table 是否包含字符串 "blue",你必须将它的元素与 "blue" 进行比较,而不是 table 本身!
你在这里所做的就像试图找出桶中是否有苹果或香蕉。所以你检查桶看起来是否像香蕉。
试试这个:
function check(colours)
for i,v in ipairs(colours)
if v == "blue" then
return true
end
end
end
您的代码表明您对 Lua 的基础知识相当缺乏。 我建议阅读 Lua 参考手册和 Lua 中的免费电子书编程。