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

What exactly does "local" mean if you're using it in the first scope?

Asked by
funyun 958 Moderation Voter
9 years ago

I know that when you're in a function or a loop or a conditional, you have to use locals. What I don't understand is when people do something like

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local camera = workspace.CurrentCamera
repeat wait() until player.Character
local char = player.Character

What does "local" mean there? There's no functions, no loops, no conditionals, you're just setting those variables in the beginning of your script.

0
Right there it does nothing. If you used those variables in the script to do something, it's pretty much a way of cutting down long pieces of code into small pieces. It makes the script shorter when using those variables longer and you only have to type the long version once. SchonATL 15 — 9y
0
Local extends it to one function or the contained function, usually. Without local, it is global to the whole script. unmiss 337 — 9y

2 answers

Log in to vote
4
Answered by
Unclear 1776 Moderation Voter
9 years ago

Generic information about local variables.

Using local on the highest scope enables all scopes beneath it access to the localized variable.

Local variables can be accessed faster than regular variables as well. This is a micro optimization that happens because accessing variables from the virtual machine is faster than accessing variables from the global table. In high-speed environments, this can prove to be a crucial optimization, but for your sake you probably don't need it.

Do note that local variables in the highest scope still follow scope rules for local variables. You must declare the local variable before accessing it, hence...

print(a) --> nil
local a = "success"

... is not valid code.

Otherwise, it's just a stylistic preference.

Do note that there is a 200 local variable limit per scope level.

Ad
Log in to vote
3
Answered by
dyler3 1510 Moderation Voter
9 years ago

Using Local in the first scope means that it can be accessed from any scope within it. So let's say you have a script like this:

local Var="Local Variable Test"

function PrintDatThang()
    print(Var) --This'll print because it's within a descendant scope from the defined variables scope.
end

if game.Workspace.Part then
    PrintDatThang()
else
    print("I don't wanna print: "..Var)
end

So, as you can see, having it in the first scope like this, basically just allows it to be accessed anywhere within the script.


Some more information about Scoping and Local Variables


Anyways, if you have any further problems or questions, please leave a comment below. Hope I helped :P

Answer this question