Meta-Functions for math operators
Posted: 27 Feb 2024, 20:18
I was working on a Vec2 lib, it would be so much nicer if we had meta-functions for math.
Example:
I think LUA sets a good example of how it's done:
https://www.lua.org/pil/13.1.html
http://phrogz.net/lua/LearningLua_MetatableEvents.html
Example:
Code: Select all
a := Vec2(150, 80)
b := Vec2(30, 490)
c := a + b ; c := Vec2(a.x + b.x, a.y + b.y)
d := a + 5 ; d := Vec2(a.x + 5, a.y + 5)
e := 5 - b ; e := Vec2(5 - b.x, 5 - b.y)
class Vec2 {
__New(x := 0, y := 0) {
This.x := x
This.y := y
}
__Add(a, b) {
if IsNumber(a)
return Vec2(a + b.x, a + b.y)
if IsNumber(b)
return Vec2(a.x + b, a.y + b)
if !(a is Vec2)
throw ValueError('Math error', -1, a)
if !(b is Vec2)
throw ValueError('Math error', -1, b)
return Vec2(a.x + b.x, a.y + b.y)
}
__Sub(a, b) {
if IsNumber(a)
return Vec2(a - b.x, a - b.y)
if IsNumber(b)
return Vec2(a.x - b, a.y - b)
if !(a is Vec2)
throw ValueError('Math error', -1, a)
if !(b is Vec2)
throw ValueError('Math error', -1, b)
return Vec2(a.x - b.x, a.y - b.y)
}
}
https://www.lua.org/pil/13.1.html
http://phrogz.net/lua/LearningLua_MetatableEvents.html