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

Why is it printing 'nil', when it should be printing a random number? (notice me '3')

Asked by 4 years ago
Edited 4 years ago

I was just testing things out, but on the last line print(xPosition), it is printing 'nil', how do I prevent that from happening?

local xPosition
local AmountOfCash

local corouti = coroutine.create(function()
    while wait() do
        AmountOfCash = Player.leaderstats.Cash.Value    
    end
end)

coroutine.resume(corouti)

local genRandomNumber = coroutine.create(function()
    while wait() do
        xPosition = math.random(0.200, 0.500)
    end
end)

coroutine.resume(genRandomNumber)
print(xPosition)

1 answer

Log in to vote
1
Answered by
Memotag 226 Moderation Voter
4 years ago

I believe it is due to while wait() do. During that wait() the thread is paused and print(xPosition) runs, therefore returning a value of nil. Since the coroutine is a separate thread, the local variable xPosition is outside the scope and so the xPosition within the loop is not the same variable.

You can remedy this by making xPosition a global variable and assigning it a value and putting a print inside the genRandomNumber coroutine.

xPosition = 0

local genRandomNumber = coroutine.create(function()
    while wait() do
        xPosition = math.random(0.200, 0.500)
        print(xPosition)
    end
end)

coroutine.resume(genRandomNumber)

As a side note, if you want a decimal then you need to be doing something like this:

local x = math.random(2, 5)/100
Ad

Answer this question