Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

What exactly are "local" functions?

I know how to use a function, but i have no idea what a local function is or how and what it does.

Thanks for your time.

1 answer

Function definitions are actually just special syntax for assignment, as the manual explains:

function foo()
	-- do thing
end

-- IS EQUIVALENT TO

foo = function()
	-- do thing
end

local functions are similar, but maybe slightly different from what might be expected:

local function foo()
	-- do thing
end

-- IS EQUIVALENT TO
local foo = nil
foo = function()
	-- do thing
end

Splitting the local from the initialization allows local functions to be recursive.

Why

Avoiding global variables as much as possible is good practice because it reduces the chance for bugs.

This especially goes for global functions being (re)defined!

This code is buggy:

function makePartFlash(part)
	function setColor(color)
		part.BrickColor = BrickColor.new(color)
	end

	while true do
		wait(1)
		setColor("Bright blue")
		wait(1)
		setColor("Bright red")
	end
end

spawn(function()
	makePartFlash(workspace.A)
end)
spawn(function()
	makePartFlash(workspace.B)
end)

That's because the function setColor of the second call will overwrite the setColor of the first call -- only one of the parts will change color!

ROBLOX will warn you about this, saying

Global 'setColor' is only used in the enclosing function; consider changing it to local

The script can be fixed as follows, which makes sense, since all your variables should be local inside a function!

function makePartFlash(part)
	local function setColor(color)
		part.BrickColor = BrickColor.new(color)
	end

	while true do
		wait(1)
		setColor("Bright blue")
		wait(1)
		setColor("Bright red")
	end
end

spawn(function()
	makePartFlash(workspace.A)
end)
spawn(function()
	makePartFlash(workspace.B)
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.