3

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
No Name
  • 116
  • 7

3 Answers3

2

I'm not sure how you set the metamethod, but the following code prints "stringified" for me:

local aTable = {a = 1, b = 2}
setmetatable(aTable, {__tostring = function() return "stringified" end})
print(aTable)
Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
2

__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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
2

If you want lua to generally print all tables human readable, you could hook up/overwrite the print function:

local orig_print = print

print = function(...)
  local args = {...}
  for i,arg in ipairs(args) do
    if type(arg) == 'table' then
      args[i] = serialize(arg)
    end
  end
  orig_print(table.unpack(args))
end

serialize could be serpent or some other lib from here

Note that this must be done before any other module/script is loaded.

lipp
  • 5,586
  • 1
  • 21
  • 32