集合操作 |
|
集合操作非常有用,例如测试元素是否在集合或列表中。Lua 没有内置的集合运算符,但我们可以使用表格来构建它们。
function contains(t, e) for i = 1,#t do if t[i] == e then return true end end return false end t = { "abc","def","ghi" } print(contains(t,"def")) --> true print(contains(t,"ddd")) --> false
可以通过将表格 t
转换为字典(即列表元素成为键)来优化此操作。例如,
t = {["abc"] = true, ["def"] = true, ["ghi"] = true} print(t["def"]) --> true (t contains "def") print(t["ddd"]) --> nil (t does not contain "def")
为了更简洁的语法,我们可以使用函数 Set
从列表表格创建字典表格。
function Set(t) local s = {} for _,v in pairs(t) do s[v] = true end return s end function contains(t, e) return t[e] end t = Set{"abc", "def", "ghi"} print (contains(t,"def")) --> true print (t["def"]) --> true (same as above) print (contains(t,"ddd")) --> nil print (t["ddd"]) --> nil (same as above)
虽然集合在定义上是无序的,但我们可能仍然希望检索用于定义集合的列表中元素的索引。上面的代码可以修改以帮助解决这个问题。
function OrderedSet(t) local s = {} for i,v in ipairs(t) do s[v] = i end -- key value is index return s end function contains(t,e) return t[e] end function indexof(t,e) return t[e] end t = OrderedSet{"abc", "def", "ghi"} if contains(t,"def") then print (indexof(t,"def")) end --> 2
出于历史参考,以下是上述部分代码的 Lua 4 版本。
function contains(t,e) for i=1,getn(t) do if t[i]==e then return 1 end end return nil -- element not found, return false end t = { "abc","def","ghi" } print (contains(t,"def")) -- gives you 1 (true)
function makeDict(t) local d={} for i=1,getn(t) do d[ t[i] ]=1 end return d -- return dictionary we have created end function contains(t,e) return t[e] end t = makeDict { "abc","def","ghi" } print (contains(t,"def")) -- gives you 1 (true) print (t["def"]) -- same as above
function makeDict(t) local d={} for i=1,getn(t) do d[ t[i] ]=i end -- key value is index return d end function contains(t,e) return t[e] end function indexOf(t,e) return t[e] end t = makeDict { "abc","def","ghi" } if contains(t,"def") then print (indexOf(t,"def")) end