Why do people store there functions as a variable?

Its very common that I see people use local function() instead of just function(). Why do people do this? What does it differ from using a plane out function? What does it benefit?

1 Like

I think its so you can garbage collect the variable, avoiding memory leaks.

2 Likes

I will wait for more feedback on this topic before I mark a solution but I appreciate the help.

Like “free” variables inside a function, it gives an error
image

local variables are faster and you avoid the previous problem, is the same as this and is considered as any value

local B = function()
	-- insert cool code
end

Local variables are obtained faster than global variables because they’re integrated into the environment in which they were created. If possible, you should always use local variables over global variables, unless there’s a specific reason otherwise.

Because your function becomes a global variable if you don’t use local.

function name() end
is the same as
name = function() end
in vanilla Lua

The same way
local function name() end
and
local name = function() end
are equivalent

As mentioned above, it is better to use local variables if possible. Local variables are stored in registers and are much faster. Global variables are stored in a global table. In other words, the following are equivalent and very slow:

local GlobalTable = {}
GlobalTable.Name = "test"

Name = "test"
2 Likes

And if I am correct, a global function is a function declared in one script but can be used in another?

Yes, you can use getfenv to access global functions, but this is very messy as you cannot outright get the environment (global table) using other scripts. You first need to call getfenv() from the script you have the global variable in, then parse it to another script using a ModuleScript or some other way (BindableEvents won’t work as they encode and decode the parsed values into JSON, effectively parsing a clone).

If you want to avoid all this hassle and just want global variables, use the _G global accessible from all scripts.

-- first script
_G.test = 1

-- second script
task.wait() -- avoid printing before the value is set
print(_G.test) --> 1