Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining and calling function at the same time in lua

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?

like image 562
saga Avatar asked Nov 17 '25 16:11

saga


1 Answers

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; }()).

like image 84
cyclaminist Avatar answered Nov 19 '25 06:11

cyclaminist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!