This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Kasea's profile picture

Question about for loops

Started by Kasea, 18 January 2014 - 02:36 PM
Kasea #1
Posted 18 January 2014 - 03:36 PM
Hello, i was wondering if it's possible to make the variables in for loops global, if yes how? if no what kind of loops offer global variables?

thx :D/>
wieselkatze #2
Posted 18 January 2014 - 04:16 PM
In your code you could just have sth. like


for i = 1, 16 do
a = i --Your global variable
end

or just call your function (I think that's the point) with the for variable as an argument
Kasea #3
Posted 18 January 2014 - 04:42 PM
no dude, i mean like i wanna use the "i" later on, after the end, for like x like x=i+2, 1, -1

Also please explain what you posted, cus without it explained i'm lost :S
wieselkatze #4
Posted 18 January 2014 - 04:46 PM
Why would you need that?
If you define your loop for "i" you either say for i = 1, 12 do and you could just say for x = 14, 1, -1 or if you use variables like

for i = 1, yourtarget do

then it would look like this

for x = yourtarget+2, 1, -1

Else I wouldn't get the point of this

The think in my previous post was meant for function calls, so if you want to call your function with i, i would be local (only in the loop)
Edited on 18 January 2014 - 03:47 PM
Kasea #5
Posted 18 January 2014 - 04:48 PM
i need it for my program, to make it easier, now is it possible or not? or i gotta find another solution?
wieselkatze #6
Posted 18 January 2014 - 04:55 PM
I don't know, if it's possible when I don't even know what you mean exactly. :P/>
Lyqyd #7
Posted 18 January 2014 - 06:01 PM
You can't use a for loop for this. You can do dumb tricks like:


local i = 1
repeat
  --loop body
  i = i + 1
until i == 5
Kasea #8
Posted 18 January 2014 - 08:39 PM
thanks for the answers, but i worked around it
surferpup #9
Posted 21 January 2014 - 04:16 PM
I thought you could do (turns out I was wrong):

local i =0
for i=1,5 do
  print (i)
end
print ("I is now "..tostring(i))

Update: I tested my theory. As it turns out, this does not work. Following the end of the for loop, i returns to a value of 0,which is the value of the original local i. So, the for loop creates its own version of a local variable for purposes of the loop. When the loop ends, the local version created by the for loop falls out of scope. While it is possible to assign that variable to another, it is not possible to obtain the final value of the the for loop variable in this manner.

Lyqyd is correct (as usual).
Edited on 21 January 2014 - 03:30 PM