why does
function inc()
x = x + 1
end
x = 0
inc()
print(x)
work, but
function inc()
x = x + 1
end
local x = 0
inc()
print(x)
not work
why does
function inc()
x = x + 1
end
x = 0
inc()
print(x)
work, but
function inc()
x = x + 1
end
local x = 0
inc()
print(x)
not work
Youâre declaring the variable after the function. Declaring it local after the function which uses it will cause it to freak out. I recommend just doing f(x) for incrementing.
function inc(x)
return x + 1
end
local n = inc(0)
print(n)
But when doing what youâre asking, itâs probably best to either not declare it local or declare it local before the function.
local x = 0
function inc()
x = x + 1
end
inc()
print(x)
tl;dr: When inc
is parsed, x
is bound to the global âx
â in both examples. The first example goes on to define a global âx
â, while the second does not.
Lua is a runtime-interpreted language. In other words, functions âdonât existâ until the interpreter reaches their declaration.
The interpreter runs line-by-line from the top of the file to the bottom.
When it sees a function, it creates a âclosureâ for that function, which binds any variables the function uses.
When a variable is bound, the closest-scoped version of that variable is used. If no local variables are available, the global scope is assumed.
So in both your examples, x
is being bound to the global scope, since the interpreter hasnât âseenâ a tighter-scoped x
yet. In the first one thatâs OK because later you actually define a global x
.
In the second one, you define a local x
. Thatâs not going to work, because inc
has already been bound to the global.
Youâll note the error you get on your second one:
attempt to perform arithmetic on global 'x' (a nil value)
Because inc
is looking for a global x
, but it couldnât find one.