luaL_dostring函数不将任何内容放在堆栈上?

我正在尝试学习Lua与C ++的接口基础知识,但我遇到了一个问题。我想调用一个返回字符串的函数,然后在C ++侧处理字符串,但是luaL_dostring似乎在Lua堆栈上没有任何东西。即使是一个简单的测试似乎也不能正常工作:

lua_State* lua = lua_open();
luaL_openlibs(lua);

//Test dostring.
luaL_dostring(lua, "return 'derp'");

int top = lua_gettop(lua);
cout << "stack top is " <<top << endl;

//Next, test pushstring.
lua_pushstring(lua, "derp");

top = lua_gettop(lua);
cout << "stack top is " << top << endl;

结果:

stack top is 0
stack top is 1

有什么想法吗?

点赞
用户1043299
用户1043299

Aha, found the problem. According to this page, in Lua 5.1 luaL_dostring ignores returns. The code I had would probably work in Lua 5.2.

要修改功能,您应该使用:

#undef luaL_dostring
#define luaL_dostring(L,s)  \
    (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0))
2012-09-21 11:36:33