button.action = function() buttonPressed() end< /pre>Is it the same?
button.action = buttonPressed() end?
I know that button.action is given the value returned by buttonPressed(), but why should it be wrapped into such an anonymous function?
You got it wrong. The statement:
button.action = function() buttonPressed () end
Assign button.action to an anonymous function, which will execute the call buttonPressed() in turn when called. Please note that the anonymous function does not return anything, so it is only called for its side effects It. This is a common idiom for callbacks. You use anonymous functions to delay the execution of some code (in this case, just call buttonPressed) until you need to execute it.
Given your code The name of the fragment, I guess this code sets the action to be performed when a certain button is pressed. When the button is pressed, the action is triggered (There will be a call somewhere inside the code, such as the button.action() call stored in Anonymous function in button.action) and execute the call buttonPressed().
I am learning Lua and encountered the following construction:
button.action = function() buttonPressed() end
Is it the same?
button.action = buttonPressed() end
?
I know that button.action is given the value returned by buttonPressed(), but why should it be wrapped into such an anonymous function?
"I know button.action is assigned the value returned by buttonPressed(), but why should it be wrapped into such an anonymous function?"
You got it wrong. The statement:
button.action = function() buttonPressed() end
.action is assigned to an anonymous function, which will be executed in turn when called. ButtonPressed() is called. Note that the anonymous function does not return anything, so it is called only for its side effects. This is a common idiom for callbacks. You use An anonymous function to delay the execution of some code (in this case, just call buttonPressed) until you need to execute it.
Given the name of your code snippet, I guess this code sets the press The action to be performed when a certain button is pressed. When the button is pressed, the action is triggered (somewhere inside the code, there will be a call, such as button.action() calls the anonymous function stored in button.action) and executes the call buttonPressed ().