Search code examples
lualocal

Why `local print = print` in Lua?


While learning from third party's Lua code, I found at the top of the main script file

local insert = table.insert
local match = string.match
local gsub = string.gsub

I understand these chunks as shortcut definitions, but I also found

local assert = assert
local ipairs = ipairs
local print = print

What is the purpose of these last instructions ?


Solution

  • Accessing locals is faster. So in some cases it might make sense to make frequently used things local to save a few percent of processing time. But in most cases there you can save yourself the trouble. Especially if a global isn't used thousands of times.

    Give this a read:

    Why are local variables accessed faster than global variables in lua?

    http://lua-users.org/wiki/OptimisingUsingLocalVariables