2012-09-21 85 views
4

我試圖學習與C++接口Lua的基礎知識,但我遇到了一個問題。 我想調用一個返回字符串的函數,然後使用C++端的字符串,但luaL_dostring似乎沒有在Lua棧上放置任何東西。luaL_dostring什麼都不放在堆棧上?

即使是一個簡單的測試,似乎沒有正常工作:

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 

任何想法?

+0

如果該功能在您的Lua環境已經存在,那麼你就可以直接推它和它的ARGS到堆棧中,並通過lua_call調用它的更好() 。 –

回答

12

啊哈,發現問題了。根據this page,在Lua 5.1中,luaL_dostring忽略返回。我有的代碼可能會在Lua 5.2中工作。

要修改的功能,你應該使用:

#undef luaL_dostring 
#define luaL_dostring(L,s) \ 
    (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) 
+1

請注意,這也是在Lua 5.1.1中修復的。 –