繁体   English   中英

在c ++函数中使用lua_call很多次

[英]Using lua_call a lot of times in c++ function

首先,我很抱歉我的英语。

我的问题是如何在C ++函数中多次使用lua_call。 我有一个程序使用lua作为主要语言,但它接受c ++插件来添加功能。 我想从c ++调用LUA函数,并在LUA Runtime中调用该c ++函数。 我想在工作时编写一个带有进度的c ++函数,然后将此进程传递给LUA函数,该函数负责向用户显示进度。

现在我在LUA中有一个测试功能:

function ShowText(text)
    Dialog.Message("Hi", text);
    return true;
end

和一个c ++函数:

static int Test(lua_State *L){
    lua_pushstring(L, "Hi There");
    lua_call(L, 1, 1);

    lua_pushstring(L, "Again");
    lua_call(L, 1, 1); 

    return 0;
}

然后我使用以下命令从LUA调用此函数:

Test.Test(ShowText);

所有工作都可以正常使用第一个lua_call但是然后清除LUA堆,函数dissapear和第二个lua_call尝试使用第一个调用的返回布尔值而不是函数。

我想要这样的东西:

static int Test(lua_State *L){
    int total = 10;

    for (int j; j<total; j++){
        lua_pushnumber(L, j);
        lua_pushnumber(L, j);
        lua_call(L, 2, 1);
        bool continue = IRLUA_PLUGIN_CheckBoolean(L, -1);
        lua_pop(L, 1); //Delete the last boolean

        if (continue == false){
            break;
        }
    } 

    return 0;
}

在LUA:

function ShowProgress(actual, final)
    local percent = (actual/final)*100;

    Dialog.Message("Working", "I'm in "..actual.." from "..final.." ("..percent.."%)");

    return true;
end

笔记:

Dialog.Message是我用来显示消息的程序的一个功能。 就像MessageBox(NULL,Text,Title,MB_OK); 在c ++中。

IRLUA_PLUGIN_CheckBoolean是插件SDK的一个函数,它检查参数是否为booleand并返回其值,否则返回错误。

我可以用lua_getfield(L,LUA_GLOBALSINDEX,“FunctionName”)来做到这一点; ,但不是我想要的。

有人知道怎么做吗?

你已经很好地理解了这个问题。 这是你如何解决它。

在第一个示例中, lua_call从堆栈中弹出函数,因此您需要先复制它。 此外,函数返回的布尔值是无用的,因此您需要弹出它或者不要通过将最后一个参数设置为0来要求它为lua_call:

static int Test(lua_State *L) {

    lua_pushvalue(L, 1); /* duplicate function */

    lua_pushstring(L, "Hi There");
    lua_call(L, 1, 0);

    lua_pushstring(L, "Again");
    lua_call(L, 1, 0); 

    return 0;
}

现在将其应用于您的第二个示例:

static int Test(lua_State *L) {
    int total = 10;

    for (int j = 0; j<total; j++) {
        lua_pushvalue(L, 1); /* duplicate function */
        lua_pushnumber(L, j);
        lua_pushnumber(L, total);
        lua_call(L, 2, 1);
        bool keep_going = IRLUA_PLUGIN_CheckBoolean(L, -1);
        lua_pop(L, 1); /* pop the boolean */

        if (keep_going == false) {
            break;
        }
    }

    return 0;
}

(我已经修复了你的代码的一些其他问题:传递的第二个数字应该是total ,而不是j ,你不想使用continue作为变量名......)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM