Thanks for the responses. My issue is that the scripts I want to run will be installed at run time and will come from a 3rd party. It will be difficult to plan cooperative multitasking if every script is coming from a different source and then there may be a possibility of unreliable scripts which get stuck somewhere and never reach the yield. Maybe there is a way which I am not aware of.
In the meantime I gave it a try to use debug library sethook function with coroutines to run multiple scripts and here is a program I tried:
xco = ""
yco = ""
doing = ""
runningTasks = {}
function scheduler (event, line)
local xdone,ydone
for i= 1,#runningTasks do
if runningTasks[i] == xco then
xdone = true
end
if runningTasks[j] == yco then
ydone = true
end
end
if not xdone then
runningTasks[#runningTasks + 1] = xco
doing = xco
print(coroutine.resume(xco))
elseif not ydone then
runningTasks[#runningTasks + 1] = yco
doing = yco
print(coroutine.resume(yco))
else
if doing == xco then
doing = yco
coroutine.resume(yco)
else
doing = xco
coroutine.resume(xco)
end
end
end
x = loadstring([[function coyield(event,line) coroutine.yield() end debug.sethook(coyield, "l") for i = 1,5 do
print("x"..tostring(i))
end]])
y = loadstring([[function coyield(event,line) coroutine.yield() end debug.sethook(coyield,"l") for i = 1,10 do print("y"..tostring(i)) end]])
xco = coroutine.create(x)
yco = coroutine.create(y)
scheduler()
-------------------------------------------------------------------------------------------------------------
I get an error saying I cannot yield across C-call boundary. That is probably because the script I execute is loaded with loadstring. I even tried making modules of the scripts and requiring them. That also did not work.
So we can't use coroutines across modules? Any way we can do this?
Thanks,
Milind