There are two ways to declare a local function directly.
local var = function()
end;
and
local function var()
end
What's the difference between them?
There are two ways to declare a local function directly.
local var = function()
end;
and
local function var()
end
What's the difference between them?
The difference is how the local variable can be accessed by its own value (currently a function).
First you need to know that the declaration of a local variable is not available in its entire scope and can duplicate, without problems. The following statements can reference previously declared locations, or environment (global) fields ( _ENV[nomeDaLocal]
on Lua 5.2).
Finally, a simple feature.
Case types when a function declared in the local f = function() end
model tries to access it using f
, but fails:
# 1
local f = function()
print(f) -- nil, mas deveria ser a função
end -- nessa local f.
f()
# 2
local f = 0;
local f = function()
print(f) -- 0
end
f()
# 3
f = 0;
local f = function()
print(f) -- 0 também
end
f()
The special syntax local function f() end
creates a local variable with the name f
, and a function for it, a function that pulls its presence.
# 1
local function f()
print(f) -- ok
end
# 2
local f;
local function f()
print(f) -- ok
end
Quoting the manual :
The command
local function f () corpo end
is translated to
local f; f = function () corpo end
Not for
local f = function () corpo end
(This only makes a difference when the body of the function contains references to f
.)