自指针,在C++函数中从Lua中使用

我仍然对Lua很陌生,而且很难确定在从C++类中注册C函数时,应该如何从Lua创建的对象中检索自指针,以便于解决问题。

foo.h

class Foo
{
public:
    static int lua_DoSomething(lua_State* pState);
    void DoSomething();
};

foo.cpp

static const luaL_Reg methods[] =
{
    {"DoSomething", Foo::lua_DoSomething},
    {nullptr, nullptr}
};

extern "C"
{
    int luaopen_Foo(lua_State* pState)
    {
        luaL_register(pState, "Foo", methods);
        return 1;
    }
}

int Foo::lua_DoSomething(lua_State* pState)
{
    Foo* self = ???; // 如何在这里获得自指针?
    self->DoSomething();
    return 0;
}

void Foo::DoSomething()
{
    //...
}

script.lua

Foo.DoSomething();

所以我已经成功地注册了函数并调用了 Foo::lua_DoSomething(获胜!)。

然而,由于 Foo 对象是由Lua创建的,所以我该如何在函数Foo::lua_DoSomething中获取自指针?

我是否需要注册某种Foo::GetInstance函数到Lua中,以获得Foo指针,然后在Lua脚本中使用它?

如果有多个 Foo 实例怎么办?

对于由Lua创建的对象,最干净的一般方法是什么?谢谢!

点赞
用户2383374
用户2383374

在类型为 Foo 的成员函数中,'this' 指针会自动为您提供。它的类型是 const Foo*。通常情况下不必要,因为在大多数情况下您可以直接使用成员。例如:您可以将以下代码:

int Foo::lua_DoSomething(lua_State* pState)
{
  this->DoSomething();
  return 0;
}

替换为

int Foo::lua_DoSomething(lua_State* pState)
{
    DoSomething();
    return 0;
}
2015-03-02 15:40:32
用户3319335
用户3319335

你需要在lua状态中传递一些信息,这将帮助你识别"self"。例如,你可以将Foo类的所有创建的实例存储在map中,并将一个实例与某个标识符(int id)关联起来,或者仅仅传递实例的指针转换为size_t。然后在lua_DoSomething方法中,从lua状态中获取该信息,将其转换为Foo实例,然后你就拥有了"self"。

编辑后:

我不太熟悉从这个角度的lua(我做过一些lua脚本)。但是。。。

在lua中,你可以存储数据并在lua和C++之间交换这些数据。 我猜你在lua中有一个C++ Foo的对应项,我们将其命名为LFoo。

C++中的Foo有一个DoSomething方法,我猜你想在lua中执行相同的操作(我知道你不能在lua中拥有类,但有一些方法可以使用表模拟)。Foo实例有它的地址(this)把这个地址传给lua并将值存储在LFoo的表格中。当你在lua中调用DoSomething函数时,这个函数会调用静态方法lua_DoSomething,通过lua_state将值从LFoo表格传递回该方法。使用它来获取"this"。

尝试使用类似于以下的东西:

void RegisterFoo(lua_state* pState, Foo* foo)
{
    Foo** p = (Foo**)lua_newuserdata(pState,sizeof(foo));
    *p = foo;
    ...
}

int Foo::lua_DoSomething(lua_State* pState)
{
    // pass the pointer at first index for example
    Foo* self = (Foo*)lua_topointer(pState,0);
    self->DoSomething();
    return 0;
}

我发现这些函数的解释:

http://pgl.yoyo.org/luai/i/lua_newuserdata

http://pgl.yoyo.org/luai/i/lua_topointer

2015-03-02 17:19:25