--Lua Optimisations

--SECTION 1:

--Create Tables with predefined sizes to avoid table hashing;

local t = { true , true , true }

t [ 1 ] = 1

t [ 2 ] = 2

t [ 3 ] = 3

--SECTION 2:

--Erasing all elements from a table using a while loop (not great for large tables)

while true do

local k = next ( t )

if not k then

break

end

t [ k ] = nil

end

--SECTION 3:

--When creating arrays consider the following;

polyline = {

x = { 10.3 , 10.3 , 15.0 , ... } ,

y = { 98.5 , 18.3 , 98.5 , ... }

} --(tables used: 3)

--OPPOSED TO

polyline = {

{ 10.3 , 98.5 } ,

{ 10.3 , 18.3 } ,

{ 15.0 , 98.5 } ,

...

} --(tables used: 1 + n)

--SECTION 4:

--Put constant tables/functions outside loops;

--Figure 1: placing a constant table outside the loop

local t = { 1 , 2 , 3 , "hi" } -- create ’t’ once

function foo ( ... )

for i = 1 , n do

local v = t [ 1 ] + 1

end

end

--OPPOSED TO

function foo ( ... )

for i = 1 , n do

local t = { 1 , 2 , 3 , "hi" } --unnecessary redeclare

local v = t [ 1 ] + 1

end

end

--Figure 2: placing a function outside the loop

function foo ( limit , delta )

--create the function once before the loop

local function aux ( num )

num = tonumber ( num )

if num >= limit then return

tostring ( num + delta )

end

end

for line in io.lines ( ) do

line = string.gsub ( line , "%d+" , aux ) --use function

io.write ( line , "

" )

end

end

--OPPOSED TO

function foo ( limit , delta )

for line in io.lines ( ) do

line = string.gsub ( line , "%d+" , function ( num )

num = tonumber ( num )

if num >= limit then return

tostring ( num + delta )

end

--else return nothing, keeping the original number

end ) --continues to create the same function for every line

io.write ( line , "

" )

end

end

--SECTION 5:

--Change a local table if constantly making new tables in a loop where the number of properties doesn't change;

local t = { }

local aux = { year = nil , month = 6 , day = 14 }

for i = 1970 , 2000 do

aux . year = i

t [ i ] = os.time ( aux )

end

--OPPOSED TO

local t = { }

for i = 1970 , 2000 do

t [ i ] = os.time ( { year = i , month = 6 , day = 14 } )

end

--SECTION 6:

--Memorising; consider creating a function that returns a value after it has been calculated ie;

function memoize ( f )

local mem = { } -- memoizing table

setmetatable ( mem , { __mode = "kv" } ) -- make it weak

return function ( x ) -- new version of ’f’, with memoizing

local r = mem [ x ]

if r == nil then -- no previous result?

r = f ( x ) -- calls original function

mem [ x ] = r -- store result for reuse

end

return r

end