我正在开发一个 lua 脚本中断项目,我想使用 std::Stack 和 lua 协程来保存上下文。但是当我将 stacksize 设置为超过 38 时,它会在 lua_resume 和 lua_close 中随机崩溃。测试.lua:
local stacksize = 40 --When changing stacksize less than 30, it runs fine.
function heavy_function(i)
print("heavy_function start",i)
if i < stacksize then
coroutine.yield(i+1)
end
print("heavy_function end",i)
end
主.cpp:
#ifdef __cplusplus
extern "C" {
#endif
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#ifdef __cplusplus
}
#endif
#include <iostream>
#include <unistd.h>
#include <ctime>
#include <stdio.h>
#include <string>
#include <stack>
using namespace std;
int main()
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
int ret = luaL_dofile(L, "test.lua");
if (ret != 0)
{
// Error loading script. Return.
printf("luaL_dofile error \n");
return -1;
}
// Add a count hook that will trigger after "count" number instructions
//lua_sethook(L, LUAHook, LUA_MASKLINE, 0);
stack<lua_State *> Lstack;
Lstack.push(lua_newthread(L));
int init = 1;
do{
lua_getglobal(Lstack.top(), "heavy_function");
lua_pushinteger(Lstack.top(),init);
ret = lua_resume(Lstack.top(),L,1);
if(ret == LUA_YIELD)
{
init = luaL_checkinteger(Lstack.top(),-1);
Lstack.push(lua_newthread(L));
}
else if(ret == 0)
{
//lua_close(Lstack.top());
lua_gc(L,LUA_GCCOLLECT,0);
cout<<"Memory Usage:"<<lua_gc(L,LUA_GCCOUNT,0)<<endl;
Lstack.pop();
}
else{
cout<<"error"<<endl;
return -1;
}
}while(Lstack.size()>0);
//printf("lua script interrupted \n");
lua_close(L);
return 0;
}
编译器选项:
g++ -g main.cpp -o test -llua -ldl
我怀疑是我调用lua_newthread时出错了,所以我在调用lua_newstate之前做了一个堆栈检查,它变得正常了。
if(ret == LUA_YIELD)
{
init = luaL_checkinteger(Lstack.top(),-1);
Lstack.push(lua_newthread(L));
cout<<"lua_checkstack(L,10) = "<<lua_checkstack(L,1)<<endl;//Add a line in line 47
}
想知道我是否在这方面犯了错误,我该如何改正?