Jay*_*Jay 49 lua list lua-table
如果我有这样的项目列表:
local items = { "apple", "orange", "pear", "banana" }
Run Code Online (Sandbox Code Playgroud)
如何检查此列表中是否有"橙色"?
在Python中我可以这样做:
if "orange" in items:
# do something
Run Code Online (Sandbox Code Playgroud)
Lua中有同等的东西吗?
Jon*_*son 74
你可以使用类似于Lua中的Programming的集合:
function Set (list)
local set = {}
for _, l in ipairs(list) do set[l] = true end
return set
end
Run Code Online (Sandbox Code Playgroud)
然后你可以把你的列表放在Set中并测试成员资格:
local items = Set { "apple", "orange", "pear", "banana" }
if items["orange"] then
-- do something
end
Run Code Online (Sandbox Code Playgroud)
或者您可以直接迭代列表:
local items = { "apple", "orange", "pear", "banana" }
for _,v in pairs(items) do
if v == "orange" then
-- do something
break
end
end
Run Code Online (Sandbox Code Playgroud)
小智 27
请改用以下表示:
local items = { apple=true, orange=true, pear=true, banana=true }
if items.apple then
...
end
Run Code Online (Sandbox Code Playgroud)
Nor*_*sey 17
你是第一手看到Lua只有一个数据结构的缺点 - 你必须自己动手.如果你坚持使用Lua,你将逐渐积累一个函数库,以你喜欢的方式操作表.我的库包括列表到集的转换和高阶列表搜索功能:
function table.set(t) -- set of list
local u = { }
for _, v in ipairs(t) do u[v] = true end
return u
end
function table.find(f, l) -- find element v of l satisfying f(v)
for _, v in ipairs(l) do
if f(v) then
return v
end
end
return nil
end
Run Code Online (Sandbox Code Playgroud)