如何在C ++中将userdata从一个Lua块传递到另一个Lua块

问题描述 投票:1回答:2

我试图从C ++中的Lua脚本(userdata)获取chunk A(通过我的示例中的函数返回变量)然后,然后,将此userdata从C ++传递回Lua脚本(chunk B)(通过我的函数参数)例如)所以userdata可以用于chunk B,就像它在chunk A中一样。

MyBindings.h

class Vec2
{
public:
    Vec2():x(0), y(0){};
    Vec2(float x, float y):x(x), y(y){};
    float x, y;
};

MyBindings.i

%module my
%{
    #include "MyBindings.h"
%}

%include "MyBindings.h"

main.cpp

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

extern "C"
{
    int luaopen_my(lua_State *L);
}

int main()
{
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    luaopen_my(L);
    lua_settop(L, 0);
    /* chunk A */
    luaL_dostring(L, "local vec2 = my.Vec2(3, 4)\n"
                     "function setup()\n"
                       "return vec2\n"
                     "end\n");
    /* chunk B */
    luaL_dostring(L, "function test(p)\n"
                       "print(p.x)\n"
                     "end\n");
    void *userDataPtr = nullptr;

    /* call setup function */
    int top = lua_gettop(L);
    lua_getglobal(L, "setup");
    if (lua_pcall(L, 0, LUA_MULTRET, 0))
    {
        std::cout << lua_tostring(L, -1) << '\n';
        lua_pop(L, 1);
    }
    /* check the return value */
    if (lua_gettop(L) - top)
    {
        /* store userdata to a pointer */
        if (lua_isuserdata(L, -1))
            userDataPtr = lua_touserdata(L, -1);
    }
    /* check if userDataPtr is valid */
    if (userDataPtr != nullptr)
    {
        /* call test function */
        lua_getglobal(L, "test");
        lua_pushlightuserdata(L, userDataPtr); /* pass userdata as an argument */
        if (lua_pcall(L, 1, 0, 0))
        {
            std::cout << lua_tostring(L, -1) << '\n';
            lua_pop(L, 1);
        }
    }
    lua_close(L);
}

结果我得到:

[string“local vec2 = my.Vec2(3,4)...”]:6:尝试索引userdata值(本地'p')

我期望的结果:

3

是否有可能从userdata获得chunk A然后将其传递给chunk B所以它可以像在chunk A中那样使用?

c++ lua swig lua-userdata
2个回答
2
投票

除了另一个答案,我想展示一个变体,你在Lua注册表中存储对值的引用。这种方法的优点是您不必将值保留在堆栈上并考虑偏移量。另见“Lua编程”中的27.3.2 – References

这种方法使用三个功能:

  1. int luaL_ref (lua_State *L, int t); 从堆栈弹出最高值,将其存储在索引t的表中,并返回该表中值的索引。因此,要在我们使用的注册表中保存值 userDataRef = luaL_ref(L, LUA_REGISTRYINDEX);
  2. int lua_rawgeti (lua_State *L, int index, lua_Integer n);n(Lua的index)中将表格的元素t[n]的值推入堆栈。因此,从我们使用的注册表中检索索引userDataRef的值 lua_rawgeti(L, LUA_REGISTRYINDEX, userDataRef);
  3. void luaL_unref (lua_State *L, int t, int ref); 删除存储在ref表中的索引t处的引用,以便可以对引用进行垃圾回收并且可以重用索引ref。因此,从我们使用的注册表中删除参考userDataRef luaL_unref(L, LUA_REGISTRYINDEX, userDataRef);
#include <iostream>
#include <lua.hpp>

extern "C" {
int luaopen_my(lua_State *L);
}

int main() {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    luaopen_my(L);
    lua_settop(L, 0);
    /* chunk A */
    luaL_dostring(L, "local vec2 = my.Vec2(3, 4)\n"
                     "function setup()\n"
                       "return vec2\n"
                     "end\n");
    /* chunk B */
    luaL_dostring(L, "function test(p)\n"
                       "print(p.x)\n"
                     "end\n");
    int userDataRef = LUA_NOREF;

    /* call setup function */
    int top = lua_gettop(L);
    lua_getglobal(L, "setup");
    if (lua_pcall(L, 0, LUA_MULTRET, 0)) {
        std::cout << lua_tostring(L, -1) << '\n';
        lua_pop(L, 1);
    }
    /* check the return value */
    if (lua_gettop(L) - top) {
        /* store userdata to a pointer */
        userDataRef = luaL_ref(L, LUA_REGISTRYINDEX);
    }

    /* check if userDataRef is valid */
    if (userDataRef != LUA_NOREF && userDataRef != LUA_REFNIL) {
        /* call test function */
        lua_getglobal(L, "test");
        lua_rawgeti(L, LUA_REGISTRYINDEX, userDataRef);

        /* free the registry slot (if you are done) */
        luaL_unref(L, LUA_REGISTRYINDEX, userDataRef);

        if (lua_pcall(L, 1, 0, 0)) {
            std::cout << lua_tostring(L, -1) << '\n';
            lua_pop(L, 1);
        }
    }
    lua_close(L);
}

也许你想看看Lua-C-API的Sol2包装器。它可以用最少的样板做到你想要的。但是,它需要C ++ 14。

#include <iostream>

#define SOL_CHECK_ARGUMENTS 1
#include <sol.hpp>

extern "C" int luaopen_my(lua_State *L);

int main() {
    sol::state L;
    L.open_libraries();
    luaopen_my(L);

    /* chunk A */
    L.script("local vec2 = my.Vec2(3, 4)\n"
             "function setup()\n"
               "return vec2\n"
             "end\n");
    /* chunk B */
    L.script("function test(p)\n"
               "print(p.x)\n"
             "end\n");

    auto userDataRef = L["setup"]();
    L["test"](userDataRef);
}

6
投票

当您获得指向userdata数据的原始指针并将其作为lightuserdata推送到参数时,您将丢失有关对象类型的所有信息。 lightuserdata甚至没有单独的元表。

正确的方法是按原样传递Lua值。将原始返回值保留在Lua堆栈上,或将其复制到其他Lua容器(您的Lua表中用于临时表或Lua注册表),然后将该值复制到Lua堆栈以将其作为参数传递。这样您就不必了解绑定实现。您甚至不必关心这是用户数据还是任何其他Lua类型。

根据您的代码,这可能如下所示:

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

extern "C"
{
    int luaopen_my(lua_State *L);
}

int main()
{
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    /* chunk A */
    luaL_dostring(L, "local vec2 = {x=3, y=4}\n"
                     "function setup()\n"
                       "return vec2\n"
                     "end\n");
    /* chunk B */
    luaL_dostring(L, "function test(p)\n"
                       "print(p.x)\n"
                     "end\n");

    /* call setup function */
    int top = lua_gettop(L);
    lua_getglobal(L, "setup");

    if (lua_pcall(L, 0, LUA_MULTRET, 0))
    {
        std::cout << lua_tostring(L, -1) << '\n';
        lua_pop(L, 1);

        exit(EXIT_FAILURE); // simpy fail for demo
    }

    /* check the return value */
    if (lua_gettop(L) - top)
    {
        // the top now contains the value returned from setup()

        /* call test function */
        lua_getglobal(L, "test");

        // copy the original value as argument
        lua_pushvalue(L, -2);

        if (lua_pcall(L, 1, 0, 0))
        {
            std::cout << lua_tostring(L, -1) << '\n';
            lua_pop(L, 1);
            exit(EXIT_FAILURE);
        }

         // drop the original value
        lua_pop(L, 1);

    }else
    {
        // nothing is returned, nothing to do
    }
    lua_close(L);
}
© www.soinside.com 2019 - 2024. All rights reserved.