lua-users home
lua-l archive

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

On 02/05/2011 7.16, Hisham wrote:
On Mon, May 2, 2011 at 1:56 AM, Lorenzo Donati
<>  wrote:


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)


Right! Nice trick! Thanks!

I really didn't think of such a solution. My mindset is still too accustomed to classical OOP behaviour of languages like Java & C++ (changing the methods of an object at runtime - really weird from such languages' standpoint!).

I really wouldn't call it a hack: it just uses the dynamic nature of Lua. Now that I see it I find it rather clean and elegant (unless I miss something, such as hidden side effects or loopholes).

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

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).

Thank you very much for the suggestion.