Coming from C I’m still not comfortable with how Corona/lua deals with tables, but I’ve settled with this method for removing elements with index i from table elementArray:
elementArray[i]:removeSelf() elementArray[i] = nil table.remove(elementArray, i)
This standard method has until now worked reasonably well (I don’t know how to hunt for memory leaks etc in Corona yet), but now I’m a bit confused.
Please consider the following code:
gridElemArr = {} -- Create new image local gridElemIdx = #gridElemArr+1 gridElemArr[gridElemIdx] = display.newImage("02\_64x64.png") gridElemArr[gridElemIdx].x = 100 gridElemArr[gridElemIdx].y = 100 gridElemIdx = #gridElemArr+1 gridElemArr[gridElemIdx] = display.newImage("02\_64x64.png") gridElemArr[gridElemIdx].x = 200 gridElemArr[gridElemIdx].y = 100 gridElemIdx = #gridElemArr+1 gridElemArr[gridElemIdx] = display.newImage("02\_64x64.png") gridElemArr[gridElemIdx].x = 300 gridElemArr[gridElemIdx].y = 100 -- Remove grid element with index 2 gridElemArr[2]:removeSelf() print("Num elems A: " .. #gridElemArr) gridElemArr[2] = nil print("Num elems B: " .. #gridElemArr) table.remove(gridElemArr, 2)
What this code snippet is supposed to do is to create 3 elements (with index 1, 2 & 3) and then remove the one with index 2.
But what happens is that two elements are removed from the table and it seems to happen at the line:
gridElemArr[2] = nil
The output of the code above is:
Num elems A: 3
Num elems B: 1
So with my “standard” way of removing table elements, obviously breaks down in this case. But what am I doing wrong?