Hi! Tried to recreate something incapaz made (thanks incapaz by the way), as I understand the basics of OOP now.
Here is my script (doesn’t work, error: ServerScriptService.Script:17: attempt to index number with ‘multiply’)
local methods = {
multiply = function(number1, number2)
number2 = {val = number2}
return number1.val * number2.val
end
}
local metaTable = { __index = methods }
local function setNumber(num) --3 for example
num = {val = num} -- val is now 3
local ret = setmetatable(num, metaTable)
return ret
end
local num = setNumber(5)
num.val:multiply(2)
Here is his script: (working)
local methods = {
multiply = function(this, num)
this.n = this.n*num
end
}
local mt = { __index = methods }
local function Number(n) -- js :3
return setmetatable({ n = n }, mt)
end
local num = Number(5)
num:multiply(2)
print(num.n) -- 10
The mistake must be that you are sending this in the function braces.
multiply = function(this, num)
The “this” keyword I think can’t be a parameter.
I do OOP in java too.
Just adding 2 other ways to create your own number class supporting multiplication:
local function tonumber(n)
local mt =
{
__mul = function(self, n)
n = type(n)=="table" and n.val or n;
local v = self.val * n
self.val = v;
return v;
end,
__tostring = function(this)return this.val end
}
return setmetatable({val = n}, mt)
end
local n1 = tonumber(2);
local n2 = tonumber(10);
print(n1, n2)
local value = n1 * n2 --// you can only multiply tables if they've both got a __mult m.method
print(value, value * 10)
print(n1 * n2)--// doing this will set the value to the result since we do that internally handling multiplication
--// or
local function tonumber(n)
return setmetatable({val = n}, {__index = {
multiply = function(self, n)
local v = self.val * n
self.val = v;
return v
end
};
__tostring = function(obj)return obj.val end})
end
local n = tonumber(10);
print(n);
local result = n:multiply(10);
print(n ,result)