lua-users home
lua-l archive

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


On Sun, Oct 18, 2009 at 11:35 PM, Geoff Leyland
<geoff_leyland@fastmail.fm> wrote:
> Hi,
>
> Has anyone got a better idea for getting the address of a table with a
> __tostring in its metatable than this?
>
>> a = setmetatable({}, { __tostring = function() return "pretty but no
>> address" end})
>> print(a)
> pretty but no address
>> function rawtostring(t) local mt = getmetatable(t) setmetatable(t, nil)
>> local r = tostring(t) setmetatable(t, mt) return r end
>> print(a, rawtostring(a), a)
> pretty but no address   table: 0x115150 pretty but no address
>
> It works, but it's a bit mucky.
>
> Cheers,
> Geoff
>
>

Not if the metatable has __metatable set to protect it from being
changed. In that case, you could use
debug.getmetatable/debug.setmetatable instead.

If you have access to the C API rather than looking for a pure-Lua
solution, you could add a Lua function that wraps lua_topointer() to
get the pointers for objects. I think this:

  lua_pushfstring(L, "%p", lua_topointer(L,1));

...should push a string onto the stack in the same format as the
pointer returned by the default tostring.

-Duncan