如何在LuaBridge中使用运算符?

我正在尝试导出我的向量类

            .beginClass<Vector>("Vector")
            .addConstructor<void(*)()>()
            .addConstructor<void(*)(float, float, float)>()
            .addFunction("__eq", &Vector::operator==)
            .addFunction("__add", &Vector::operator+)
            .addData("x", &Vector::x)
            .addData("y", &Vector::y)
            .addData("z", &Vector::z)
            .addFunction("Length", &Vector::Length)
            .addFunction("Angle", &Vector::Angle)
            .addFunction("Distance", &Vector::DistTo)
        .endClass()

但当我尝试做另外3个操作符时,我有多个重载函数。我如何指定要使用哪一个并且这可能吗?

点赞
用户3586583
用户3586583

如果你有一个函数重载int MyClass::Func(int)MyClass* MyClass::Func(MyClass),那么你可以使用以下方式定义要使用的重载。在这个例子中,我选择使用MyClass* MyClass::Func(MyClass)作为重载。

.addFunction("Func", (MyClass*(MyClass::*)(MyClass)) &MyClass::Func)

在这里发生的是,函数签名被提供了指向函数的指针。

2015-12-14 00:39:04
用户4376737
用户4376737

所以我刚刚写了一个加减乘除的函数,并调用它们。看来运算符就是不想顺从。

2015-12-14 09:01:11
用户7865250
用户7865250

infect luabridge可以用以下方法实现:

如果你定义了一个名为A的类:

.addFunction("__eq", &A::equal )

那么'equal'应该声明如下:

bool A::equal( const A & )

然后:

if obj1 == obj2 then
end

'equal'就会起作用了!

但如果你实现了A的子类B:

class B : public A

那就会花费很多时间!

首先,你必须对模板类或者模板方法进行特化:

luabridge::UserdataValue

luabridge::UserdataPtr::push(lua_State* const L, T* const p)

然后指定你需要注册对象或指针的哪个(元)表

你应该阅读luabridge的源代码来完成这个任务!

接着!

你需要再次将这个函数注册到B中:

.addFunction("__eq", &B::equal )

Lua代码:

local inst_a = app.new_class_A();
local inst_b = app.new_class_B();
-- this will call the '__eq' in B's metatable
if( inst_b == inst_a )then
end
-- this will call the '__eq' in A's metatable
if( inst_a == inst_b )then
end

在调用__eq时,luabridge不会搜索类的父类的元数据表,所以你需要在A的子类中重新注册一遍!

希望能帮到你!

对我的糟糕英语表示抱歉!

2017-04-14 03:35:33