Local variables in a global scope

When looking through people’s code, I often notice that they set everything as a local variable, even when the variable isn’t placed inside a function. I’ve always been a bit annoyed by this and found it to be unnecessary, but is there any real reason why this practice is so common?

Example of what I’m talking about:

local var1 = 1
local var2 = 2
function()
    ...
end
2 Likes

Mostly because this is how vanilla Lua works, you usually end up having to do this there. However, it’s the standard to define everything as local unless it’s absolutely necessary to use globals.

On a smaller note, local read/write tends to be a lot faster than for globals.

And on a technical note, the Lua “global scope” is actually just a hidden function.

7 Likes

Your variables in the top-level scope would still work without the local keyword. That’s all I know.

Global tables and returning a table while using include/require exists for a reason and globals are MUCH faster than readwrite.

I will never use global variables in my code, period. Everything that requires definition will be a local variable. I treat my code as if it’s always in a function or scope of some sort (it is) and my conventions call for using local before a variable. Not doing so just looks gross and there’s supposedly bad technical implications about globals.

If they aren’t Lua or Roblox built-in globals, I find that globals have no use in Roblox programming. It annoys me when I see a global variable, so for me I see this thread out backwards.

2 Likes

I’m not sure how your first point about global tables and returning a table while using require pertains to his argument.

As for your second point, @Autterfly is correct in that local access is much faster than global access. I encourage you to read the following sources:

Especially the “basic facts” in this pdf, which is written by the creator of Lua:

2 Likes

To highlight what @Darkenus shared from that PDF:

CPU register is always going to be much faster to access. If you think about it at the hardware level, it’s much easier/faster for the CPU to access it’s own registry than for it to call out to RAM to access other items in memory (such as global variables in Lua).

On another note, the term local in Lua is odd for initializing variables. My guess is that it was chosen due to the lexical scope nature of Lua. In other words, “this variable is local to the given scope.” Thus, if a local variable is registered top-level, it’s “local” to the whole program.

10 Likes