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)
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