Why put local in front of a function?

Yeah so I have been thinking about this for a while now I have seen some people
write their functions like this:

local function example()
	
end

instead of just writing it normally writing it like this

function example()
	
end

Is there a reason behind this? and does it work the same as variables?

2 Likes

In some cases yes, how to place a function inside another function

script.Changed:Connect(function()
	function A()

	end
end)

A will be underlined in red, it is the same thing that happens with the variables that are defined within the function, but in general using or not using local is the same.

3 Likes

The difference between local and global variables is the way they’re stored.

Local variables are stored in the stack, and as such tend to be faster to access. Inside functions new stack frames are created and any scoped variables we placed there, and that’s why the variables have to be local.

Global variables are stored on a table internally, are a bit slower to access but can be used within any given scope.

Edit: I forgot to explain why people actually use them for functions, lol. As SOTR rightfully said, you can then make them in events, other functions (and then have access to other variables due to closures), etc, but people will use local as it just tends to be faster and looks better.

7 Likes

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.

From the variables article:

Global functions cause more lag I think

use these

Ok, ok so what everyone is saying i the replies is that I should put local in front of my functions from now on?

2 Likes

You should, unless you need your function as a global function so that you can call it from any scope.