Local variable and a normal variable

So I`ve been learning on scripting for 1 month and I still confuse with this thing.

local Variable = game.workspace.part
-- vs
Variable = game.workspace.part

When should i use (local) variable) and a normal variable?

1 Like

“local Variable” is used to define an variable and “variable = value” is used to change the variable’s value

You should never use global variables. Always use local variables.


Basically the difference is in the speed of getting the variable, so if its local the u are getting the variable from your computers memory and thats fast, if u make it on server (without local) then u must get it from the server all the time and thats slower and not efficient

That’s not always the case, how OP described his inquiry, he was comparing local and global variables, not reassigning variables.

If it is local then that variable can be accessed by everything after it in the same scope. If it is global it can be accessed everywhere, no matter the location or scope, although global variables can be useful, you shouldn’t use them because putting a local variable at the start of the script already makes it “global”.

The DevHub says following:

Please use the search feature before posting, I answered the same question a few days ago which you can view here. To answer your question local variables are more efficient than global variables.

1 Like

That’s not at all what it is. That would cause so many problems. Both variables are stored in memory inside of the C-side of Lua, but local variables are faster to access due to the nature of Lua. It’s negligible unless you’re using them all in a huge loop with no yields.
Local variables behave the same way regular variables do in other languages, as in they won’t leak out of the scope. Regular variables in Lua behave the same as global or shared or constant or forward-declared variables in other languages (Depending on the language the terminology or types of variables could be different)
You should always be using local variables because it is a better practice, however, in standard Lua there is a limit of 200 local variables per scope. You couldn’t conceivably hit that limit, but it is there. I don’t know if that was changed in Roblox.

1 Like