It looks like you're new here. If you want to get involved, click one of these buttons!
loves_oi
Member
function x() y = 3 function z() u = 5 print (u) end local a = 3 local function b() c = 5 print (c) end end print (z()) ---error print (y) ---error |
Dislikes: Yan
Comments
Likes: atilim
It's important to realise that Lua does not "look ahead" and initialise global variables before it processes a file. Global variables are available anywhere but are not auto-initialised in any way. For instance
The other thing to notice is that functions are first class values in Lua, they are not special like in other languages. The statement
https://github.com/gideros/gideros
https://www.youtube.com/c/JohnBlackburn1975
https://github.com/gideros/gideros
https://www.youtube.com/c/JohnBlackburn1975
If you put the local function bar() before the function foo() it'll work - this is "I think" because when the parser pre-compiles foo it can't find bar (it's not been defined yet) and so assumes it's a global bar it's looking for.
So the fact that you then have a local bar is irrelevant as foo's already looking for the global one.
If you declare bar first (either global or local) then foo will know that bar exists within the current scope and thus generate the correct code.
At least that's my (current) understanding.
#MakeABetterGame! "Never give up, Never NEVER give up!" - Winston Churchill
Lua has no problem compiling functions which call other functions which are currently nil. It's only when a function is actually called that it needs to be defined.
The reason foo cannot access bar when its called is because functions only have access to three things:
1) Their arguments
2) global variables
3) Their upvalues
Upvalues, or "external local variables" are local variables outside the scope of the function and defined before the function. The example can be fixed if we add the line local bar
Upvalues and closures are among the most complex features of Lua. Personally I just declare all functions as global to avoid this sort of problem.
https://github.com/gideros/gideros
https://www.youtube.com/c/JohnBlackburn1975
#MakeABetterGame! "Never give up, Never NEVER give up!" - Winston Churchill
It also helps me to avoid creating too many global variables/functions.
Edit : same as you said, @techdojo