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

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

Should I do

plr = game.Players.LocalPlayer

or

local plr = game.Players.LocalPlayer

is there any difference and does it affect anything?

1 answer

✓ Accepted answer

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.

2 comments

0

Thank you so much :) I really appreciate it :) God loves you so much :) You are His son and He loves you so much

0

Thanks :D

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