How to call a function from a variable using the 'colon' syntax

This is what I want to achieve:

-- Module
local module = {}
module.Variable = "Hello world"
function module:Func()
	print("Executed function")
	print(self.Variable)
end

-- Script
module:Func()

Executed function
Hello world

But how do you do the same when calling the function from a variable (e.g. because you want to check it exists beforehand)?

-- Module
local module = {}
module.Variable = "Hello world"
function module:Func()
	print("Executed function")
	print(self.Variable)
end

-- Script
local funcName = "Func"
local func = module[funcName]
if func then
	func()
end

error: attempt to index nil with ‘Variable’

(because self is passed along with the arguments when using ‘.’ over ‘:’ )

-- Module
local module = {}
module.Variable = "Hello world"
function module:Func()
	print("Executed function")
	print(self.Variable)
end

This module should have a return module at the end of it, make sure you add that, also “self.Variable” should be module.Variable. It should also be module.Func(), as opposed to module:Func()

-- Script
local funcName = "Func"
local func = module[funcName]
if func then
	func()
end

I’m not entirely sure what the purpose of this is, but “module[funcName]” would be searching for a table as oppose to a function. You need to actually call the function, ex;

local func() = module.Func()

Using the colon is just “syntactic sugar” that injects self as the first argument.

-- This...
function modue:Func()
end
-- ...is exactly the same as this:
function module.Func(self)
end

-- This...
module:Func()
-- ...is exactly the same as this:
module.Func(module)

Thus, to answer your question, you just need to pass the table as the first argument to the function:

local funcName = "Func"
local func = module[funcName]
if func then
   func(module)
end
12 Likes

What do you mean? What does the string represent? A function name, a key in a table?

You want to call a function accessed by a string with colon syntax?

You’ll need to do this instead.

object[string](object, function parameters)

2 Likes