I am trying to implement a sort of decorator pattern in Lua, and along the way I have run into an issue regarding lambda functions calling themselves.
The following code runs fine:
local function foo()
print("bar")
foo()
end
foo()
However the following is not allowed:
local foo = function ()
print("bar")
foo()
end
foo()
The interpreter throws the following error:
Exception has occurred: main.lua:27: attempt to call a nil value (global 'foo')
stack traceback:
main.lua:27: in local 'foo'
main.lua:30: in main chunk
[C]: in ?
The lua documentation states that "the usual way to write a function in Lua, like function foo (x) return 2*x end
is just an instance of what we call syntactic sugar; in other words, it is just a pretty way to write foo = function (x) return 2*x end
", so it seems to me these should be equivalent.
What am I missing?
CodePudding user response:
in other words, it is just a pretty way to write
foo = function (x) return 2*x end
Yes, that's how function
works. local function
works slightly differently.
The problem is that the compiler doesn't know that the foo
named in the function is a local variable, because the full declaration of the local variable foo
has not yet been completed. And that only happens at the end of the entire local function
statement; until then, foo
would refer to a global variable.
To prevent this, local function X <stuff>
is syntactic sugar for two statements: local X; X = function <stuff>
. You can do the same thing if you like, but the declaration of the local variable has to be a statement separate from the function expression itself.