Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Operator overload #1

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions class.lua
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,32 @@ 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({})
if obj.init then obj:init(...) end

-- overload operators
opOverload(self, obj)

return obj
end

Expand Down