如何使用SWIG绑定类在Lua中使用操作符?

这里有一个名为Value的类,它可以简单地获取和设置float

class Value
{
public:
    Value(float f)
    :f(f){};
    float get()
    {
        return f;
    }
    void set(float f)
    {
        this->f = f;
    }
private:
    float f;
};

我希望我的类能够像Lua中的以下示例一样工作。

local value = my.Value(3);
value = value * 2 - 1
if (value == 5) then
    print("succeed");
else
    print("failed");
end

并且它应该输出以下结果。

succeed

我该如何修改我的类,以便我可以在其中使用操作符?

点赞
用户1944004
用户1944004

你需要重载你想使用的每个运算符,例如 operator*operator+operator==。不幸的是,比较运算符无法正常工作,因为 Lua 仅在比较的两个操作数具有相同的元表时才考虑 __eq 元方法。来自 Lua 用户 Wiki

__eq - 检查相等性。当计算 "myTable1 == myTable2" 时,将调用此方法,但仅当两个表都具有相同的 \_\_eq 元方法时才调用。

您可以通过将比较的另一个操作数包装在 Value 构造函数中来解决这个问题。

%module my
%{
class Value
{
public:
    Value(float f) :f(f) {};
    Value operator*(float f) const {
        return this->f * f;
    }
    Value operator-(float f) const {
        return this->f - f;
    }
    bool operator==(Value const &rhs) const {
        return this->f == rhs.f;
    }
private:
    float f;
};
%}

class Value {
public:
    Value(float f);
    Value operator*(float f) const;
    Value operator-(float f) const;
    bool operator==(Value const &rhs) const;
};
local my = require("my")

local value = my.Value(3);
value = value * 2 - 1

if (value == my.Value(5)) then
    print("succeed");
else
    print("failed");
end
2018-07-09 09:46:19