How to create a generic function

Hello everyone!

I want to make a generic function like the embedded lua module “table”,
there is a function that I can use in 2 different ways, for example.
The first way:
image
The second way:
image

Trying to do this, it throws an error “DuplicateFunction”

function test(array, var, text)
	print(array, var, text)
end
 -- DuplicateFunction: (5,10) Duplicate function definition: 'test' also defined on line 1
function test(array, text)
	print(array, text)
end

local a = 2
test({1, 3, 4}, a, "hello world")
test({1, 3, 4}, "hello world")

The way that this is typically done is to check the types of the arguments using type & typeof, and to use if statements to separate the different functionality.

Those functions in C/C++ (which is what Roblox is written in) are, to my knowledge, a lot easier to write, and are called function overrides. In lua, there aren’t any function overrides, so you have to describe them yourself.

For example, you could write your functions above like this:

local function testFirstFunctionality(array, var, text)
	-- first function (third argument is present or the second argument isn't a string)
end

local function testSecondFunctionality(array, text)
	-- second function (second argument is a string, third is nil)
end

local function test(array, varOrText, text)
	if type(varOrText) == "string" and type(text) == "nil" then
		return testSecondFunctionality(array, text)
	else
		return testFirstFunctionality(array, varOrtext, text)
	end
end

In general, it might be nicer to just write two separate functions that do what you want in the different cases, and, that’s often not too bad, but, it depends on your use case and your goals and your preferences.

4 Likes

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