Log In  

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 ?

P#31542 2016-10-23 10:53 ( Edited 2016-10-23 20:05)

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
P#31549 2016-10-23 12:03 ( Edited 2016-10-23 16:03)

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.

Other popular scripting languages use different scoping rules. Especially watch out for Python (function scope, local by default on assignment) and JavaScript (with "var," function scope, global by default). ECMAScript 6's "let" declarations are closer to Lua's "local."

P#31558 2016-10-23 15:59 ( Edited 2016-10-23 19:59)
:: dw817

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.

P#31559 2016-10-23 16:05 ( Edited 2016-10-23 20:05)

[Please log in to post a comment]

Follow Lexaloffle:        
Generated 2022-09-30 20:09:29 | 0.008s | Q:13