【问题标题】:luaL_dostring puts nothing on the stack?luaL_dostring 什么都没有放在堆栈上?
【发布时间】:2012-09-13 18:36:30
【问题描述】:

我正在尝试学习 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

有什么想法吗?

【问题讨论】:

  • 如果函数已经存在于你的 Lua 环境中,那么你最好将它和它的参数直接推入堆栈并通过 lua_call() 调用它。

标签: c++ lua lua-c++-connection


【解决方案1】:

啊哈,找到问题了。根据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))

【讨论】:

  • 注意,这在 Lua 5.1.1 中也已修复。
猜你喜欢
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
  • 2015-12-29
  • 2018-01-17
  • 2013-11-08
  • 2019-10-06
  • 2012-01-31
  • 2011-10-07
相关资源
最近更新 更多