我有一张像这样的表:
table = {milk, butter, cheese} -- without "Quotation marks"
我正在寻找一种检查表中是否存在给定值的方法,并发现了这一点:
if table.hasValue(table, milk) == true then ...
但它返回nil
,有什么原因吗? (它说.hasValue
无效)或者我可以选择检查该表中是否存在值?我试过几种方式:
if table.milk == true then ...
if table[milk] == true then ...
所有这些都返回nil或false。
答案 0 :(得分:1)
你可以试试这个
items = {milk=true, butter=true, cheese=true}
if items.milk then
...
end
OR
if items.butter == true then
...
end
答案 1 :(得分:1)
Lua表可以充当数组或关联数组(map)。
没有hasValue,但通过使用表作为关联数组,您可以轻松有效地实现它:
local table = {
milk = true,
butter = true,
cheese = true,
}
-- has milk?
if table.milk then
print("Has milk!")
end
if table.rocks then
print("Has rocks!")
end
答案 2 :(得分:0)
如果您撰写table = {milk=true, butter=true, cheese=true}
,则可以使用if table.milk == true then ...
。
答案 3 :(得分:0)
你有几个选择。
一,是创建一个集合:
local set = {
foo = true,
bar = true,
baz = true
}
然后检查表中是否有其中任何一个:
if set.bar then
这种方法的缺点是你不会以任何特定的顺序迭代它(pairs
以任意顺序返回项目。)
另一种选择是使用函数来检查表中的每个值。这在大型表中会非常慢,这使我们回到第一个选项的修改:反向查找生成器:(这是我建议做的 - 除非你的设置是静态的)
local data = {"milk", "butter", "cheese"}
local function reverse(tbl, target)
local target = target or {}
for k, v in pairs(tbl) do
target[v] = k
end
return target
end
local revdata = reverse(data)
print(revdata.cheese, revdata.butter, revdata.milk)
-- Output: 3 2 1
这将生成一个集合(额外的好处是为您提供原始表中值的索引)。您也可以将反向放入与数据相同的表格中,但这对于数字来说效果不佳(如果您需要再次生成反向数据,它会很混乱)。