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

What's the difference between a local variable and a variable?

I'm going to preface this by saying that I don't wan't any code, but rather to further my understanding about scripting.

I've been scripting for about 2 years now, and I'm starting to get serious about it. And one question that I've been asking myself is what is the difference between a local variable and a regular variable.

Regular Variables


function removeItem()
	player.Backpack.Item:Destroy()

end




while true do
	wait(3)
	
	players = game.Players:GetChildren()
	
	player = players[math.random(1,#players)]
	
	removeItem()
	
	
end

Local Variables


function removeItem()
	player.Backpack.Item:Destroy()

end




while true do
	wait(3)
	
	local players = game.Players:GetChildren()
	
	local player = players[math.random(1,#players)]
	
	removeItem()
	
	
end

This script works perfectly, but when I defined everything as a local variable it didn't work, and I was getting errors everywhere. Why does this work now?

1 comment

1 answer

✓ Accepted answer

A local variable is local to it's block of code. You can not access a local variable outside it's block of code. For example:

This would not work because it is outside a block of code


if true then

	local a = 5

end

print(a)

This output would be "nil" because it is outside the block of code. If you take the "local" away it will print "5" because it can access that.

If you're not sure what a block of code is then this is it.

The image you are looking for is the image with the blue, red, and green. That will display what the "Block of Code" is if you are not sure.

https://www.robloxdev.com/articles/Variables

2 comments

0

This helps me a ton! Explains why a lot of my scripts don't function like I expect them to!

0

Using local variables both protects your code from accidentally editing values elsewhere and makes it faster since it only needs to look in the current local stack.

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