Lua - Table.hasValue 返回 nil

我有一个表格,内容如下:

table = {milk, butter, cheese} -- 没有引号

我正在寻找一种方法来检查一个给定的值是否在表格中,我找到了这个:

if table.hasValue(table, milk) == true then ...

但它返回 nil,有什么原因吗?(它说 .hasValue 无效)还是我可以找到替代方案来检查值是否存在该表格中?我尝试了几种方法,例如:

if table.milk == true then ...
if table[milk] == true then ...

所有这些都返回 nil 或 false。

点赞
用户107090
用户107090

如果你写 table = {milk=true, butter=true, cheese=true},那么你可以使用 if table.milk == true then ...

2014-07-20 16:45:44
用户1827883
用户1827883

你可以尝试这样做:

items = {milk=true, butter=true, cheese=true}

if items.milk then
  ...
end

或者

if items.butter == true then
  ...
end

enter image description here

2014-07-20 16:45:55
用户18403
用户18403

Lua 的表可以作为数组或者关联数组(映射)使用。

虽然没有 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
2014-07-20 17:21:25
用户2698261
用户2698261

你有几个选项。

第一种是创建一个 set:

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

这将生成一个 set (还附带了一个奖励就是给你原始表中的值的索引)。你也可以将反向查找放入与数据相同的表中,但这对于数字不会很好(如果需要再次生成反向查找,它会很混乱)。

2014-07-20 20:33:59