Dr.Tyler O. wrote:
I'm aware of table.remove() but I have to remove a specific object that depends on the order in which the player touches the coins.
There’s at least one way to accomplish this. The idea is to manage references to tables instead of indices. Indices change every time you modify the entries in a table; references stay the same if you re-order the entries (i.e.,
pointers). If you have a table where you store all your references, you can use a field on each table reference to remove it when you no longer need it. You’ll need some functions and tables to keep track of your data management, though. Here are some tips:
You need to use a function to create a table of references (the "master table") and store every new entry:
Code: Select all
function createEntry(masterTable)
local i = #masterTable + 1
print("initial entry ID: "..i)
masterTable[i] = {} -- you will store the object here
i = masterTable[i]
print("ID is now a 'pointer' ")
return i -- the reference of the entry
end
Note that the function returns the reference of the entry. You need to use this value in whatever data structure (or function) you use to update (or draw) your object. You can also include a table field to use as remove flag.
Code: Select all
function drawTableEntry(tableReference, removeFlag, img) --tableReference is returned by createEntry
tableReference.removeFlag = removeFlag
tableReference.img = img
end
To remove the entry, loop through the references table (using a
reverse loop) and look for the remove flag. Be sure to call this function only when needed, for instance, only when the object's state changes.
Code: Select all
function removeEntry(masterTable)
for i = #masteTable, 1, -1 do
if (masteTable[i].removeFlag) then
table.remove(q, i)
print("item removed from list, index was: "..i)
end
end
end