2010-12-23 18 views
0

我在我的C++应用程序中嵌入了Lua。嵌入Lua和重载的C++运算符

我有一个类Foo,我正在接触Lua(通过tolua ++)。

符重载一些运营商如下图所示:

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 
+0

当你尝试时会发生什么? – 2010-12-23 11:11:35

回答

3

根据文档tolua ++支持此 - 见Binding classes and methods - Overloaded operators

tolua自动绑定下列二进制运算符:

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

对于关系运算符,toLua还自动返回的0值转换成无,所以在C中的虚假在Lua中变成虚假的。

作为一个例子,假设的是,在上面的代码中,代替具有:

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

我们有:

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

在这种情况下,在Lua,我们可以简单地编写:

p3 = p1 + p2

0

在Lua中可能需要的行为是可能的。我不知道如何用tolua ++来做到这点(我从来没有用过),但是可以通过为你的用户数据定义metamethods来实现。详情请看Relational metamethods。这可能会给你一个线索。