I have a simple problem: I would like to cause the print function in lua to print the contents of a table, rather than just the word “table” and a memory address. For example:
> tab = {}
> tab[1]="hello"
> tab[2]="there"
>
> print(tab)
table: 0x158ab10
--should be
1 hello
2 there
I am aware that I can get this effect by executing something like:
for i,v in pairs(tab) do print(i,v) end
but I would like it to happen simply when I execute print(tab) rather than having to write out a loop every time. can this be done?
You would need to set __tostring() on every table you created. An easier way would be to use a pretty printing technique.
See this link: http://lua-users.org/wiki/TableSerialization