Sto leggendo il libro programming in Lua
. Diceva che
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
Sembra che se chiamo digitButton
, restituirà action
(questo creerà una chiusura), quindi, posso accedere a digit
passato a digitButton
.
La mia domanda è questa:
Why we need call back functions? what situations can I apply this to?
L'autore ha detto:
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.
secondo l'autore, penso che un esempio simile sia come questo:
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()
quindi the callback can be called a long time after digitButton did its task and after the local variable digit went out of scope.