Is it possible to print a table without using metatables in Lua?
In Roberto's book Programming in Lua, he mentions "The function print
always calls tostring
to format its output". However, if I override tostring
in my table, then I get the following results:
> a = {}
> a.tostring = function() return "Lua is cool" end
> print(a)
table: 0x24038c0
It can NOT be done without metatables.
The function
tostring
to format its output.
You misunderstood this. Here, tostring
is the function tostring
, not a field of a table. So what it means is that print(t)
will call print(tosstring(t))
, that's it.
For tables, tostring(t)
will then find if it has a metamethod __tostring
, and uses that as the result. So eventually, you still need a metatable.
local t = {}
local mt = {__tostring = function() return "Hello Lua" end}
setmetatable(t, mt)
print(t)