I believe local variables are always better than globals, but you are right that this restraint on a function’s location is oftentimes terrible for code organization.
Say you have 4 functions, each implemented in the last:
function findInTable() ...
function indexTable() ...
function validateIndex() ...
function decodeIndex() ...
It’s more of a pain to scroll down to find the main functions at the bottom than it is to simply glance at them right at the top. i.e, you find the findInTable
function at the bottom, but a new reader (like future you from 2 years in the future) would be confused as to why s/he is finding all these technical functions like decodeIndex
surfacing up top. Unless, you still have a trained instinct to scroll straight down to the bottom, unlike me.
The usual answer in Lua is “tough,” but you can use tables to stay local while receiving the benefits of globals at the same time:
local TableLib = {}
function TableLib.Find() ...
function TableLib._index() ...
function TableLib._validateIndex() ...
function TableLib._decodeIndex() ...
Accessing these functions are probably just as fast as accessing a global, if not slower, but I don’t really know.
Also, having to keep reading down to find the main functions and know what they do is time-consuming and uses up the mental power you need to move on to the next feature or fix the next bug. It is much more professional (in my opinion) to be able to assume what your code does and trust that it works through clear and concise function/parameter names and without having to understand lower-level implementations. If you need more information, you keep reading down, and if you only need a gist, it’s right there.