示例工程 16-call-and-tostring
16-call-and-tostring/02-tostring-and-name/main.lua
-- @runtimes lua54 luajit
--- 演示:__tostring 与 __name 对错误信息的影响。
local M = {}
local Point = {}
Point.__name = "Point"
Point.__tostring = function(self)
return ("Point(%d,%d)"):format(self.x, self.y)
end
--- @return table { text = string, name = string }
function M.run(log)
log = log or print
local point = setmetatable({ x = 1, y = 2 }, Point)
local text = tostring(point)
local name = getmetatable(point).__name
log(("text=%s name=%s"):format(text, name))
return { text = text, name = name }
end
if not ... then
M.run()
end
return M