gpt4 book ai didi

c++ - 如何使 SWIG 绑定(bind)类在 Lua 中使用运算符?

转载 作者:行者123 更新时间:2023-11-30 04:59:22 24 4
gpt4 key购买 nike

在这里,我有一个名为 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

我应该如何更正我的类以便我可以使用运算符?

最佳答案

您必须重载要使用的每个运算符,即 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

关于c++ - 如何使 SWIG 绑定(bind)类在 Lua 中使用运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51240738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com