Just a quick update on this....
Over the last few years, I've put together a list of some more Lua tricks that I've come across:
Using Memory Efficiently
1. Eliminate memory leaks — Global variables are never considered garbage so you need to set them to "nil" when they are no longer required.
2. Avoid loading resource files until they're actually needed.
Lua Optimizations
Localize, Localize
Avoiding Global variables and functions isn't always possible. Access to local variables and functions is faster, especially in time-critical routines.
This also applies to core Lua libraries. In time-critical routines, you should always localize library functions:
local sin = math.sin --local reference to 'math.sin'
local function foo(x)
for i = 1,100 do
x = x + sin(i)
end
return x
end
Finally, Functions should also be localized whenever possible (just remember to create them in the correct order):
--NON-LOCAL
function func1()
func2( "myValue" )
end
function func2( y )
print( y )
end
func1()
--LOCAL
local function func2( y ) --'func2' properly scoped above 'func1'
print( y )
end
local function func1()
func2( "myValue" )
end
func1()
Avoid "table.insert()"
table.insert() is quite slow and should be avoided. Below are a few alternatives:
--LOOP INDEX
local a = {}
for i = 1,100 do
a[i] = i
end
--TABLE SIZE
local a = {}
for i = 1,100 do
a[#a+1] = i
end
--COUNTER
local a = {}
local index = 1
for i = 1,100 do
a[index] = i
index = index+1
end
Avoid "unpack()"
unpack() is also slow, so use a Loop instead:
local a = { 100, 200, 300, 400 }
for i = 1,100 do
print( a[1],a[2],a[3],a[4] )
end
Avoid "ipairs()"
ipairs() has quite a high overhead, so should never really be used. A simple loop usually works just as well, with less overhead:
local t1 = {}
local t2 = {}
local t3 = {}
local t4 = {}
local a = { t1, t2, t3, t4 }
for i = 1,#a do
print( a[i] )
end
Math Performance
Multiplication is faster than division, so you should multiply by a decimal instead of dividing.
Multiplication is also faster than exponentiation:
Some of these tricks could be useful in time-critical sections of your code.
HTH
Shando