Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do you constantly add numbers to variables?

Asked by 5 years ago
while true do
    n = 0
    print(n + 1)
end

What I want to do is constantly add 1 to 0 (n) so it will be like 1 2 3 4 5 6, etc... and it will keep going. I forgot how to do this and just need some little help. When I run the script above it will just print 1 because its only added to n(0) 1 time. It's a little hard to explain but i hope you guys know what I mean.

0
Your studio probably crashes because of the inf loop. Code1ng 15 — 5y

4 answers

Log in to vote
0
Answered by 5 years ago

There's 2 issues with this. First, you're redefining n as 0 each time the loop restarts, so any changes to the variable wouldn't affect the next loop. Second, you're never adding onto n, simply printing what n+1 would return, which doesn't change the variable itself. Also, you may want to add a wait() at the end of the loop to prevent it from freezing roblox studio.

n = 0 --this creates the variable and sets it to 0 once
while true do
    n = n + 1 --redefines n as n+1
    print(n) --prints the new value of n
    wait() --stops the loop from freezing
end
Ad
Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

that's an infinite loop, you need to use wait

Use this code

local n = 0

while true do
    wait(1) --  change it to set the speed with which it increases
    n = n + 1
    print(n)
end
0
or could just do 'while wait(1) do --code end' Theswagger66 54 — 5y
Log in to vote
0
Answered by 5 years ago

You could do it like this using a while loop

n = 0

while(n <= 20) do
    print("Value of n is: ", n)
    n = n + 1
    end

The above code prints from 0 to 20 until reaching 20 and it will no longer be true.

or using a for loop:

for i = 0,20,1 do
    print("value of i is: ", i)
    end

Above code also prints from 0 to 20.

Log in to vote
0
Answered by
OBenjOne 190
5 years ago
Edited 5 years ago

You have the right idea but there are a few problems in your code:

  1. You need to add a wait to your code so that the computer will wait a bit between adding 1 to n each time

  2. You need to add the line n = n + 1 so that each repetition of the code the value of n will increase by 1.

  3. Put the n = 0 outside of the loop so that n will not be repeatedly reset to 0

The finished code should look something like this:

 n = 0 --the starting value for n
 while true do wait (1) -- the loop will repeat once every second
 n = n + 1 -- increases the value of n by 1
 print (n) -- prints the value of n
 end

Answer this question