Disconnect an event in Lua
-
16-03-2021 - |
Question
I was reading a part of the LuaInterface Tutorial (here) and found out that you can associate an event with a function by doing something similar to this:
button.Click:Add(function()
MessageBox.Show("We wuz clicked!",arg[0],MessageBoxButtons.OK)
end)
Now, with this in mind, does anybody know how I would remove an event handler? Say I just want to disconnect the one above. How would I do it?
Solution
Probably the .Net API has a way to remove callbacks or reset the button completely. You should look for that method.
In the meantime, here's a Lua-only ugly hack that should work:
local showMessageWhenButtonClicked = true
button.Click:Add(function()
if showMessageWhenButtonClicked then
MessageBox.Show("We wuz clicked!",arg[0],MessageBoxButtons.OK)
end
end)
When you want to deactivate the message, just do
showMessageWhenButtonClicked = false
(You might need to make showMessageWhenButtonClicked global - removing the "local"- if you are going to deactivate it in a different scope - for example, in another file).
But this is very crude and brutish. Don't use it unless you don't have time to browse the .Net documentation because you are coding to save your life.
OTHER TIPS
First you must name the function:
function button_Click(sender, e)
Then you can set this function to handle the events:
button.Click:Add(button_Click) -- Add event handler
button.Click:Remove(button_Click) -- Remove event handler.