Making a number change a bit by bit

So if I made a script:
local blahblah = math.Random(2,7)
It would make the number be between 2-7
But if i made a loop:
while true do
local blahblah = math.Random(2,7)
print(blahblah)
wait(0.2)
end
That would print a random number from 2-7 every 0.2 seconds. But can I make it so the number changes only by 1 or 2 so my output might look like this?

2
3
4
3
2
So it can only change by 1? Because the original script can print random numbers like
3
7
3
2
Help Appreciated!

I’m not entirely sure what you’re asking here.

So if I made a script that was this:
while true do
local blahblah = math.Random(2,7)
print(blahblah)
wait(0.2)
end
My output would be full of random numbers between 2-7
How do I make it so the number can only change by one? So the value of blahblah would only change by one every loop

local num = 2
while true do
    num = math.clamp(num + math.random(0, 1) * 2 - 1, 2, 7)
    print(num)
    wait(0.2)
end

Thanks! Could you please label what each line means because I am a bit confused.

  1. You declare what number you will start with, it can also be math.random(2, 7) instead of 2
  2. Loop
  3. Update the num so that it’s a new number in range [2, 7] - that’s what math.clamp is for
    math.clamp looks internally similiar to this:
function clamp(n, a, b)
    if n < a then return a end
    if n > b then return b end
    return n
end

The new number is calculated like this:

num + math.random(0, 1) * 2 - 1

That means we take the old num and add -1 or 1 to it.
4. printing new number
5. wait
6. loop end

Thank you so much! I can continue my game I am developing.

Here’s an update because you wanted the number to always change by one, but when the number is 7 (on the [2, 7] interval boundary) and you add one it will remain 7 because of the math.clamp function. Therefore we will have to do something like that:

local intervalA, intervalB = 2, 7

local num = math.random(intervalA, intervalB)
while true do
    if num == intervalA then
        num = num + 1
    elseif num == intervalB then
        num = num - 1
    else
        num = num + math.random(0, 1) * 2 - 1
    end
    print(num)
    wait(0.2)
end

Now when the number is equal to 7 it will always be decremented by one and when it is 2 it will be always incremented.