#ifndef ALA_LUA_CO_H
#define ALA_LUA_CO_H
#include<vector>
#include<stdio.h>
#include<lua.hpp>
std::vector<lua_State*>co_threads;
void co_update();
void co_add(lua_State*);
void co_resume(lua_State*);
void co_report(lua_State*thread){
if(lua_status(thread)==LUA_ERRRUN){
printf("ERROR: %s",lua_tostring(thread,-1));
lua_pop(thread,-1);
};
};
void co_resume(lua_State*thread){
switch(lua_status(thread)){
case LUA_OK:{//never resumed thread or running or dead
if(lua_gettop(thread)!=0){//surely not dead thread and not running thread
if(lua_resume(thread,NULL,0)==LUA_YIELD){//crash maybe here
co_add(thread);
}else{
co_report(thread);
};
};
return;
};
case LUA_YIELD:{
lua_resume(thread,NULL,0);
return;
};
default:{
return;
};
};
};
void co_add(lua_State*thread){
co_threads.push_back(thread);
};
void co_update(){
if(co_threads.empty())return;
size_t i=co_threads.size();
while(i>0){
--i;
lua_State*thread=co_threads[i];
constint status(lua_status(thread));
if(status==LUA_YIELD){
lua_resume(thread,NULL,0);
co_report(thread);
}else{
co_report(thread);
co_threads.erase(co_threads.begin()+i);
};
};
};
#endif
1 2 3 4 5 6 7 8 9
--lua source code
for thread_id=1,100 dofor i=1,100 do coroutine.yield();end;
rthread(mthread(function()
for i=1,1000 do coroutine.yield();end;
print(thread_id);
end));
end;