再看lua协同程序的lua_yield、coroutine.yield、和lua_resume的应用

1:lua_resume_yield.cpp程序

#include <stdio.h>
#include <lua.hpp>
#include <lualib.h>
#include <lauxlib.h>


static int Stop(lua_State* L);


lua_State* CreateCoroutine(lua_State* gL, const char* corName);


int main()
{
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    luaL_dofile(L,"corTest.lua");
    lua_State* newL = CreateCoroutine(L,"CorTest");
    lua_register(newL,"Stop",Stop);
    int re = lua_resume(newL, 0);  // 这次传0个参数(因为CorTest没有参数)
    if(re != LUA_YIELD)
        printf("ERROR");
    //lua挂起后, 栈增加了coroutine.yield的参数:100, 和hello C++
    int rint = luaL_checknumber(newL, -2);
    const char* str = lua_tostring(newL, -1);
    printf("stack value: %d,  %s,now stack size:%d\n", rint, str,lua_gettop(newL));  // ? 100, hello C++
    // 这次恢复协程时传入参数, 参数压栈, lua中就是对应返回值local re
    lua_pushstring(newL, "from c++");
    printf("3333 stack szie: %d\n",lua_gettop(newL));
    /// from c++这个字符串当做lua_resume的参数回传给coroutine的主函数
    re = lua_resume(newL, 1);
    // 挂起后是在Stop()函数中传入了一个"call c yield!"
    printf("555 stack szie: %d\n",lua_gettop(newL));
    re = lua_resume(newL, 0); // 这里无法传值回去lua了,因为Stop的栈已经被释放 ,而是直接运行lua中Stop的后一句
    lua_close(L);
    return 0;
}


static int Stop(lua_State* lp)
{
    // 会传一个参数进来
    const char* str = lua_tostring(lp,-1);
    printf("C Stop Func: %s\n", str);
    //将这个值再次压入栈中
    lua_pushstring(lp,str);
printf("Stop func stack szie: %d\n",lua_gettop(lp));
    //Yields a coroutine.
    //This function should only be called as the return expression of a C function
, as follows:
    return lua_yield(lp,1);
}


lua_State* CreateCoroutine(lua_State* gL, const char* corName)
{
    lua_State* newL = lua_newthread(gL);
    lua_getglobal(newL, corName);  // 协程函数入栈
    return newL;
}
2:lua程序<corTest.lua>

function CorTest()
    print("coroutine begin")
    ---100,hello c++两个参数返回栈
    local re = coroutine.yield(100, "hello c++")  
    ---re是lua_resume的参数
    print("coroutine continue: " .. re) 
    Stop("call c yield!")  
    print("coroutine continue after yield")
    print("coroutine end")
end

3:编译运行整个程序
[root@localhost testLua]# g++ -g lua_resume_yield.cpp -ldl -llua
[root@localhost testLua]# ./a.out 
coroutine begin
stack value: 100,  hello c++,now stack size:2
3333 stack szie: 3
coroutine continue: from c++
C Stop Func: call c yield!
Stop func stack szie: 2
555 stack szie: 1
coroutine continue after yield
coroutine end

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值