示例工程 08-table-structure
08-table-structure/04-iteration-order/main.lua
-- @runtimes lua54 luajit
--- 演示:pairs 顺序不确定;应比较集合而不是顺序。
local M = {}
--- @return table { keys = table, sorted = table, has_all = boolean }
function M.run(log)
log = log or print
local t = { alpha = 1, beta = 2, gamma = 3 }
local keys = {}
for key in pairs(t) do
keys[#keys + 1] = key
end
local sorted = { table.unpack(keys) }
table.sort(sorted)
log(("keys=%s"):format(table.concat(keys, ",")))
log(("sorted=%s"):format(table.concat(sorted, ",")))
return { keys = keys, sorted = sorted, has_all = #sorted == 3 }
end
if not ... then
M.run()
end
return M