On the subject to declaring variables to their most confining scope next should be noted:
Lua Code:
local a
for i=1, 5 do
a = i
end
Code:
-- Compiles into
main <test.lua:0,0> (7 instructions, 28 bytes at 0x80049128)
0+ params, 5 slots, 0 upvalues, 5 locals, 2 constants, 0 functions
1 [3] LOADK 1 -1 ; 1
2 [3] LOADK 2 -2 ; 5
3 [3] LOADK 3 -1 ; 1
4 [3] FORPREP 1 1 ; to 6
5 [4] MOVE 0 4
6 [3] FORLOOP 1 -2 ; to 5
7 [5] RETURN 0 1
]]
Lua Code:
for i=1, 5 do
local a
a = i
end
Code:
-- Compiles into
main <test.lua:0,0> (8 instructions, 32 bytes at 0x80049128)
0+ params, 5 slots, 0 upvalues, 5 locals, 2 constants, 0 functions
1 [2] LOADK 0 -1 ; 1
2 [2] LOADK 1 -2 ; 5
3 [2] LOADK 2 -1 ; 1
4 [2] FORPREP 0 2 ; to 7
5 [3] LOADNIL 4 4
6 [4] MOVE 4 3
7 [2] FORLOOP 0 -3 ; to 5
8 [5] RETURN 0 1
]]
and
Lua Code:
for i=1, 5 do
local a = i
end
Code:
-- Compiles into
main <test.lua:0,0> (7 instructions, 28 bytes at 0x80049128)
0+ params, 5 slots, 0 upvalues, 5 locals, 2 constants, 0 functions
1 [2] LOADK 0 -1 ; 1
2 [2] LOADK 1 -2 ; 5
3 [2] LOADK 2 -1 ; 1
4 [2] FORPREP 0 1 ; to 6
5 [3] MOVE 4 3
6 [2] FORLOOP 0 -2 ; to 5
7 [4] RETURN 0 1
As you can guess, the second is a bit slower, but it should also be noted that the gain from this is only going to be noticable for large amount of variable declarations.
While doing a large amount of variable declarations, next should also be noted (I'll leave the compiled versions out since I don't want to pollute the thread):
Lua Code:
function UnitAura(unitId, index)
end
local startTime, endTime
startTime = os.clock()
for j = 1, 1000000 do
local name, rank, icon, count, dispelType, duration, expires, caster, isStealable, shouldConsolidate, spellID, canApplyAura, isBossDebuff, value1, value2, value3
for i = 1, 40 do
name, rank, icon, count, dispelType, duration, expires, caster, isStealable, shouldConsolidate, spellID, canApplyAura, isBossDebuff, value1, value2, value3 = UnitAura("player", i)
end
end
endTime = os.clock()
print(endTime-startTime)
startTime = os.clock()
for j = 1, 1000000 do
for i = 1, 40 do
local name, rank, icon, count, dispelType, duration, expires, caster, isStealable, shouldConsolidate, spellID, canApplyAura, isBossDebuff, value1, value2, value3 = UnitAura("player", i)
end
end
endTime = os.clock()
print(endTime-startTime)
startTime = os.clock()
for j = 1, 1000000 do
for i = 1, 40 do
local name, rank, icon, count, dispelType, duration, expires, caster, isStealable, shouldConsolidate, spellID, canApplyAura, isBossDebuff, value1, value2, value3
name, rank, icon, count, dispelType, duration, expires, caster, isStealable, shouldConsolidate, spellID, canApplyAura, isBossDebuff, value1, value2, value3 = UnitAura("player", i)
end
end
endTime = os.clock()
print(endTime-startTime)
--- Results
$ lua test.lua
5.859
2.562
6.375
If you really want to optimize your addon, you need to look at compiled code and understand how function calls/lua stack works.