c++ - 将一些数据推送到 Lua 调用函数

标签 c++ lua luabind

我有两个文件 - 一个用于执行 Lua 脚本和脚本本身。

他们在这里:

host.cpp:

#include <lua.hpp>
#include <iostream>

using namespace std;

int someHandler(lua_State  *l)
{
    int argc = lua_gettop(l);

    for (int i = 0; i < argc; i++)
    {
        cout << "ARG[" << i + 1 << "] = " << lua_tostring(l, i + 1) << endl;
    }

    lua_pushstring(l, "m_pi");
    //lua_pop(l, argc - 1);
    //lua_pushnumber(l, 3.14);

    return argc;
}

int main()
{
    lua_State *l = lua_open();
    luaL_openlibs(l);

    lua_register(l, "moo", someHandler);

    luaL_dofile(l, "script.lua");

    lua_close(l);

    return 0;
}

script.lua:

res = moo("hello", "world");

print(moo());

for k, v in res do
    print(k.." = "..v);
end

使用 g++ host.cpp -o host.elf -I/usr/include/lua5.1 -llua5.1 编译 host.cpp

运行host.elf的结果是:

ARG[1] = hello
ARG[2] = world
<\n>

虽然它应该是:

ARG[1] = hello
ARG[2] = world
m_pi

我做错了什么?

最佳答案

逐行解释:

--This calls moo with two arguments
--(ignore the assignment for now, we will come back to that)
res = moo("hello", "world");

控制转移到 C++:

//the stack of l looks like this: ["hello", "world"]
int someHandler(lua_State  *l)
{

    int argc = lua_gettop(l); //int argc = 2;

    //This loop prints:
    //"ARG[1] = hello\n"
    //"ARG[2] = world\n"
    for (int i = 0; i < argc; i++)
    {
        cout << "ARG[" << i + 1 << "] = " << lua_tostring(l, i + 1) << endl;
    }
    //This pushes "m_pi" on to the stack:
    lua_pushstring(l, "m_pi");

    //The stack now looks like ["hello", "world", "m_pi"]

    //Returns 2.
    //Lua will treat this as a function which
    //returns the top two elements on the stack (["world", "m_pi"])
    return argc;
}

控制返回给lua:

--Assigns the first result ("world") to res, discards the other results ("m_pi")
res = moo("hello", "world");

--Calls `moo` with zero arguments.
--This time, `lua_gettop(l)` will evaluate to `0`,
--so the for loop will not be entered,
--and the number of results will be taken to be `0`.
--The string pushed by `lua_pushstring(l, "m_pi")` will be discarded.
--`moo()` returns no results, so `print` prints nothing.
print(moo());

--WTF??: res = "world", which is a string, not an expression which evaluates to
--a loop function, a state variable, and a element variable.

--The for loop will raise in an error when it 
--attempts to call a copy of `res` (a string)
for k, v in res do
    print(k.." = "..v);
end

关于c++ - 将一些数据推送到 Lua 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9783252/

相关文章:

c++ - 我应该如何将 lua 函数绑定(bind)到 C++ 函数?

c++ - 生成随机掷骰子并测量结果的频率

c++ - 使用 Qt 创建自定义消息/事件

c++ - 如何从一个lua函数调用另一个lua函数?

c++ - 类似 Luabind 的语法(索引运算符)

c++ - luabind 没有启动我定义的功能

通过引用递归函数传递字符串或流对象时的 C++ 段错误

c++ - 编写用于日志记录的宏

lua - 在 Lua 中如何判断 ANY 变量何时被设置为给定值?

c++ - 需要帮助了解 luabind 如何实例化类