While there are some definite head-turning elements in PICO that help game writers, occasionally I will come across something - strange.
And this is one of them.
cls() for i=0,3 do for j=0,3 do print(j.." "..i) end end print"" print(i) print(j) -- ^ nil ??
That's right, if you run this, instead of getting "4" and "4" for the end it gives NIL.
What gives ?? Is FOR (variable) even using a variable ?
Nope, that works exactly as it should — In Lua (and therefore PICO-8), and some other languages (most I know), the variable you use to increment 'for' is temporary and stored separately from a normal variable with the same name.
Try running this:
cls() i=0 j=4 for i=0,3 do for j=0,3 do print(j.." "..i) end end print"" print(i) print(j) --should returns this: --> 0 --> 4
Here's a decent scope tutorial in the Lua wiki that (briefly) mentions for loops: http://lua-users.org/wiki/ScopeTutorial In terms of scopes, Lua uses block scopes for variables declared local, and for loops declare their control variables as local in their block scope automatically. I would agree that this is slightly confusing because Lua variables otherwise refer to outer scopes unless explicitly declared local.
So ... thinking. I really can use any 'variable' I want in a for/next loop. Let me try something ...
Well, that answers that. There is NO need to define a variable as LOCAL if it is only going to be used in a FOR/NEXT loop.
The contents of the variable prior and after remain undefined if it is not earlier initialized as a standard variable.
[Please log in to post a comment]