This is kinda hard to explain, but I want to restart an in pairs()
loop while it’s still running. Like, let’s say the i
would only ever get up to 10. If I wanted to stop the loop at, let’s say, 8, and then reset the loop from 1, so it loops again, how would I do that?
I’ve tried setting i = 0
, because I thought that I might be able to set the iteration from inside the loop, but that didn’t work. Also, because this question is pretty niche/hard to phrase, I wasn’t able to find anything on the DevForum/the internet.
Very simplified version of what I'm trying to achieve
xValues = {
[1]="one",
[2]="two",
[3]="three",
[4]="four",
[5]="five",
[6]="six",
[7]="seven",
[8]="eight",
[9]="nine",
[10]="ten"
}
local count = 0
while count < 10 do count += 1
task.wait()
for i,v in pairs(xValues) do
print("current array number is "..i.." and the current value is "..v)
if count == 8 then
--reset loop from the beginning when this happens
i = 0 --not working
end
end
end
1 Like
Maybe you could use return function? Not sure anyway
1 Like
that’s because you’re setting i = 8
change it to count = 0
Then after setting that it should work.
2 Likes
The count variable isn’t present in my actual code, so this wouldn’t work for me. I just put it in the example code for simplicity’s sake. My actual code is checking to see if a number is the same as any number that’s present in a table, and if it is, it randomizes it. I then need it to check against every number in the table again.
Edit: I also made a typo in the example code, I meant to say i = 0
, not i = 8
. It’s fixed now though.
Alright, then you’d want to use the continue
keyword.
Instead of i = 8
just use continue
I’m not too familiar with it’s use so it may not work.
I’m trying to basically set i = 0
, not i = 8
. I made a typo in my original post, but it’s fixed now. I just need it to restart the loop as if it had just begun from the first iteration.
Sorry for the poor communication here!
No problem.
Then the quickest method is moving the pairs
loop into it’s own function so you can use break
function PairLoop(xValues)
for i,v in pairs(xValues) do
if i == 8 then
break -- Next while loop iteration will start from beginning.
end
end
end
while task.wait() do
PairLoop(xValues)
end
4 Likes
This is exactly what I was looking for, thank you so much!! I’ve been struggling on this for a few hours now, so this is an absolute life-saver!
No problem, glad I could help.
1 Like