Indeed, but if your read the program, you would see that the variables are declared in the main block of the program, same as the functions which used them. Ergo it should have worked.
Well i think the matter lies with the order of declaration - for example:
If you do this:
local function f()
print(x)
end
f()
x = 6
f()
It will print "5 \n 6"
but if you do
local function f()
print(x)
end
local x = 5
f()
x = 6
f()
it will print "nil \n nil"
because it compiles the code from top to bottom, it sets all not defined variables environments to global - in this case, there doesnt exist any global x! so it return Nil.
To understand that better: this is the way the compiler works:
local x = 5 -- Declare variable x as local -> create new Environment _ENV
local function f()
print(x) -- x translates to _ENV["x"], because it was declared physically beforehead
end
vs
local function f()
print(x) -- "Was it declared beforehand?" -> No -> x translates to _G["x"]
end
local x = 5 -- -- Declare variable x as local -> create new Environment _ENV
(note that there is no actual "current" Environment, it rather accesses the register directly, but for simplicities sake i left it at that)
now you have 2 totally different Environment references:
In the first case, the variable X in the function has the Environment _ENV.
In the second case, the variable X has the global Environment _G
So if you would declare a variable "local chestcokecount" before you declare the function it would be fine. (you can just declare without a value at all)
To give another example:
local function f()
print(x)
end
local x = 8
_G["x"] = 5
f() --> 5
x = 6
print("Local:"..x)
f() --> 6
returns this:
5
Local:6
5