Assuming I have a piece of code such as the following
aTable = {aValue=1}
aTable_mt = {}
print(aTable)
What must I do to make Lua print something like aTable current aValue = 1
as opposed to table: 0x01ab1d2
.
So far I've tried setting the __tostring
metamethod but that doesn't seem to be invoked by print
. Is there some metamethod I've been missing or does the answer have nothing to do with metamethods?
__tostring
works:
aTable = {aValue=1}
local mt = {__tostring = function(t)
local result = ''
for k, v in pairs(t) do
result = result .. tostring(k) .. ' ' .. tostring(v) .. ''
end
return result
end}
setmetatable(aTable, mt)
print(aTable)
This prints aValue 1
(with one extra whitespace, remove it in real code). The aTable
part is not available, because aTable
is a variable that references the table, not the content of the table itself.