Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How does the __call = function work in this Lua OOP tutorial?

Here is the link to the tutorial where I got the following example. Here is the script:

local MyClass = {}
MyClass.__index = MyClass

setmetatable(MyClass, {
  __call = function (cls, ...)
    return cls.new(...)
  end,
})

function MyClass.new(init)
  local self = setmetatable({}, MyClass)
  self.value = init
  return self
end

-- the : syntax here causes a "self" arg to be implicitly added before any other args
function MyClass:set_value(newval)
  self.value = newval
end

function MyClass:get_value()
  return self.value
end

local instance = MyClass(5)
-- do stuff with instance...

I understand the first example in the tutorial to which I provided a link. The main question I have is about line 5 above. How does the __call function work and what is its purpose. I would be really grateful if someone could help me understand this. Thanks!

3 comments

1

There is a full list of all the metamethods and all the definitions of them here.

0

That does not help me understand what it is doing.

0

Just what __call does

1 answer

✓ Accepted answer

__call is fired when you call it. For example, you could do

local foo = setmetatable({}, {__call = print})

and when you call it like foo(2, 6, 3), you get tableAddress 2 6 3.

In this example, it makes it work, like if we have

local Vector3 = {}
Vector3.__index = Vector3

setmetatable(Vector3, {
  __call = function (cls, ...)
    return cls.new(...)
  end,
})

so it works with Vector3.new(1, 1, 1) and Vector3(1, 1, 1) (although the return value would only contain the first 1)

Hope this helps!

4 comments

0

What is cls and how is it used? Also when it returns cls.new what is it returning?

0

It's the table that was being called (aka which table the metatable is attached to aka Vector3)

0

so its saying table.new(...) with the argument being what?

0

The argument would be whatever you passed in when you called the table. So, 1, in this example.

This discussion is preserved as it was. New answers, comments, and votes are closed.