Indexing through a table which can act as a function?

Can’t find any resources to this in DevForum, considering I don’t know the actual name anyway

Heyo, I am currently creating a brand new UI framework that is designed to be completely modular. While creating some of the components, I have a question in my mind: Can you index through a table, and the table itself can also act as a function?

If you have a stroke reading the title, or purely don’t understand my level of English, I’ll explain it here.

I’ve seen modules with this type of design, so I am quite sure this is possible.

local module = require(script.mod) -- a table
module() -- a function
module.indexOne() -- also a function

Et cetera.

I know this will probably require some metatables magic but I am not sure how should I go implement something like that. If someone can help me out and know how to implement this, please do!

Module script

local function dostuff(yes)
  print(yes)
end

local myTable= {
  func1 = dostuff
}

return myTable

Normal script

local module = require(ModuleScript)

module.func1("hello")

Output

hello

How would you go implement this as well meanwhile preserving the indexing?

local module = {}

local mt = {}

function mt:__call(...)
    --self is the module in this situation
    print(tostring(self).." was called with arguments", ...)
end


function module.PrintHi()
    print("Hi!")
end

setmetatable(module, mt)

module.PrintHi()
module(true, "hello", 4)
3 Likes

Thanks, I forgot __call existed. I guess I learnt something aswell

1 Like