[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Getting the "ID" of an object.
- From: Lorenzo Donati <lorenzodonatibz@...>
- Date: Mon, 02 May 2011 06:56:32 +0200
I recently stumbled on an issue I cannot find a workaround for.
When defining the __tostring metamethod for a a table, the old behaviour
is completely lost, i.e. there is no "rawtostring" and no apparent way
to concoct a substitute (without resorting to C).
What I'd like is a way to get the unique IDs (I suppose they are the
memory address) that Lua generates for the default string representation
of tables, i.e. the NNN in
tostring(t) --> "table: NNN"
It doesn't seem that the debug library helps here either.
I need the "NNN" above to include that ID into the string representation
for my OOP objects when defining __tostring.
I know that I could either:
1) generate an unique ID with a custom algorithm
2) upon creation, before attaching the metatable to the object being
created, call tostring on the object and store the ID in a (weak?) table.
3) use a proxy and return the ID of the "private" object instead
(preserves uniqueness because of the 1-to-1 relationship between proxies
But both these approaches are lots of boilerplate code and/or useless
overhead (the logic for that ID is already somewhere in the bowel of Lua
- it just need a way to be exposed cleanly).
I wonder if there is a nifty trick to recover that NNN only when needed
without too much overhead or code.
If not, why not adding a new method to the debug library, such as
"debug.getid". Maybe it could be useful in other contexts and it
shouldn't be to "heavy" to implement (just expose what's already in
Lua). I see that upcoming Lua 5.2 has a debug.upvalueid. Maybe rename it
as debug.getid and make it applicable to any Lua object? Wouldn't it be
more in Lua spirit (less functions, with more general application)?
Or even enhance debug.getinfo to give info also on tables (and other
Or, still another option, add a second return value to "type" (I admit
that this solution is maybe not very clean semantically).