How to declare a variable as a function

In Lua you can declare what datatype a variable is, for example

local myNumber: number = 2

and

local myString: string = "hello"

but how would you declare a variable as a function?

local myFunction: function = function()
    -- This isn't how it's used in my actual code, just a simplified example
end

I’ve been looking around for a while and haven’t been able to find anything, I thought asking here would be a good idea.

Just make a seperate function and declare a new variable that uses it.

local function MyFunction()
-- code
local myVariable = 1 -- example
return myVariable
end

local myVariable
myVariable = MyFunction()
print(tostring(myVariable)) -- prints 1

If this isn’t what youre looking for, I’m curious as to what you mean by “a variable that is a function”, because

local function

Already makes a name/variable for the function. just with () at the end to signify its a function

That wouldn’t really work in my case since the function is defined in a seperate module

This is my current code:

local Container = require(script.Container)

for cIndex, category in Container.Data do
	for sIndex, setting: {Name: string, Type: string, Min: number, Max: number, Function: } in category do
		if setting.Type == "NumberInput" then
			local frame = script.NumberInput:Clone()
			
			frame.TextBox.Changed:Connect(setting.Function)
		end
	end
end

Forgive me if i’m wrong, because I seldom work with module scripts, but couldn’t you just do Container:MyFunction() instead of declaring the function as a variable?

Functions can be typed in the format () -> () where the first parenthesis is the parameter types and the second is the return types.

e.g a function that takes a number and returns a number has type (number) -> (number)

local double: (number) -> (number) = function(n)
	return n * 2
end

The parameter types can also have a name associated to them
(parameter1: type, parameter2: type) -> (type)

6 Likes

Ah yes I forgot about the arrow thing

oh thank you so much! this was exactly what I’ve been looking for!

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