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

本文详细探讨了使用C++调用Lua协程的过程,包括创建、注册、恢复及挂起Lua协程的具体实现,展示了如何在C++中通过Lua API与Lua脚本交互,以及如何处理协程间的参数传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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);
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);

// 这次恢复协程时传入参数, 参数压栈, 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;
}
 

 

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("calield!")
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
--------------------- 
作者:leisure_footprint 
来源:优快云 
原文:https://blog.youkuaiyun.com/leisure_footprint/article/details/53072563 
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值