Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Lua
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Functions === Lua's treatment of functions as [[first-class function|first-class]] values is shown in the following example, where the print function's behavior is modified: <syntaxhighlight lang="lua"> do local oldprint = print -- Store current print function as oldprint function print(s) --[[ Redefine print function. The usual print function can still be used through oldprint. The new one has only one argument.]] oldprint(s == "foo" and "bar" or s) end end </syntaxhighlight> Any future calls to <code>print</code> will now be routed through the new function, and because of Lua's [[Scope (programming)#Lexical scoping|lexical scoping]], the old print function will only be accessible by the new, modified print. Lua also supports [[Closure (computer programming)|closures]], as demonstrated below: <syntaxhighlight lang="lua"> function addto(x) -- Return a new function that adds x to the argument return function(y) --[[ When we refer to the variable x, which is outside the current scope and whose lifetime would be shorter than that of this anonymous function, Lua creates a closure.]] return x + y end end fourplus = addto(4) print(fourplus(3)) -- Prints 7 --This can also be achieved by calling the function in the following way: print(addto(4)(3)) --[[ This is because we are calling the returned function from 'addto(4)' with the argument '3' directly. This also helps to reduce data cost and up performance if being called iteratively.]] </syntaxhighlight> A new closure for the variable <code>x</code> is created every time <code>addto</code> is called, so that each new anonymous function returned will always access its own <code>x</code> parameter. The closure is managed by Lua's garbage collector, just like any other object.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)