I was just testing things out, but on the last line print(xPosition)
, it is printing 'nil', how do I prevent that from happening?
01 | local xPosition |
02 | local AmountOfCash |
03 |
04 | local corouti = coroutine.create( function () |
05 | while wait() do |
06 | AmountOfCash = Player.leaderstats.Cash.Value |
07 | end |
08 | end ) |
09 |
10 | coroutine.resume(corouti) |
11 |
12 | local genRandomNumber = coroutine.create( function () |
13 | while wait() do |
14 | xPosition = math.random( 0.200 , 0.500 ) |
15 | end |
16 | end ) |
17 |
18 | coroutine.resume(genRandomNumber) |
19 | 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.
01 | xPosition = 0 |
02 |
03 | local genRandomNumber = coroutine.create( function () |
04 | while wait() do |
05 | xPosition = math.random( 0.200 , 0.500 ) |
06 | print (xPosition) |
07 | end |
08 | end ) |
09 |
10 | coroutine.resume(genRandomNumber) |
As a side note, if you want a decimal then you need to be doing something like this:
1 | local x = math.random( 2 , 5 )/ 100 |