lua-users home
lua-l archive

Operator overloading using tolua++

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi,
 
 I'm using tolua++ (1.08pre4) to bind some C++ vector math classes to
Lua 5.1-rc, and I'm having trouble making math operators convenient to
use from Lua. Say I have a class like this
 
class Vec2 {
 ...
 Vec2 operator*(float s);
 ...
};
 
and tolua++ binds my operator*, I can do this in Lua: v1 = Vec2(1, 2)
* 5
However, this fails: v1 = 5 * Vec2(1, 2)
Because tolua++ doesn't know how to bind my global C++ operator*(float,
Vec2). I'm trying to find a way to make this code work.
 
My attempt at a workaround was this:
 
Vec2[".mul_orig"] = Vec2[".mul"] -- save tolua-generated mul
operator
Vec2[".mul"] = function( lhs, rhs ) -- .mul is called from Vec2's
__mul metamethod
 if type( lhs ) == "number" then
 return Vec2[".mul_orig"]( rhs, lhs ) -- switch operand order and
call original mul
 else
 return Vec2[".mul_orig"]( lhs, rhs )
 end
end
The idea is to call the original wrapped operator* with the order of the
operands swapped. Unfortunately, this does not work. With or without my
workaround the error message I get when executing "v1 = 5 * Vec2(1,2)"
is "Attempt to perform operation on an invalid operand".
According to the lua documentation I would expect Lua to call Vec2's
__mul metamethod, unless builtin numbers have their own metatable. I
tried to get the metatable of a number, but it fails from both a script
and from the Lua C api.
Is there a way to change my metatables or operator function to make my
call succeed?
Any hints would be greatly appreciated.
Thanks,
-Thorsten Scheuermann

AltStyle によって変換されたページ (->オリジナル) /