How to pass an Object function as a parameter?

So, we all know how to pass a function as a parameter in another function. Looks like this:

function foo()
   return 1
end
function bar(functionRef)
   print(functionRef())
end
bar(foo)
--this will print 1

The trick is to just not CALL the function by instead not using parentheses. Simple enough, but what about functions that are part of an object?
Ie this:

--this script makes a simple object with a Foo function inside.
--Its designed to print Index stored when Foo is called
local Module={}
Module.__index=Module

function Module:Foo()
  print(self.Index)
end

function Module.Init(Index)
  local Object ={}
  setmetatable(Object,Module)
  Object.Index=Index
  return Object
end
return Module
--This script is inside inheriter
local Module = require(Module).Init(1)
Module:Foo() --this will print 1, as expected.

function Bar(functionRef)
  functionRef()
end

Module:Foo --this is unusable as a parameter in a function
Bar(Module:Foo) --this is unacceptable. :(

As you can see, I just want to know how to pass an object function as a parameter in a different function. This could be extremely help for binding/connecting events too. Any help is appreciated

EDIT:
I tried this: Module.Foo(Module) but since the function is being call immediately, it still isnt a parameter. Very sad :frowning:

Use a dot .

--This script is inside inheriter
local Module = require(Module).Init(1)
Module:Foo() --this will print 1, as expected.

function Bar(functionRef)
  functionRef(Module) -- equivalent of Module:Foo()
end

Bar(Module.Foo)
1 Like

This would work if Bar knows or has access to the object. In my case, it does not. and will not, since their are multiple objects

You can pass the object as a parameter:

local Module = require(Module).Init(1)
Module:Foo()

function Bar(functionRef, ...)
  functionRef(...) -- Passes the object and any additional parameters
  -- equivalent of Object:Method(...)
end

Bar(Module.Foo, Module)

Sorry, but it looks like the easiest way to accomplish what i wanted was an anon function

local Module = require(Module).Init(1)
Module:Foo() --this will print 1, as expected.

function Bar(functionRef)
  functionRef()
end

Module:Foo --this is unusable as a parameter in a function
Bar(function() Module:Foo() end)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.