Storing Function as variable

I’m making a game in which a for-in loop iterates through instances, and requires the module parented under the instance.
What I have in the module:

return require(game.ReplicatedStorage.Formulas).MiningSpeedCost

I store the result of this in a variable:

local mod = require(v.ModuleScript) -- v is what the loop iterates

Is it possible to store a function into a variable like this and call mod(parameter)?
I’ve tried different ways, but I don’t know the root of the problem.

1 Like

I believe a better visual, i.e. the semi-full thing would illustrate your goal a little better

1 Like

module:

return require(game.ReplicatedStorage.Formulas).MiningSkillCost

loop:

for i,v in ipairs(frame:GetChildren()) do
    local mod = require(v.ModuleScript)
	game.ReplicatedStorage.UpdateStats.OnClientEvent:Connect(function()
		Set(v,mod)
	end)
end

function Set():

local function Set(v,mod)
	v.Cost.Text = "$"..tostring(module:Suffix(mod(plr)))
	v.Button.Text = "Upgrade"
	local lvl = game.ReplicatedStorage.GetStat:InvokeServer("Mining Speed")
	local child = game.ReplicatedStorage.Formulas:FindFirstChild(v.Name)
	local list
	if child then list = require(child)end
	local max = require(game.ReplicatedStorage.Formulas.MaxStats)
	if lvl < max[v.Name] and list then
		v.Change.Text = list[lvl].." sec --> "..list[lvl+1].." sec"
	elseif list then
		v.Change.Text = list[lvl].." sec"
		v.Button.Text = "Maxed!"
	elseif lvl >= max[v.Name] then
		v.Button.Text = "Maxed!"
	end
end

I’m still not sure what you are trying to do? What do you mean by storing functions in variables? You do it all the time. For example, Set is a variable pointing to a function.

Unless you’re talking about something else? Doesn’t this do what you want it do?

Lets say this:

local func = function() return "Hi" end

How would you implement that?

Also if it were a module:

return require(module).Function1() -- If this were to have: function() return "Hi" end

And a script had this:

local func = require(moduleAbove)

With this, could you say func(something)?

return require(module).Function1

With the parentheses omitted.

Remember that Lua has first-class functions, and that they are a datatype, first class means they have the same rights as other conventional value (like strings, numbers, etc) in where variables can contain them, they can be passed around as arguments, and can be returned by functions.

1 Like

Yeah, that’s what I had.
The error that caused me to post this was from a call that didn’t pass the function as a parameter, my bad.

1 Like