lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 22/06/2022 10:21, Egor Skriptunoff wrote:
A question about Lua coding style. Is it a good or bad idea to
distinguish global from local variables by its uppercase / lowercase
initial letter? Var=0 -- global var=0 -- local or upvalue
https://stackoverflow.com/questions/72710110/uppercase-or-lowercase-for-global-variables


I think it's more of a personal style, IMO.

I don't follow that because it reminds me too much of Java classes.
So I usually reserve Camel-case identifiers for variables which should represent either "classes" or, sometimes, functions (following another Java convention).

For globals I prefer an explicit suffix or prefix (G_name or name_G).

I'm not too consistent, though, since I use them very sparingly. In small scripts it's not too important to differentiate them: usually I give them fairly long names like e.g. "collected_files_list" and so they are quite distinguishable.

For long programs, I avoid them like the plague, except in some Lua files written in some Lua-based DSL that I devised, where they are essential.

Anyway my muscle memory is trained to prepend "local" to any new identifier I define, and I find I almost never need global variables at all in my code (except for the DSL case above, which is a coding pattern I use frequently).

When different parts of my Lua code need access to some shared data structure, I almost never use globals. Instead I pass a reference to some context object that holds all the info that needs to be shared.

YMMV

Cheers!

-- Lorenzo