lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, Nov 10, 2009 at 8:57 AM, spir <denis.spir@free.fr> wrote:
> Hello,
>
> Is there any builtin way to output table content? Couldn't find in docs, maybe I'm blind...
> Also, I would enjoy some clues about the reasoning for tostring(t) not doing that by default (and print(t) not writing that). Probably getting the memory address is useful in specific occasions, so there should certainly be a method for this in library "table". But the table content is certainly what we need in most cases, esp. during developpment/testing/debug phases, so that this should be the easiest output to get. Or am I missing something
>
> Below a (superficially tested) example of what I mean. (The func names don't pretend to be best.) Still, I guess the default output for a table should be a (flat) view of its content. Even if big (the programmer knows it).

There is no such standard function, and I believe the main reason is
loops - a table might (directly or indirectly) contain fields that
refer to the table itself. For example, the global variable _G is a
reference to the global variables table itself, so if you try to use
your function to display _G then it will get into an infinite loop
trying to display _G._G._G._G...

Now, of course you can rewrite your print function to keep track of
the hierarchy and stop itself when it detects it is about to go into
an infinite loop. But, what do you output instead? It is not trivial
to be concise, meaningful, unambiguous and fit for all purposes here,
as a standard function would have to be.

One thing you should be also be aware of is that the keys of a Lua
table can be (almost) any value, not only a string. For example, this
would be valid thing to do in T.test():

  local abcd = {a=1, b=2, c=3, d=4}
  circle[abcd] = true

...and would eventually cause an error at 'key .. T.KS', since 'key'
would be a table not a string. Having a representation that displays
tables-as-keys nicely is also not that easy.

-Duncan