示例工程 02-values-and-types

02-values-and-types/01-truthiness-table/main.lua

lua · 0.7 KB

-- @runtimes lua54 luajit
--- 演示:只有 nil 与 false 为假;0、空串、空表都为真。
 
local M = {}
 
--- 返回每个候选值的真值判断。
--- @return table { rows = table }
function M.run(log)
	log = log or print
	local candidates = {
		{ label = "0", value = 0 },
		{ label = '""', value = "" },
		{ label = "{}", value = {} },
		{ label = "false", value = false },
		{ label = "nil", value = nil },
	}
	local rows = {}
	for _, item in ipairs(candidates) do
		local truthy = item.value and true or false
		rows[#rows + 1] = { label = item.label, truthy = truthy }
		log(("%s -> %s"):format(item.label, tostring(truthy)))
	end
	return { rows = rows }
end
 
if not ... then
	M.run()
end
 
return M