#Roblox Coroutines Being Silly

1 messages · Page 1 of 1 (latest)

gloomy burrow
#

I am pretty new to using coroutines in lua, so I am having trouble getting them to work the way that I want them to.

Essentially what I am trying to do is to run this function asynchronously

function UpdateCoroutine(control, name, value, init, final, rate, time)
    print("test")
    local tick = 0
    print(tick)
    while ( tick < time ) do
        print(tick)
        value = init + (final - init)*(1 - math.exp(-1 * rate * tick / time)) / (1 - math.exp(-1 * rate))
        tick += 1

        coroutine.yield()
    end
    value = final
    print("ending")
    Threads[name] = nil
end

I create the thread here.

Threads.SG = coroutine.create(UpdateCoroutine(Reactor.Controls.ToggleSG, "SG", Reactor.Status.SG, 0, 100, 5, 50))

The debug print statement before this line runs, but the print statement after this line does not run, so something weird is happening here.

Then, I am running the thread with

local function UpdateValues()
    for _, thread in Threads do
        print("RUNNING THREAD")
        coroutine.resume(thread())
    end
end

The print statement here never happens, so this isn't running. It is also worth noting that this is the ONLY place that I use coroutine.resume.

The first print statement in UpdateCoroutines DOES get printed. Since my UpdateValues function isn't running, why is my coroutine running? It's also worth noting that it only runs one time, when UpdateValues gets called every 0.1 seconds.

Thanks for the help : )

vocal mantleBOT
#

studio** You are now Level 8! **studio

solid scaffold
#

coroutines is the thread library, they do not run asynchronously. they only set up the context for asynchronous execution. coroutine.wrap() is a newb trap in that way, i see a lot of people using it to create an async thread when it's actually not async. tl;dr use task.spawn, not coroutine.create or coroutine.wrap.

gloomy burrow
solid scaffold
gloomy burrow
#

alright

solid scaffold
#

you can also use coroutine.create to create the thread, and then task.spawn(coroutine.create(function()...etc...end)) to put the thread into the task scheduler

#

and then inside the coroutine you can use while true do task.wait() end

#

you can also do coroutine.yield in a thread executed from task.spawn and use other control code to manage the state of the thread, but yea if you ever want to resume the thread in async then you need to use task.spawn(coroutine.resume) otherwise it will yield the calling thread.

#

a bit confusing for beginners totally understandable but it's not that bad when you get used to it

gloomy burrow
#

Also thank you for the help so far, I appreciate it

solid scaffold
#

dont worry about it

#

if you had 1000 threads then maybe but 20 isn't going to make much of a difference