感谢所有Lua stackoverflow人员,他们讨论了如何自定义打印表.经过多次阅读,我发布以下内容并询问Lua大师....
请注意以下内容:
metatable为每个对象添加大小.我的方法重写了默认tostring方法.
_tostring = _tostring or tostring
function tostring(t)
if type(t) == "table" then
status, stuff = pcall(function() return t:s() end)
if status then
return stuff
end end
return _tostring(t)
end
Run Code Online (Sandbox Code Playgroud)
以上是一个有点邪恶(调用pcall ...不是我最自豪的代码,但是,嘿,它的工作原理).
无论如何,现在tostring让方法调用t:s()一个我们可以使用以下自制对象系统定义的对象:
Object={}
function Object:new(o)
o = o or {}
setmetatable(o,self)
self.__index = self
return o
end
Run Code Online (Sandbox Code Playgroud)
这是默认定义:s()- 可以在子类中自定义.
function Object:s()
-- can be customized in subclasses
local out,sep="{",":"
for x,y in …Run Code Online (Sandbox Code Playgroud)