posfan12
posfan12

Reputation: 2651

Lua 4 outermost variable scope

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

Upvotes: 1

Views: 108

Answers (1)

Vinni Marcon
Vinni Marcon

Reputation: 616

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!

Upvotes: 1

Related Questions