示例工程 12-iterators

12-iterators/04-next-direct/main.lua

lua · 0.5 KB

-- @runtimes lua54 luajit
--- 演示:直接用 next 遍历,以及 pairs 只是 next 的包装。
local M = {}
 
--- @return table { count = integer, keys = table }
function M.run(log)
	log = log or print
	local t = { a = 1, b = 2 }
	local keys = {}
	local key, value = next(t)
	while key ~= nil do
		keys[#keys + 1] = key .. "=" .. tostring(value)
		key, value = next(t, key)
	end
	table.sort(keys)
	log(("count=%d keys=%s"):format(#keys, table.concat(keys, ",")))
	return { count = #keys, keys = keys }
end
 
if not ... then
	M.run()
end
return M