lua-users home
lua-l archive

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


2011/5/2 Lorenzo Donati <lorenzodonatibz@interfree.it>:
> Yes, I know that I can use tables as keys, thanks.
> I need the ID only for debugging/logging purposes, just to build a more
> detailed string representation of an object and tell apart two objects which
> may happen to have the same "content", but different identity (say, for
> example, two complex numbers having the same cartesian components).

You can also easily generate an id on the fly. For example you can use
the following tostring metamethod:

local ids = setmetatable({}, {__mode='k'})

function mt.__tostring(self)
  local id = ids[self]
  if not id then
    id = {}
    ids[self] = id
  end
  return tostring(id):gsub('^%w+: ', 'mytype: ')
end

Ids are only created when used, and become collectable whenever the
object itself gets collected. You can try to replace the empty table
with a zero-sized userdata (call newproxy) to save some memory.