2

我正在开发一个 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
}

想知道我是否在这方面犯了错误,我该如何改正?

4

1 回答 1

2

通过不断生成新的 Lua 线程并将其 Lua 对象留在堆栈上,您正在溢出 Lua 堆栈。

lua_newstack()不仅返回一个指向lua_State结构的指针,它还在你的状态LUA_TTHREAD的堆栈上留下一个类型的值。L您应该相应地适应 Lua 堆栈,或者以其他方式管理返回的 Lua 线程。

快速而肮脏的“修复”将是lua_checkstack(L, 10);在您的Lstack.push(lua_newthread(L));线路之前打电话。它允许您的代码按原样运行,但堆栈会不断增长。相反,您应该从堆栈中获取新的线程对象并将其放入某个 Lua 表中,直到需要将其删除为止。

于 2018-09-29T10:27:57.310 回答