I am reading the book programming in Lua
. It said that
Closures provide a valuable tool in many contexts. As we have seen, they are useful as arguments to higher-order functions such as sort. Closures are valuable for functions that build other functions too, like our newCounter example; this mechanism allows Lua programs to incorporate sophisticated programming techniques from the functional world. Closures are useful for callback functions, too. A typical example here occurs when you create buttons in a conventional GUI toolkit. Each button has a callback function to be called when the user presses the button; you want different buttons to do slightly different things when pressed. For instance, a digital calculator needs ten similar buttons, one for each digit. Y ou can create each of them with a function like this:
function digitButton (digit)
return Button{label = tostring(digit),
action = function ()
add_to_display(digit)
end}
end
It seems that if I call the digitButton
, it will return the action
(this will create a closure), so, I can access the digit
passed to digitButton
.
My question is that:
Why we need call back functions? what situations can I apply this to?
The author said:
In this example, we assume that Button is a toolkit function that creates new buttons; label is the button label; and action is the callback closure to be called when the button is pressed. The callback can be called a long time after digitButton did its task and after the local variable digit went out of scope, but it can still access this variable.
according to the author, I think a similar example is like this:
function Button(t)
-- maybe you should set the button here
return t.action -- so that you can call this later
end
function add_to_display(digit)
print ("Display the button label: " .. tostring(digit))
end
function digitButton(digit)
return Button{label = tostring(digit),
action = function ()
add_to_display(digit)
end}
end
click_action = digitButton(10)
click_action()
thus, the callback can be called a long time after digitButton did its task and after the local variable digit went out of scope.