How do we change the way print displays a table

南楼画角 提交于 2019-12-10 22:07:10

问题


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?


回答1:


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




回答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)



回答3:


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.



来源:https://stackoverflow.com/questions/29639479/how-do-we-change-the-way-print-displays-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!