如何使 SWIG 绑定 class 以使用 Lua 中的运算符?

How to make the SWIG binded class to use operators in Lua?

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

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

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

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

它应该输出以下结果。

succeed

我应该如何更正我的 class 才能使用运算符?

您必须重载要使用的每个运算符,即 operator*operator+operator==。不幸的是,比较运算符不起作用,因为 Lua 仅在比较中的两个操作数具有相同的元表时才考虑 __eq 元方法。来自 Lua users wiki:

__eq - Check for equality. This method is invoked when "myTable1 == myTable2" is evaluated, but only if both tables have the exact same metamethod for __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