class.lua icon indicating copy to clipboard operation
class.lua copied to clipboard

Operator overload

Open JonathanOrr opened this issue 2 years ago • 0 comments

This pull request aims to add operator-overloading to the classes created by the original library

The usage example of the added feature is as follows:

    require "class"

    Vector2 = Class:extend()
    function Vector2:init(x, y)
        self.x = x
        self.y = y
    end

    -- attributes --
    Vector2:set{x = 0, y = 0}

    -- operator overloading --
    function Vector2:__add(other)
        return Vector2(
            self.x + other.x,
            self.y + other.y
        )
    end

    function Vector2:__tostring()
        return string.format("Vector2(%f, %f)", self.x, self.y)
    end

    -----------------------------------------------------------
    local vec1 = Vector2(1, 2)
    local vec2 = Vector2(3, 4)
    print(vec1 + vec2)

The output of the example above is:

    "Vector2(4.0, 6.0)"

JonathanOrr avatar Aug 16 '23 13:08 JonathanOrr