1

Should I explicitly declare a variable in the outermost scope of a Lua 4 script a local variable versus a global variable? Should I avoid one or the other? Thanks.

For instance:

local foo = 5

versus

faa = 8

1 Answer 1

1

I believe you already know that local variables are variables where they exist only within a certain scope, while normal variables are global and are included within the _G table. However, according to Lua's Performance Guide, it also helps to make your code faster:

Lua precompiler is able to store all local variables in registers. The result is that access to local variables is very fast in Lua. For instance, if a and b are local variables, a Lua statement like a = a + b generates one single instruction.

So, it is easy to justify one of the most important rules to improve the performance of Lua programs: use locals!

Sign up to request clarification or add additional context in comments.

2 Comments

Is this true for all scopes including the outermost one?
@posfan12 in the case of outermost scope, the main focus of using local is to improve the performance of the script, but in the case of internal scopes it has the functionality to exist only inside the scope

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.