for example
function foo1()
local i=10 --or just i=10
end
The variable i
is not visible out of the function. So should I declare it as local
explicitly. Or It's already a local
variable.
for example
function foo1()
local i=10 --or just i=10
end
The variable i
is not visible out of the function. So should I declare it as local
explicitly. Or It's already a local
variable.
in Lua, every variable that's not explicitly declared local
(except for arguments, because they are upvalue locals created implicitly by the VM) is a global, so doing this:
function foo1()
i=10
end
foo1()
print(i) -- prints "10"
is exactly the same as:
_G["foo1"] = function()
_G["i"]=10
end
foo1()
print(i) -- prints "10"
which is bad. so you should declare it as:
local function foo1()
local i=10
end
foo1()
print(i) -- prints "nil", so it's local
EDIT: but mind the closure's upvalues. e.g. this:
local function foo()
local i=10
local function bar()
i=5
end
print(i) -- 10
bar()
print(i) -- 5
end
print(i) -- nil
foo()
print(i) -- nil
EDIT 2: also, you should consider making your functions local, so they don't bloat the global table. just declare them as local function ......
tl;dr: just make everything local unless you really have a good reason not to (=never), because that way you can't accidentally collide names. lua making everything global by default is a historical decision that's considered bad practice nowadays. one the reasons i like moonscript because it defaults everything to local (also the syntax is way nicer to me).
upvalue
is a variable that's usable by a function without being declared in that function but also not global. like declaring a local variable in a function that THEN declaring a function that uses the variable. like the i
in my example: it's not global, but because foo
declares it locally before declaring bar
, bar
can use it. –
Caudillo do
... end
, or function
... end
) in which it is defined. upvalues are former local variables whose lifetime has been extended beyond the scope of the defining block by being referenced by a closure (which is just a fancy name for a function referencing local variables defined outside the function's body). Function parameters are local variables until you create a closure which references them in which case they are transformed into upvalues. –
Project This is stated clearly in the online Lua ref manual, section 2.3:
Any variable is assumed to be global unless explicitly declared as a local (see §2.4.7)
When running in the lu54 environment on Windows, not declaring a variable in a function makes it global. For example:
function scope_test()
some_number = 25
end
scope_test()
print(some_number)
results in 25 being printed out.
If local were to be added in front of some_number as below:
function scope_test()
local some_number = 25
end
scope_test()
print(some_number)
The output would be nil.
© 2022 - 2025 — McMap. All rights reserved.
upvalue
mean. What properties does this kind value have? – Rearrange