lua-users home
lua-l archive

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


Andreas Falkenhahn wrote:

Hi,

I've a question concering callback functions that do not get deleted
after they were passed to a function. Imagine the following code:

createbutton("About", function() print("About button clicked!") end)

The createbutton() function is a function that I've implemented in C.
Now the question is: How do I preserve the function that the user
passed to my createbutton() function? IIRC, lua would normally
delete the function I passed as parameter 2 because it is not needed
any more after createbutton() returns. But this is not the case in
this specific example because createbutton() just creates a button
and does not need to call the function specified but it needs to
store it somewhere.

I somehow need to store the function that the user passed
(in this case: function() print("About button clicked!") end), tell
lua that it should not delete it and I must be able to call it later
when that button is clicked. How can all this be done?

Is there any documentation about how to implement callback
functions which must stay valid _after_ the function that they were
passed to exited? Or example code?

I saw in the lua book in chapter 6.1 that there is an example
just like mine above but it does not tell me how to implement those
callbacks on the C side.

Perhaps with something like that:
callbacks = {}

function CreateButton(buttonName, callbackFunction)
  callbacks[buttonName] = callbackFunction
end

function ClickOnButton(buttonName)	-- Simulate user clicking
  callbacks[buttonName]()
end

CreateButton("About", function () print"I did this!" end)
CreateButton("DoIt", function () for i = 1, 10 do print(i) end end)

ClickOnButton("About")
ClickOnButton("DoIt")

You need to do this on the C side, but the idea is here: the function is given as parameter and you can store it, perhaps in a global table like I did, or perhaps in the Lua registry, which is used to store data that must not be garbage collected. As long as the function is referenced somewhere (table, registry, etc.), it won't be garbage collected.

Well, if I didn't missed anything... Seasoned Lua programmers will correct me if I gave wrong informations :-P

--
Philippe Lhoste
--  (near) Paris -- France
--  http://Phi.Lho.free.fr
--  --  --  --  --  --  --  --  --  --  --  --  --  --