[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Question about __gc metamethod and when the actual value is removed and might it be used before removal
- From: Vyacheslav Napadovsky <napadovskiy@...>
- Date: Wed, 7 Jan 2015 17:42:02 +0300
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.