lua-users home
lua-l archive

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

luaL_ref simply finds a suitable integer number (one that hasn't been
"taken" by other references) and then assigns the referenced value to
the registry table under this integer key.  The registry table is just
a normal table in Lua so the GC handles it just like any other value
that has been stored in a table (which by the way is what globals are
since the globals table where they're stored is just another normal
table).  That's the cool part about Lua it makes heavy use of just a
small set of concepts and mechanisms so after a (short) while you can
deduce what the semantics should be logically (instead of reading the
manual/reading the code/asking on the list etc.)


On Tue, May 8, 2012 at 1:23 PM, Rena <> wrote:
> On Tue, May 8, 2012 at 4:22 AM, Tezduyar Lindskog, Umut
> <> wrote:
>> Hi Rena, Rob, Kevin,
>> Thank you very much for the quick response. It worked like charm. I have further question. Does GC take into account the fact that we are holding a reference to a function?
>> Thanks
>> -----Original Message-----
>> From: [] On Behalf Of Rob Hoelz
>> Sent: Tuesday, May 08, 2012 10:10 AM
>> To: Lua mailing list
>> Subject: Re: Is it possible to store lua function in a C struct?
>> luaL_ref should handle your needs quite nicely:
>>  /* with your function on the top of the stack */
>>  int ref = luaL_ref(L, LUA_REGISTRYINDEX);
>>  /* squirrel away ref in your struct */
>>  /* later on... */
>>  lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
>>  /* your function is once again on the top of the stack! */
>> -Rob
>> On Tue, May 08, 2012 at 10:02:28AM +0200, Tezduyar Lindskog, Umut wrote:
>>> Hi all,
>>> Is it possible to store lua function in a C struct and later call lua function from C using the stored information?
>>> I am looking for an implementation as following:
>>> void* myluafunc = luaL_checkluafunction (L, 1);
>>> lua_pushfunctionptr (L, myluafunc);
>>> lua_call (L,0,0);
>>> I have implemented a workaround where lua function's name is stored in a char array in C and then later on lua function is called using following APIs. This way is working fine but using function name as the identifier is using extra memory.
>>> char name[128];
>>> int button_lua_new (lua_State *L)
>>> {
>>>    const char* myluafuncname = luaL_checkstring (L,1);
>>>    strcpy (name, myluafuncname);
>>> }
>>> void call_button_event_handler ()
>>> {
>>>   lua_getglobal(L, name);
>>>   lua_call (L,0,0);
>>> }
>>> Thanks
> Yes. It won't be deleted until you use luaL_unref to free the reference.
> --
> Sent from my Game Boy.