[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Getting the "ID" of an object.
- From: Lorenzo Donati <lorenzodonatibz@...>
- Date: Mon, 02 May 2011 20:58:42 +0200
On 02/05/2011 10.49, Eike Decker wrote:
> 2011/5/2 Lorenzo Donati<lorenzodonatibz@interfree.it>:
>> 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)
>
> You can modify 1) a bit to make it less performance critical:
>
> do
> local idcnt = 0
> local idcache = setmetatable({},{__mode='k',__index = function(t,k)
> idcnt = idcnt + 1 t[k] = idcnt return idcnt end})
> function getid (o) return idcache[o] end
> end
>
> So this would only affect performance for debug code that tags objects
> if you take a look at them.
Nice technique.
I think Hisham's suggestion suits my needs better, but this technique is
really worth remembering for future reference.
Interesting way of implementing lazy initialization using the subtleties
of metamethods call sequence.
>
> Aside from this, I don't know any other trick. Well, you could also
> erase the metatable, get the string and restore the original metatable
> again.
Well, I thought of this, but it seemed a bit drastic approach to me. I
feared it could have some nasty side effects. Just a feeling, though -
the only downside of erasing the metatable of which I can think in a
rational way is something related to what Mike Pall mentioned in another
thread: IIRC there is some form of caching for metatables/metamethods,
so erasing the metatable could maybe thrash the cache.
I still feel the metatable of an object is something to be left alone
once set whenever possible, but I must admit that maybe this is only an
irrational feeling due to my past experience on "static" languages like
C++/Java.
>
> And besides all that: You could look into the Lua code and find out,
> how the table:#xxx code looks like and provide it as additional
> function if you have access on the C API. E.g. table.getpointerid
>
Well, I'm not completely unaware of C, but I don't feel competent enough
to tinker with the bowels of Lua. I wrote a couple of toy extensions
using Lua C API, just to play with the API and refresh my C knowledge,
but I really prefer a pure Lua solution. I feel on much safer ground there.
> Cheers,
> Eike
>
>
>
Thanks for the suggestions.
Cheers
--
Lorenzo