-
Notifications
You must be signed in to change notification settings - Fork 2
Operator Overloading Tutorial
Sometimes, it would be nice to make a table behave like a number or a string. Making a table return some useful information when tostring()ed would also be great. Thankfully, due to Lua's awesomeness, this is possible.
Each instance has a meta table. This table is the metatable of the instance. You can modify this at any time to alter the behaviour of the instance, with the exception of the __index metamethod.
Imagine a Vector2 class. It could look somewhat like this:
class "Vector2" {
x = 0;
y = 0;
}
function Vector2:Vector2( x, y )
self.x = x
self.y = y
end
function Vector2:add( other )
return Vector2( self.x + other.x, self.y + other.y )
endIt would be great to be able to write vec1 + vec2 instead of vec1:add( vec2 ), and by doing this, you can:
function Vector2:Vector2( x, y )
self.x = x
self.y = y
self.meta.__add = self.add
endNow, when you try to add something to a Vector2, it will call add() as if you're calling the function.
A Vector2 might also want a nice tostring() output. As this is so common, the class library handles it automatically. All you need to do is define a Class:tostring() method, and it is automatically added to the metatable.
function Vector2:tostring()
return "(" .. self.x .. ", " .. self.y .. ")"
endNow, when calling tostring( vec1 ), it will output something like this: "(1, 5)".
Sheets uses operator overloading for a couple of things, but mainly parenting. You can do child = parent + child with classes that contain children to add the child to the parent.
- Exception
- DynamicValueException
- ExpressionException
- IncorrectConstructorException
- IncorrectParameterException
- ParserException
- ResourceLoadException
- ThreadRuntimeException