Skip to main content

arithmetic

Trait arithmetic 

Source
pub trait arithmetic {
    // Provided methods
    fn __add(&self, other: any) -> any { ... }
    fn __sub(&self, other: any) -> any { ... }
    fn __mul(&self, other: any) -> any { ... }
    fn __div(&self, other: any) -> any { ... }
    fn __mod(&self, other: any) -> any { ... }
    fn __pow(&self, other: any) -> any { ... }
    fn __unm(&self) -> any { ... }
    fn __idiv(&self, other: any) -> any { ... }
}
Expand description

Metamethods controlling the arithmetic operators.

Each event fires when the corresponding operator is applied to a value that does not support it natively — for example, adding two tables looks for an __add field in either operand’s metatable and calls it with both operands.

Provided Methods§

Source

fn __add(&self, other: any) -> any

The addition (+) operation.

§Examples
local mt = { __add = function(a, b) return a.n + b.n end }
local a = setmetatable({ n = 1 }, mt)
local b = setmetatable({ n = 2 }, mt)
print(a + b)    --> 3
Source

fn __sub(&self, other: any) -> any

The subtraction (-) operation.

§Examples
mt.__sub = function(a, b) return a.n - b.n end
print(a - b)    --> -1
Source

fn __mul(&self, other: any) -> any

The multiplication (*) operation.

§Examples
mt.__mul = function(a, b) return a.n * b.n end
print(a * b)    --> 2
Source

fn __div(&self, other: any) -> any

The division (/) operation.

§Examples
mt.__div = function(a, b) return a.n / b.n end
print(a / b)    --> 0.5
Source

fn __mod(&self, other: any) -> any

The modulo (%) operation.

§Examples
mt.__mod = function(a, b) return a.n % b.n end
print(a % b)    --> 1
Source

fn __pow(&self, other: any) -> any

The exponentiation (^) operation.

§Examples
mt.__pow = function(a, b) return a.n ^ b.n end
print(a ^ b)    --> 1.0
Source

fn __unm(&self) -> any

The negation (unary -) operation.

§Examples
mt.__unm = function(v) return -v.n end
print(-a)    --> -1
Source

fn __idiv(&self, other: any) -> any

The floor division (//) operation.

§Examples
mt.__idiv = function(a, b) return a.n // b.n end
print(a // b)    --> 0

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§