Whats the difference between local function and function?

I know this post exist many times, but actually I still didnt understand it. What does local do? and what is the difference between local function and function. Can someone give me a clearly explanation just for me.

pls dont just give a code. I want understand it really good.

1 Like

Here ya go lua-users wiki: Locals Vs Globals

Global’s affect everyone’s game, for example if you wanted to script a house with an opening door you would use global, but local is for personal servers or particular players.

That is local scripts vs Server scripts. They are asking the difference between:

local function AddNumbers()

vs

function AddNumbers()

The main difference is that you can call a global function in code above the function. So you can do this with a global function, while you couldn’t do that with a local function.

print(AddNumbers(10, 20))
function AddNumbers(1, 2)
      return(1 + 2)
end
3 Likes

And what is the exactly benefit about that. And local functions arent necessary for server script if I understand that right?

This is an advanced question and the differences and benefits of using one over the other can only be appreciated when you have enough experience in lua.

The simple answer is that functions (without using the word local) are scoped throughout the code, that is, they are global no matter where they are. for example this code will print “Hello”.

if true then
	function hello()
		print("Hello")
	end
end

hello()

this one too:

function some()
	function thing()
		function hello()
			print("Hello")
		end
	end
	thing()
end
some()

hello()
6 Likes

To explain what @Auxintic posted, locals are basically ‘loaded’ into your local memory which makes accessing them a little bit quicker than global functions or variables.

This also means like @MillaGamerF said, that you can access global functions and variables anywhere in your script no matter where it was defined. Whereas with local functions and variables you can only access it in the function in which you define it.

Hope this helps, let me know if you need more clarification!

8 Likes

That’s entirely false. Your code will error:

image

The real answer is scope.

5 Likes

That’s the word I was looking for! haha

4 Likes