How to call a function with colons

Hi! So this is what I want to achieve:

local function :multiply(self, numberToMultiplyWith)
      self = self * numberToMultiplyWith
end
local myNumber = 1

myNumber:multiply(5)

print(myNumber) -- prints 5

So is there any way I could make something like this work? I also can’t add colons as the first letter of a function. Thank you.

1 Like

t:f() is a sugar syntax for t.f(t) so

local t = { }
function t.f(a, b)
   print(a == t, b);
end;
t:f(1)

prints

true, 1

Also you cannot index doubles in Lua unlike JavaScript, C#, Python, etc :frowning:

1 Like

You could got for an object-oriented approach, but please don’t actually use this.

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

I can repeat it a million times if I wanted to, don’t actually use this

3 Likes