introspection in Lua

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

introspection in Lua

Max Ischenko
I'm writing routines for saving/restoring Lua table to/from file
and I have the question:
How can I find out the name of object from the object, i.e

foo={}
print(?) -- must print 'foo'


-- 
With your bare hands?!?

Reply | Threaded
Open this post in threaded view
|

Re: introspection in Lua

Luiz Henrique de Figueiredo
>I'm writing routines for saving/restoring Lua table to/from file

See also lua/test/save.lua.

>How can I find out the name of object from the object, i.e
>
>foo={}
>print(?) -- must print 'foo'

If foo is a global variable, then you can search the table of globals:

 local obj=get_object_somehow()
 name=foreach(globals(), function (i,v) if v==%obj then return i end end)

This will find *one* name for the object, not necessarily the one you expect.
For instance, if you do "xyz=print", then the code above may return "print"
or "xyz". If you want all names, then you can collect them in a table.

Anyway, objects in Lua are really anonymous, much like files in Unix.
They can have several global names or none at all, for they can be fields
of a table. When no other object points to them, they are deleted.

--lhf

Reply | Threaded
Open this post in threaded view
|

Re: introspection in Lua

Steve Dekorte-4
In reply to this post by Max Ischenko
Max Ischenko wrote:
> I'm writing routines for saving/restoring Lua table to/from file 
> and I have the question: 
> How can I find out the name of object from the object, i.e 

One solution(if I understand your question correctly) is to store the 
name of the object/class in it's table:

Dog = {}
Dog["_name"] = "Dog"

Steve

Reply | Threaded
Open this post in threaded view
|

Re: introspection in Lua

Max Ischenko
	Hi there, Steve Dekorte!
	On Thursday, 14 of December you wrote:

> 
> Max Ischenko wrote:
> > I'm writing routines for saving/restoring Lua table to/from file 
> > and I have the question: 
> > How can I find out the name of object from the object, i.e 
> 
> One solution(if I understand your question correctly) is to store the 
> name of the object/class in it's table:
> 
> Dog = {}
> Dog["_name"] = "Dog"
> 

Yes, I came to it.
It's a pity that Lua doesn't have powerful introspection mechanism like
tcl's `info' command, but on the same time Lua much more efficient than Tcl.

-- 
Best regards, Maxim F. Ischenko.