无法从 Lua 函数中获取 C 函数返回值。

我试图通过 Lua 库获取 C 函数的返回值,但失败了。 我的代码如下:

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include <stdio.h>

static int testcmd(lua_State *L)
{
    lua_pushnumber(L, 0xBADF00D);
    return 1;
}

lua_State *initLua()
{
    lua_State *L = luaL_newstate();
    lua_gc(L, LUA_GCSTOP, 0);
    luaL_openlibs(L);
    lua_register(L, "testcmd", testcmd);
    lua_gc(L, LUA_GCRESTART, 0);
    return L;
}

int main(void)
{
    lua_State *L = initLua();
    int error = luaL_loadbuffer(L, "testcmd()", 9, "line");
    if (error) { printf("Error @ luaL_loadbuffer()\n"); return 0; }
    lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
    if (lua_gettop(L) > 0) {
        int i;
        for (i = 1; i <= lua_gettop(L); ++i) {
            printf("%d: %g\n", i, lua_isnumber(L, i) ? lua_tonumber(L, i) : 0.0);
        }
    } else {
        printf("No data in stack\n");
    }
    lua_close(L);

    return 0;
}

我期望在 lua_call() 之后从 L 中获取一个大约为 0xBADF00D 的浮点数。然而,实际结果是 No data in stack

我该如何获取在 testcmd() 中推送到栈中的值呢?

点赞
用户258523
用户258523

你已经告诉了 C 函数,当被调用时要将返回值返回给 Lua(这就是将值推到堆栈上并返回 1 的作用)。

但你没有在运行的 Lua 块中返回该返回值。

当你从 Lua 调用该函数(使用 luaL_loadbuffer(L, "testcmd()", 9, "line"))时,要运行的语句是 testcmd(),该语句并未对返回值做任何操作,因此它不会从该块中返回。

你需要运行的代码是 return testcmd()

请记住,luaL_loadbuffer/ lua_pcall 的组合并不直接调用 testcmd,而是执行一个调用 testcmd 的 Lua 代码。

2014-09-18 15:14:17