- 论坛徽章:
- 4
|
本帖最后由 linux_c_py_php 于 2013-02-24 17:05 编辑
举个简单例子, 服务端假设提供各个插件(包括lua插件)提供完成的回调通知接口, 那么为宿主写一个lua扩展可以大致像这样来通知event loop该lua脚本执行结束了(这里直接在coroutine内的第0级调用上就做了yield, 演示用途.):- [root@vps616 study]# bin/main
- write 1 byte to pipe to notify event loop that lua finishes
- [root@vps616 study]# cat logic.lua
- co = coroutine.running()
- coroutine.yield(co)
- [root@vps616 study]# cat src/main.c
- #include <lua.h>
- #include <lualib.h>
- #include <lauxlib.h>
- int luaCoroutineFinish(lua_State *LL) {
- /*lua_getctx can check if error occurs in luascript, so we can return differet result to lua_resume*/
- int ctx = 0;
- int err = lua_getctx(LL, &ctx);
- printf("err=%d ctx=%d write 1 byte to pipe to notify event loop that lua finishes\n", err, ctx);
- if (err != LUA_YIELD) {
- printf("%s\n", lua_tostring(LL, -1));
- }
- return 0; /*coroutine dead here*/
- }
- int luaError(lua_State *LL) {
- printf("lua script error, we may pushback a errmsg for luaCoroutineFinish\n");
- lua_pushstring(LL, "cao");
- return 1;
- }
- int luaCoroutine(lua_State *LL) {
- lua_pushcfunction(LL, luaError);
- luaL_loadfile(LL, "./logic.lua");
- if (lua_pcallk(LL, 0, 0, -2, 0, luaCoroutineFinish) != LUA_OK) {
- lua_pushstring(LL, "fuck");
- lua_error(LL);
- }
- printf("Also write 1 byte to pipe to notify event loop that lua finishes\n");
- return 0; /*coroutine dead here*/
- }
- int main(int argc, char *const argv[]) {
- lua_State *L = luaL_newstate();
- luaL_openlibs(L);
- lua_State *LL = lua_newthread(L);
- lua_pushcfunction(LL, luaCoroutine);
- if (lua_resume(LL, NULL, 0) != LUA_YIELD) {
- printf("___1:%s\n", lua_tostring(LL, -1));
- return -1;
- }
- if (lua_resume(LL, NULL, 0) != LUA_OK) {
- printf("___2:%s\n", lua_tostring(LL, -1));
- return -1;
- }
- return 0;
- }
复制代码 |
|