int scheduler_start(lua_State *L) { luaL_checktype(L,1,LUA_TTABLE); hive_createenv(L); struct global_queue * gmq = lua_newuserdata(L, sizeof(*gmq)); globalmq_init(gmq); lua_pushvalue(L,-1); hive_setenv(L, "message_queue"); lua_State *sL; sL = scheduler_newtask(L); luaL_requiref(sL, "cell.system", cell_system_lib, 0); lua_pop(sL,1); struct cell * sys = cell_new(sL, "system.lua"); if (sys == NULL) { return 0; } scheduler_starttask(sL); lua_getfield(L,1, "thread"); int thread = luaL_optinteger(L, -1, DEFAULT_THREAD); lua_pop(L,1); struct timer * t = lua_newuserdata(L, sizeof(*t)); timer_init(t,sys,gmq); _start(gmq,thread,t); cell_close(sys); return 0; }
void * hive_copyenv(lua_State *L, lua_State *fromL, const char *key) { hive_getenv(fromL, key); void *p = lua_touserdata(fromL, -1); lua_pop(fromL, 1); lua_pushlightuserdata(L, p); hive_setenv(L, key); return p; }
struct cell * cell_new(lua_State *L, const char * mainfile) { hive_getenv(L, "cell_map"); int cell_map = lua_absindex(L,-1); // cell_map luaL_requiref(L, "cell.c", cell_lib, 0); // cell_map cell_lib struct cell * c = cell_create(); c->L = L; cell_touserdata(L, cell_map, c); // cell_map cell_lib cell_ud lua_setfield(L, -2, "self"); // cell_map cell_lib hive_getenv(L, "system_pointer"); struct cell * sys = lua_touserdata(L, -1); // cell_map cell_lib system_cell lua_pop(L, 1); if (sys) { cell_touserdata(L, cell_map, sys); lua_setfield(L, -2, "system"); } lua_pop(L,2); lua_pushlightuserdata(L, c); hive_setenv(L, "cell_pointer"); int err = luaL_loadfile(L, mainfile); if (err) { printf("%d : %s\n", err, lua_tostring(L,-1)); lua_pop(L,1); goto _error; } err = lua_pcall(L, 0, 0, 0); if (err) { printf("%d : %s\n", err, lua_tostring(L,-1)); lua_pop(L,1); goto _error; } lua_pushcfunction(L, traceback); // upvalue 1 lua_pushcfunction(L, data_unpack); // upvalue 2 hive_getenv(L, "dispatcher"); // upvalue 3 if (!lua_isfunction(L, -1)) { printf("set dispatcher first\n"); goto _error; } hive_getenv(L, "cell_map"); // upvalue 4 lua_pushcclosure(L, lcallback, 4); return c; _error: scheduler_deletetask(L); c->L = NULL; cell_destroy(c); return NULL; }
lua_State * scheduler_newtask(lua_State *pL) { lua_State *L = luaL_newstate(); luaL_openlibs(L); hive_createenv(L); struct global_queue * mq = hive_copyenv(L, pL, "message_queue"); globalmq_inc(mq); hive_copyenv(L, pL, "system_pointer"); lua_newtable(L); lua_newtable(L); lua_pushliteral(L, "v"); lua_setfield(L, -2, "__mode"); lua_setmetatable(L,-2); hive_setenv(L, "cell_map"); return L; }