lua-users home
lua-l archive

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




On Tuesday, September 4, 2012 at 4:41 PM, Coda Highland wrote:

On Tue, Sep 4, 2012 at 1:37 PM, James Norton <jamesnorton@gmail.com> wrote:
I'm sure this must be a pretty common situation, but I can't seem to find a
solution anywhere. Pointers to an existing solution would be greatly
appreciated.

I have implemented a callback system that lets users register Lua functions
as handlers/listeners for events received by objects like this:

local myListener = function(event)

-- do something here

end


someObject:addEventListener("myEvent", myListener)



Internally, my C code calls luaL_ref to get a reference to the callback
function and then stores that reference in an array of callbacks associated
with the event, in this case "myEvent". These references are then used to
call the handlers when the event occurs.

This works fine, but I want to be able to remove the listener using the same
syntax:

someObject:removeEventListener("myEvent", myListener)

The problem with this is that I can't think of a way to associate the
function on the stack at this point (myListener), with the reference I
stored earlier. Calling luaL_ref again with the same function simply
generates a new reference. So apparently I need to store something else to
identify the listener in addition to the reference, but I'm not sure what.

Any suggestions would be greatly appreciated.

Thanks,

James
--
James Norton
Sent with Sparrow

I would create a table and store it in the registry, with the keys
being the callback functions and the values being the registry index
you got earlier.

/s/ Adam
Thanks for the quick reply.  That's actually a great idea.  Even better, I probably don't need to create a separate table as I have a uservalue table attached to each object.  I can store them there.  Come to think of it, I would not need to call luaL_ref at all if I am storing the functions in the table.

-- 
James Norton
Sent with Sparrow