【发布时间】:2014-09-18 15:01:21
【问题描述】:
我尝试通过 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 的1 个浮点值。但是,实际结果是No data in stack。
如何在testcmd() 中将值推送到堆栈?
【问题讨论】:
-
您需要
return testcmd()作为您的块,以便它返回值而不是仅仅将其丢弃。 -
@EtanReisner 我真的不知道应该在哪里
return testcmd()使L包含堆栈顶部的值。我在testcmd()中有lua_pushnumber()。对不对? -
是的,它告诉 C 函数返回值,但是当你 call 来自 lua 的函数时,你的语句是
testcmd(),它不会对返回值做任何事情所以它不会从块中返回。return testcmd()是您需要执行的字符串。您没有直接调用testcmd,而是在执行调用testcmd的lua代码。 -
@EtanReisner 它有效。请将其发布为答案,以便我接受。
-
不幸的是,这还不够接近,但这本质上是 stackoverflow.com/questions/25850797/… 的副本(我敢肯定还有很多其他问题)。