joh*_*ell 1 lua metatable lua-table
是否可以在Lua中不使用元表打印表格?
在Roberto的" Lua编程 " 一书中,他提到"函数print始终要求tostring格式化其输出".但是,如果我tostring在我的表中覆盖,那么我得到以下结果:
> a = {}
> a.tostring = function() return "Lua is cool" end
> print(a)
table: 0x24038c0
Run Code Online (Sandbox Code Playgroud)
没有元表就无法做到.
该函数
tostring格式化其输出.
你误解了这一点.这里tostring是函数tostring,而不是表的字段.所以这意味着它print(t)会调用print(tosstring(t)),就是这样.
对于表格,tostring(t)将查找是否具有元方法__tostring,并将其用作结果.所以最终,你还需要一个metatable.
local t = {}
local mt = {__tostring = function() return "Hello Lua" end}
setmetatable(t, mt)
print(t)
Run Code Online (Sandbox Code Playgroud)