lua-users home
lua-l archive

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

On Mon, May 2, 2011 at 1:56 AM, Lorenzo Donati
<> wrote:
> Hi all!
> 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 and objects)

Besides the options you gave, if what you want is to use the original
tostring() value within your custom __tostring, an option (hack?) is
to temporarily disable your custom __tostring, like this:

local tbl = {}
local meta = {}

local function meta_tostring(t)
   meta.__tostring = nil
   local s = tostring(t)
   meta.__tostring = meta_tostring
   return "Original tostring is "..s
meta.__tostring = meta_tostring

setmetatable(tbl, meta)


In case you're using it for something else, I'd use one of the methods
you mentioned, like the weak table. But make sure you really need the
id -- for most situations where one would use an object id in other
languages, one can simply use the table itself as a key when coding in

-- Hisham