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
1while true do
2    n = 0
3    print(n + 1)
4end

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.

1n = 0 --this creates the variable and sets it to 0 once
2while true do
3    n = n + 1 --redefines n as n+1
4    print(n) --prints the new value of n
5    wait() --stops the loop from freezing
6end
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

1local n = 0
2 
3while true do
4    wait(1) --  change it to set the speed with which it increases
5    n = n + 1
6    print(n)
7end
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

1n = 0
2 
3while(n <= 20) do
4    print("Value of n is: ", n)
5    n = n + 1
6    end

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

or using a for loop:

1for i = 0,20,1 do
2    print("value of i is: ", i)
3    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:

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

Answer this question