[POST CLOSED] Figured the issue

[ Post Closed Due To Inconvenience]

Its best practice to make all variables by defualt local.

It is indeed good practice to localize all variables.
https://devforum.roblox.com/t/localizing-variables-but-not-functions/369038/2

1 Like

All variables should be local as having them global only makes sense when using getfenv and setfenv. But even then, the _G table is a cleaner solution if you just want to have them accessible outside their script.

Globals are slower in vanilla Lua (don’t know if the optimizations are active yet in Luau) as they are stored in the current environment’s global table. Each time you assign or index the variable, you have to write or read from the table, which isn’t very fast.

My friend korbykobs, he thinks there is no difference between local and global variables. Is there acctually much of a difference between them, and can It affect that much?

pls put back the issues etc. so other devs can learn from this

There is no point, there was nothing to learn from. It was simply just a raycasting issue in our game. Just to classify, this was not because of local variables.

I’m going to explain it based on vanilla Lua 5.1 as Roblox’s implementation (Luau) isn’t open sourced and has a completely different compiler which gets updated on a monthly basis.

Global variables are the easiest to explain. Every function in Lua (including the script itself) has an environment. To put it simply, it is a table that contains all of your global variables. This creates 2 issues. Firstly, the values are stored as env.varname = value and it is widely known that hash tables aren’t very fast to read or write to. Secondly, since Lua assumes that globals can be accessed from anywhere, no optimizations are performed to ensure that the value is always present.

Local variables are stored in a stack (very fast) and are dynamically allocated. For example, if a variable is no longer required, another value can be stored in its register.

Adding local to the start of your variable declaration represents nothing in terms of work time, makes it clear where variables are declared and can result a massively faster code.