示例工程 16-call-and-tostring

16-call-and-tostring/01-callable-table/main.lua

lua · 0.5 KB

-- @runtimes lua54 luajit
--- 演示:__call 让表可像函数一样调用。
local M = {}
 
local function new(base)
	return setmetatable({ base = base }, {
		__call = function(self, value)
			return self.base + value
		end,
	})
end
 
--- @return table { result = integer }
function M.run(log)
	log = log or print
	local add = new(10)
	local result = add(5)
	log(("result=%d"):format(result))
	return { result = result }
end
 
if not ... then
	M.run()
end
return M