From 321df57c49119c15463c44677fc30c3087529426 Mon Sep 17 00:00:00 2001 From: JonathanOrr Date: Wed, 16 Aug 2023 22:57:07 +1000 Subject: [PATCH 1/2] [class] add operator overloading private method --- class.lua | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/class.lua b/class.lua index 8540297..a4f1576 100644 --- a/class.lua +++ b/class.lua @@ -87,6 +87,24 @@ function Class:set(prop, value) end end +---perform operator overloading for an new object of a class +---@param class table +---@param obj table +local function opOverload(class, obj) + local opKeys = { + "__mode", "__tostring", "__len", "__pairs", "__ipairs", "__gc", "__name", "__close", --Special Operators + "__unm", "__add", '__sub', "__mul", "__div", "__idiv", "__mod", "__pow", "__concat", --Mathematic Operators + "__eq", "__lt", "__le", --Equivalence Comparison Operators + "__band", "__bor", "__bxor", "__bnot", "__shl", "__shr" --Bitwise Operators + } + local objMt = getmetatable(obj) + for _, operator in pairs(opKeys) do + if class[operator] then + objMt[operator] = class[operator] + end + end +end + -- create an instance of an object with constructor parameters function Class:new(...) local obj = self:extend({}) From 5b4f3902731f60ae1b3d40005b0162c6930f85de Mon Sep 17 00:00:00 2001 From: JonathanOrr Date: Wed, 16 Aug 2023 22:57:54 +1000 Subject: [PATCH 2/2] [class] add support for operator overloading --- class.lua | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/class.lua b/class.lua index a4f1576..df3dd5e 100644 --- a/class.lua +++ b/class.lua @@ -109,6 +109,10 @@ end function Class:new(...) local obj = self:extend({}) if obj.init then obj:init(...) end + + -- overload operators + opOverload(self, obj) + return obj end