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?

01local xPosition
02local AmountOfCash
03 
04local corouti = coroutine.create(function()
05    while wait() do
06        AmountOfCash = Player.leaderstats.Cash.Value   
07    end
08end)
09 
10coroutine.resume(corouti)
11 
12local genRandomNumber = coroutine.create(function()
13    while wait() do
14        xPosition = math.random(0.200, 0.500)
15    end
16end)
17 
18coroutine.resume(genRandomNumber)
19print(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.

01xPosition = 0
02 
03local genRandomNumber = coroutine.create(function()
04    while wait() do
05        xPosition = math.random(0.200, 0.500)
06        print(xPosition)
07    end
08end)
09 
10coroutine.resume(genRandomNumber)

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

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

Answer this question