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

Which is the best way to make a declaration of LocalPlayer in a LocalScript?

Asked by 8 years ago

Should I do

plr = game.Players.LocalPlayer

or

local plr = game.Players.LocalPlayer

is there any difference and does it affect anything?

1 answer

Log in to vote
0
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
8 years ago

Putting local in front of a variable declaration makes it confined to that specific scope. This means that it will only work inside the function, if statement, loop, etc. that it was defined it. If a local variable is defined at the top of the script it will work throughout the entire script.

A global variable -- one that doesn't have local in front of it -- will work throughout the entire script no matter where it's defined.

Unless you're not able to, you should always make your variables local when inside a function, loop, etc.

function func()
    local var = "hello world"
end

It's more efficient this way, because the computer doesn't need to keep track of the variable var outside of the function.


But what about at the top of a script?

var = "hi"
-- or --
local var = "hi"

Both of these variables can be used throughout the entire script, because even the local variable is in the global scope -- it's not confined in a function or loop.

I would encourage, however, to still use a local variable. Some argue that it's still slightly faster, but it's also more readable. When you see the bright blue local keyword, you immediately know that a new variable is being defined. It helps organize your code.

It's also just a good idea to get into the habit of putting local in front of your variables to increase efficiency in other situations. If you make a mistake and have to use a global, it's easy enough to fix.

0
Thank you so much :) I really appreciate it :) God loves you so much :) You are His son and He loves you so much shasta342 37 — 8y
0
Thanks :D Perci1 4988 — 8y
Ad

Answer this question