lua_pcall 导致了“无法恢复死亡协程”的错误。

我有下面的 C++ 代码来调用 Lua 代码:

for (int i =0; i < 2000; i++)
{
    lua_getglobal(g_L, "AnalyzeScript");
    lua_pushstring(g_L, "1");
    lua_pushstring(g_L, "2");
    lua_pushstring(g_L, "3");

    if(lua_pcall(g_L,3,0,0) != 0)
    {
        //          char temp[200]={0}; sprintf(temp, "err: %s",  lua_tostring(g_L, -1));
        //          MessageBoxA(0,temp,0,0);
    }

Lua 代码如下:

local cnt = 0
function AnalyzeScript(foldername, filename, pOut)
    cnt = cnt + 1
    print(cnt)
end

除了“无法恢复已死协程”(协程在另一个位置)的问题外,一切都正常。看起来 2000 次调用 lua 函数破坏了 lua 栈,如果将其更改为 200,则一切正常!

为什么?

点赞
用户2346921
用户2346921

我无法重现你的错误。我稍微改了一下代码:

/* test.c */
#include "lua.h"
#include "lauxlib.h"

void main() {
    int i;
    lua_State *g_L = luaL_newstate();
    luaL_openlibs(g_L);
    luaL_dofile(g_L, "s.lua");
    for (i =0; i < 2000; i++)
    {
        lua_getglobal(g_L, "AnalyzeScript");
        lua_pushstring(g_L, "1");
        lua_pushstring(g_L, "2");
        lua_pushstring(g_L, "3");

        if(lua_pcall(g_L,3,0,0) != 0)
        {
//          char temp[200]={0}; sprintf(temp, "err: %s",  lua_tostring(g_L, -1));
//          MessageBoxA(0,temp,0,0);
        }
    }
    lua_close (g_L);
}

我在我的 Linux 上使用以下命令编译它(我已经在 /fakepath/lua-5.2.0 中安装了 Lua 发行版):

gcc test.c -I/fakepath/lua-5.2.0/src /fakepath/lua-5.2.0/src/liblua.a -lm -ldl

test.lua 文件正好是您发布的内容。也许问题出在别的地方...

2013-05-03 12:48:59