集合初始化

数组和集合 / 集合(Set)

-- An item is a key, true marks that it is there
local int_set = {[2] = true, [3] = true,
                 [5] = true}
local str_set = {one = true, two = true,
                 three = true}
local has_three = int_set[3]
-- has_three = true
local has_two = str_set.two
-- has_two = true

-- From a list: repeats collapse into one key
local numbers = {1, 2, 2, 3, 3, 3}
local from_list = {}
for _, number in ipairs(numbers) do
  from_list[number] = true
end
local keys = {}
for key in pairs(from_list) do
  keys[#keys + 1] = key
end
-- pairs promises no order: sorted to print
table.sort(keys)
-- keys = 1, 2, 3

print("has_three = " .. tostring(has_three))
print("has_two = " .. tostring(has_two))
print("keys = " .. table.concat(keys, ", "))