gpt4 book ai didi

c++ - 嵌入式 Lua 和重载的 C++ 运算符

转载 作者:行者123 更新时间:2023-11-28 01:09:00 27 4
gpt4 key购买 nike

我在我的 C++ 应用程序中嵌入了 Lua。

我有一个 Foo 类,我将它暴露给 Lua(通过 tolua++)。

Foo 重载了一些运算符,如下所示:

class Foo
{
public:
explicit Foo(const int i);
bool operator==(const Foo& foo) const;
bool operator< (const Foo& foo) const;
int operator-(const Foo& foo) const;

private:
int m_ival;
};

我的问题是,在我的 Lua 脚本中,我可以在我的 Lua 脚本中使用如下所示的表达式吗:

f1 = Foo:new(42)
f2 = Foo:new(123)

if f1 < f2 then
print(f2 -f1)
end

最佳答案

根据文档,tolua++ 支持这个 - 参见 Binding classes and methods - Overloaded operators :

tolua automatically binds the following binary operators:

operator+   operator-   operator*   operator/ 
operator< operator>= operator== operator[]

For the relational operators, toLua also automatically converts a returned 0 value into nil, so false in C becomes false in Lua.

As an example, suppose that in the code above, instead of having:

Point add (Point& other); // add points, returning another one

we had:

Point operator+ (Point& other); // add points, returning another one

In that case, in Lua, we could simply write:

p3 = p1 + p2

关于c++ - 嵌入式 Lua 和重载的 C++ 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4517550/

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