Add properties to Lua function

What I want to achieve is being able to have properties returning on a ModuleScript that returns a function.

This is my current code:

local module = function()
-- function code, etc
end

module.hey = function()
print("hey")
end

return module

What I want to achieve is being able to do this:

module("string and whatever")

module.hey()
1 Like

You can do that with metatables

I would suggest readin its very useful if you want to use lua to its fullest

Code example

local module = {}

local meta = {} -- the metatable

module.hey = function()
  print('hey')
end

meta.__call = function(t, ...) -- __call allows for the table to be called like a function
  print('module has been called')
end

return setmetatable(module, meta) -- sets the metatable (also returns the table)

somewhere else

module.hey() -- 'hey'

module() -- 'module has been called'
1 Like

image

.hey seems to work but __call doesn’t seem to be working correctly.

local module = {
    hey = function()
        print("hey")
    end
}

local meta = {}

meta.__call = function (message: string)
    print(message)
end

return setmetatable(module, meta)

I think the first argument of call is the table the metatable is linked to, if I remember that correctly that is. Try this:

local module = {
    hey = function()
        print("hey")
    end
}

local meta = {}

meta.__call = function (_,message: string) --> or tbl:table, message:string
    print(message)
end

return setmetatable(module, meta)

EDIT:
Also for anyone uh in the future reading this please note that the original solution came from this guy:

I just fixed the code the author of this post wrote.

1 Like