1 | while true do |
2 | n = 0 |
3 | print (n + 1 ) |
4 | 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.
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.
1 | n = 0 --this creates the variable and sets it to 0 once |
2 | while 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 |
6 | end |
that's an infinite loop, you need to use wait
Use this code
1 | local n = 0 |
2 |
3 | while true do |
4 | wait( 1 ) -- change it to set the speed with which it increases |
5 | n = n + 1 |
6 | print (n) |
7 | end |
You could do it like this using a while loop
1 | n = 0 |
2 |
3 | while (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:
1 | for i = 0 , 20 , 1 do |
2 | print ( "value of i is: " , i) |
3 | end |
Above code also prints from 0 to 20.
You have the right idea but there are a few problems in your code:
You need to add a wait to your code so that the computer will wait a bit between adding 1 to n each time
You need to add the line n = n + 1 so that each repetition of the code the value of n will increase by 1.
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:
1 | n = 0 --the starting value for n |
2 | while true do wait ( 1 ) -- the loop will repeat once every second |
3 | n = n + 1 -- increases the value of n by 1 |
4 | print (n) -- prints the value of n |
5 | end |