Docs > Operators and Overloading
Several operators are provided: +
, -
, *
, and /
function as normal. %
and ^
represent modulus and exponentiation, respectively. <
, >
, <=
, >=
, ==
, and !=
behave as normal. Objects can overload these operators using several functions: - __add
for +
, - __sub
for -
, - __mul
for *
, - __div
for /
, - __mod
for %
, - __pow
for ^
, - __lt
for <
, - __gt
for >
, - __le
for <=
, - __ge
for >=
, - __eq
for ==
, - and finally, __neq
for !=
. For example, to create an object A
which can be added to, we might do: object A(n) { fn __add(other) { n + other } }
Then we can do something like the following: obj = new A(5) obj + 6
This should evaluate to 11
. ## Overloading Str and Bool Representation One thing you may have noticed is that when printed on the REPL, objects use the native Ruby format, ie. `. To get around this, we can overloading
asstr: ``` object A(n) { # SNIP fn __as_str() { n.__as_str() } } ```
asstr()should take no arguments and return a str. As well, you may have noticed that all objects are truthy. You can get around this using
asbool: ``` object A(n) { # SNIP fn __as_bool() { false } } ``` This would make all instances of
Aevaluate to falsy, rather than truthy. Like
asstr,
asboolshould take no arguments and return a boolean. ## Calling It is quite simple to make an object callable. You have to define two properties:
arity, the number of arguments the object should take, and
_call`, a function taking that many arguments. For example: object A(n) { # SNIP __arity = 2 fn __call(a, b) { ... } }