[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Question about __gc metamethod and when the actual value is removed and might it be used before removal
- From: Oliver Kroth <oliver.kroth@...>
- Date: Wed, 07 Jan 2015 16:48:51 +0100
when you sue userdata, the Lua VM will allocate (and free) the memory.
You may possibly go better with light userdata, which is actually a
pointer to something you maintain.
__gc will still be called when the Lua VM does no longer references the
data, but it will not free then memory.
This way you get the chance to let your objects live longe than Lua uses
them, and share the same object among several variables (even in
different Lua VMs if you handle concurrency correctly)
Am 07.01.2015 um 15:42 schrieb Vyacheslav Napadovsky:
I'm trying to integrate lua into my program. I have a bunch of objects
and their userdata's.
Each object's userdata only holds a pointer to a C++ object (4 bytes
on a 32-bit OS).
I use the reference counting system to determine when to delete the
C++ objects (Addref/Release)
(The lifetime of C++ object is longer than Lua userdata)
Every C++ object has its own userdata in Lua. I create userdatas when
needed (and call Addref on the C++ object).
Moreover, if I want to load C++ object into Lua once more I need to
use the same userdata
(to make '==' operator work correctly). For this purpose I've created
a table in LUA_REGISTRYINDEX.
The table has __mode=='v', and when I load object into Lua I check
if (table[this] ~= nil) then -- actually I use lua_rawgetp(L,
table_idx, this) in C++ code
I use userdata from this table
I create lua_newuserdata and save it in this table (lua_rawsetp)
When Lua's userdata __gc metamethod is called I have to decrement the
object reference (Release) and
(probably) clear the reference for the userdata from the table:
table[this] = nil.
The question is: should I do this: table[this] = nil ?
And is that overall a correct way to propagate C++ objects to Lua?
P.S. If I do (table[this] = nil), I sometimes get 2 userdatas pointing
to the same C++ object.
P.P.S. How to get to know that __gc metamethod has been called for
this particular userdata from C code?
I use Lua 5.2.3.