lua-users home
lua-l archive

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


On Tue, 2009-11-10 at 14:11 +0100, spir wrote:
Le Tue, 10 Nov 2009 10:35:53 +0000,
Duncan Cross <duncan.cross@gmail.com> s'exprima ainsi:
> 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...

Right.

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

Have no idea how to identify the root table itself (after, I'm a beginner -- but see also (*)) as we get the object, while nested ones can be identified while walking, sure.
As I said, the output needs not be perfect and a simple placeholder like
 <recursion to 'name'> would be fine for me.



That's exactly what 'print_r' does (I use it for debugging):
http://www.hpelbers.org/lua/print_r

It is not intended for serializing, but it's very handy for debugging (or even to see what functions are in a loaded module (just do pr(_G) and scroll around in the output)

require 'print_r'
circle={}
abcd = {a=1, b=2, c=3, d=4, ref=circle}
circle['abcd']= '123'
circle[abcd] = '456'
circle[print] = 'the standard print function'
circle['zorro'] = abcd  -- circular reference
pr(circle, 'my circle'

This prints:

my circle = {
|  function: 0x870a020 = "the standard print function"
|  zorro = {
|  |  a = 1
|  |  c = 3
|  |  b = 2
|  |  d = 4
|  |  ref = {} -- my circle (self reference)
|  }
|  table: 0x870e288 = "456"
|  abcd = "123"
}