2

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 ?

jlaurens
  • 529
  • 5
  • 10

2 Answers2

4

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

Piglet
  • 27,501
  • 3
  • 20
  • 43
  • 2
    Here's another resource: [Lua Performance Tips](https://www.lua.org/gems/sample.pdf). It specifically mentions this pattern on page 17, but it talks specifically about functions being called in a loop, not just any function used in the code. – DarkWiiPlayer Jan 08 '21 at 13:18
1

It increase a little bit performance in some workload

reason why: Why are localized functions faster in Lua?

Blanket Fox
  • 377
  • 4
  • 15