I’ve been looking at some Lua source code, and I often see things like this at the beginning of the file:
local setmetatable, getmetatable, etc.. = setmetatable, getmetatable, etc..
Do they only make the functions local to let Lua access them faster when often used?
Local data are on the stack, and therefore they do access them faster. However, I seriously doubt that the function call time to
setmetatableis actually a significant issue for some program.Here are the possible explanations for this:
Prevention from polluting the global environment. Modern Lua convention for modules is to not have them register themselves directly into the global table. They should build a local table of functions and return them. Thus, the only way to access them is with a local variable. This forces a number of things:
One module cannot accidentally overwrite another module’s functions.
If a module does accidentally do this, the original functions in the table returned by the module will still be accessible. Only by using
local modname = require "modname"will you be guaranteed to get exactly and only what that module exposed.Modules that include other modules can’t interfere with one another. The table you get back from
requireis always what the module stores.A premature optimization by someone who read “
localvariables are accessed faster” and then decided to make everythinglocal.In general, this is good practice. Well, unless it’s because of #2.