In javascript, one can quickly create closures by defining and calling a function at the same time like this:
function() {
local something = 1;
return function () {
// something
}
}()
Is it possible to do the same in lua
?
Yes, you can create immediately invoked function expressions (IIFEs) in Lua. Lua requires parentheses around the function expression: (function () return 10 end)()
. Remove the parentheses, function () return 10 end()
, and you get a syntax error. And naming the function is impossible: (function f() return 10 end)()
. The named function syntax is syntactic sugar for assigning the function to a variable, f = function() return 10 end
, and assignments are not expressions in Lua so they cannot be called as functions.
JavaScript requires parentheses either around the function expression or around the whole function plus function-call parentheses combination: (function () { return 10; })()
or (function () { return 10; }())
. Parentheses ensure that function () {}
is interpreted as a function expression rather than a function declaration. The equivalent of the second construction, (function () return 10 end())
, is invalid in Lua. In JavaScript but not Lua, you can provide a name in function expressions, and the name will be shown in stack traces in case of an error: (function f() { return 10; })()
or (function f() { return 10; }())
.