Is there any value in creating local copies of common Lua functions like print()
, pairs()
or ipairs()
?
Example:
local _print = print
local _pairs = pairs
local _ipairs = ipairs
for i, v in _ipairs(someTable) do
_print(v)
end
I've seen some Lua written using this and am wondering if there are any benefits (performance or otherwise) to doing this?
Lua - Variables. A variable is nothing but a name given to a storage area that our programs can manipulate. It can hold different types of values including functions and tables. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore.
The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While creating a Lua function, you give a definition of what the function has to do.
A method definition in Lua programming language consists of a method header and a method body. Here are all the parts of a method − Optional Function Scope − You can use keyword local to limit the scope of the function or ignore the scope section, which will make it a global function.
Have you studied general tips for keeping Lua performance high? i.e. know table creation and rather reuse a table than create a new one, use of 'local print=print' and such to avoid global accesses.
The main motivation is probably performance because access to global variables requires a hash table lookup while access to local variables does not. However, you should measure the difference in your program. Don't overdo it.
Note that you don't need to use different names: you can write local print=print
etc so that the rest of your program does not really need to know whether these variables are local or global.
Finally, there is a semantic difference when you save the value of a global variable into a local one: you are doing early binding; if your program calls an outside module that uses the same function, it will use the current value, not the frozen one you have. In other words, later redefinitions of say print
do not affect you.
For a longer discussion of performance, read Chapter 2 of Lua Programmming Gems.
Another motivation for defining local copies of common functions is to redefine them and still retain the original functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With