Rockbox Technical Forums

Support and General Use => Plugins/Viewers => Topic started by: Bilgus on July 27, 2018, 09:57:10 AM

Title: Lua coroutines and anonymous functions
Post by: Bilgus on July 27, 2018, 09:57:10 AM
So what is a coroutine anyways?
in lua coroutines simulate multithreading within a single threaded environment
similar to how Rockbox schedules threads.

What about anonymous functions?
well this is a function that has no name weird huh?

So look at the function test1() below this is an example of a coroutine with an
anonymous function a very simple one but still...

This is in the style the lua manual exemplifies coroutines
I ran into some weird errors using coroutines in separate modules with this first style
stackoverflows.. weird crashes.. incorrect results.. attempt to yield across metamethod/C-call boundary

it just might be our own rocklua that has a bug that causes this but I'm pretty sure its a result of limited ram

the second style (test2()) worked perfectly
 
Just keep this in mind if you have weird errors with coroutines in lua

Code: [Select]
local count = 10

local function test1()
    local co = coroutine.create(function ()
        while true do
            count = count - 1
            local ct = coroutine.yield()

            if ct == 1 then count = -100 end     
        end
    end)
   
    while count > 0 do
        coroutine.resume(co, count)
    end
   
end


local function test2()
    function test_co()
        while true do
            count = count - 1
            local ct = coroutine.yield()

            if ct == 1 then count = -100 end     
        end
    end

    local co = coroutine.create(test_co)
   
    while count > 0 do
        coroutine.resume(co, count)
    end
   
end

test1()
rb.splash(rb.HZ, tostring(count))
os.exit()