How to make a function with name as a concatenated string?

Hi everyone, so today I was making a utilities module to create easy access functions, but I ran into a problem.

image

My module tree

I started to make functions like utilities.random() and such, but I tried to optimise my code with a for loop

--Inside the "utilities" module
local utilities = {}

for i, v in pairs(script:GetChildren()) do
	local name = v.Name
	local funcName = "utilities"..name
	funcName = function()
		require(script:FindFirstChild(name))()
	end
	
	print(funcName)
end

return utilities

as you can see, I was trying to make a function with a concatenated string, as seen in funcName, then set it as a function, but after debugging I found out that the name was not saved in the function:

image

The initial utilities.random return in the console is funcName before setting it to a function, function: 0xaef0a86404def21f is after changing funcName into a function

Any ideas how I can achieve my goal? Any help is appreciated, thanks!

It might be because you forgot to include it in the returned table

What exactly do you mean by the returned table?

You make a table called “utilities”, which you return
when you require the module script, studio gives you this table, however you never add anything to it

funcName is the variable that references the function. Functions do not have names, the variables that point to them are named.

You can do something like

local utilities = {}

for _, m in pairs(script:GetChildren()) do
	utilities[m.Name] = require(m)
end

return utilities

You might try this:

--Inside the "utilities" module
local utilities = {}

for i, v in pairs(script:GetChildren()) do
	local name = v.Name
	local funcName = "utilities"..name
	utilities[funcName] = function()
		require(script:FindFirstChild(name))()
	end
	
	print(funcName)
end

return utilities

Where are you getting v from? Are you referring to _?

Alright, let me check this real quick

Oh yeah, sorry. Try m.Name instead of v.Name.

1 Like

Also triplestryke321 has a more optimized version of what I gave

1 Like

I think adding an extra set of parenthesis to the require() statement is wrong, because it calls the function that you are trying to store. Removing it would probably work though. The other issue is the utilities table would end up looking like

utilities = {
    utilitiesgenerateTeam = function() --[[generate team]] end,
    utilitiescreateTable = function() --[[create table]] end,
    -- etc
}

So you would call a function like

utilities.utilitiesgenerateTeam(args)

Nah, it worked just fine in the old way, the () were needed, as factory functions were stored in the module

Do the modules under utilities only store one function?
If so I’d recommend just storing all of them in the utilities module

Some of them store multiple functions, I will use a different method for those

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