Loop always printing 2 instead of incremental numbers

while true do
wait(1)
local p = 1
p = p + 1
print(p)
end

why is this always printing 2, but when i put local p = 1 outside of the loop it prints 2,3,4,5...

since you assigned the variable p as 1 and then changed the variable to
p = p+1 and since p’s previous value was one, you literally added 1+1
you should do this instead

Use a for loop

local p =1
for   p=1,10,1--start at 1, end at 10, increments of 1
do 
	print(p)
end

for it to be infinite , try adding while true do in the beginning

3 Likes

That’s because when local p = 1 is outside the loop, it’s only declared once, and it incremented (added to) by 1 each time the while loop loops.

What the script is doing:
Declare p = 1
Add 1 to p = 2
Add 1 to p = 3
ect.

But when it’s delcared inside of the loops, logically, it is going to be **re-**declared/overwritten each time the loop loops.

What the script is doing:
Declare p = 1
Add 1 to p = 2
Declare p = 1
Add 1 to p = 2
Declare p = 1
and the cycle continues

4 Likes