You shouldn't be worrying about memory issues here. Lua is optimized enough to handle hundreds of tables without any lag issues.
Anyway, the problem is that it's not table.remove that is bugging but rather your code and the way your object IDs work. You are using those IDs to index your instance table, but whenever you remove an item from the table all the items above the table go down, thus you can no longer trust the ID. Here, I'll visualize what I mean:
--# Before table.remove:
t = {
[1] = { id = 1 };
[2] = { id = 2 };
[3] = { id = 3 };
[4] = { id = 4 };
[5] = { id = 5 };
}
table.remove( t, 3 )
--# After table.remove:
t = {
[1] = { id = 1 };
[2] = { id = 2 };
[3] = { id = 4 };
[4] = { id = 5 };
}
You see what happens here? All the other items move - change their index inside the table, but IDs don't change. There's even more problems with this:
# continuing the above example
c = table.getn( t ) --> 4
n = c + 1 --> 5
t[n] = { id = n }
# table after inserting a new item:
t = {
[1] = { id = 1 };
[2] = { id = 2 };
[3] = { id = 4 };
[4] = { id = 5 };
[5] = { id = 5 };
}
# Now you have two items with the same ID
What you should be doing is making the ID something more unique, maybe a string like "Player" or "Enemy". That way you will get more precise control over what item you want to alter. And unless you're going to be having millions of tables, don't worry about performance issues.
You can use the length operator (#) instead of table.getn:
local t = { 1, 2, 3 }
print( #t ) --> 3
For default values, you can have them like this:
local function add ( a, b )
a = a or 2
b = b or 1
return a + b
end
print( add( 2 ) ) --> 3
print( add( nil, 5 ) ) --> 7
Also, 'repeat' is very similar to 'while' except that it first runs the body and only then checks the condition. It's very helpful when you need to get a certain event to fire:
print( "Press [Enter] to continue..." )
repeat
local event, key = os.pullEvent( "key" )
until key == keys.enter or key == keys.numPadEnter
print( "You pressed [Enter] key!" )
The for loop in here:
function instanceDestroy(t)
if(t.inst==true) then
local temp_id=t.id
objs.insts[temp_id]=nil
for k in pairs(t) do <-- right here
t[k] = nil
end
end
end
Shouldn't be needed. Lua handles with tables that are not referenced anywhere by itself, no need to do it yourself.