Ensber
Ensber

Reputation: 26

pause function and resume later without corutine

I am trying to implement multitasking to lua, so that I can use multiple Threads on the Node MCU.

My idea was to run the threads as functions, pause them and continue with the next and do that in a loop. The debug.sethook function seemed prommising but didn't work with the corutines, they executed the hook only after the corutine finished. I only really need a way to pause a functon.

mt = {}
mt.threadList = {}

function mt.newThread(fnc)
    table.insert(mt.threadList,fnc)
end

function mt.update()
    for i=1,#mt.threadList do
        print("EPOCH: "..i)
        debug.sethook(print,"c",40)
        coroutine.resume( mt.threadList[i] )
        debug.sethook()
    end
end

function tA()
    for i=1,100 do
        print("A",i)
    end
end

function tB()
    for i=1,100 do
      print("B",i)
    end
end

mt.newThread(tA)
mt.newThread(tB)

mt.update()

Upvotes: 0

Views: 379

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473537

coroutine.resume continues a coroutine, not a regular function. Coroutines (from the Lua side) are generated by coroutine.create. coroutine.resume can only be called on the value returned by coroutine.create.

That being said, Lua coroutines are cooperative (hence the term "co-routine"). That means that you're not supposed to be able to arbitrarily interrupt their execution at any particular point. The coroutine itself should decide when to suspend, via a call to coroutine.yield or similar functions.

You can use debug.sethook on a coroutine to set its debug hook (if you don't pass a coroutine to sethook, then it assumes that you're setting the debug hook for the current thread, which is not what you want), and thereby coroutine.yield at arbitrary points in time. But you really shouldn't.

In any case, without coroutines, there is no way to "pause" a function's execution at all. Not even with a debug hook.

Upvotes: 1

Related Questions