Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

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

Asked by 6 years ago

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 answer

Log in to vote
1
Answered by 6 years ago

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

0
This helps me a ton! Explains why a lot of my scripts don't function like I expect them to! MezornoIV 25 — 6y
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. gullet 471 — 6y
Ad

Answer this question