Brett Comardelle
Brett Comardelle

Reputation: 322

How to remove a table from a table using it's index

I am currently using/learning Corona SDK and I am trying to make a card game. A player has a set of unique cards that are drawn from their hand. These cards drawn should be removed from the deck. I am using a table of tables for this. I am having trouble removing the drawn cards. I am trying the below:

local tbl = cardTable[math.random(#cardTable)]  --tbl = random card drawn
table.insert(handTable, tbl)  --insert the table into a hand table
local indx = table.indexOf(cardTable, tbl) --get the index of the removed
table.remove(cardTable,indx) --remove that index

The cardTable is similar to the below:

cardTable = { {a,b,c}, {d,e,f}, {g,h,i}, ...}

This is inside a for loop iterating 5 times for a hand of 5 cards.

Edit

I realized that I made a mistake while inserting the cards into the cardTable. I inserted multiple copies of each card making it seem that it wasn't being removed. I should have checked this originally.

Upvotes: 2

Views: 90

Answers (2)

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22421

You code looks good, so I assume it is some typo or set up error. However you're doing too much unnecessary work. You don't really need to find index - you've just generated/obtained it from user yourself. Why go looking for something you already know? You also don't need to separately retrieve value because table.remove returns value it removed. Just remove from cardTable and insert what you removed to handTable right away.

local indx = math.random(#cardTable) -- obtain draw and remove index in any way
table.insert(handTable, table.remove(cardTable, indx))

Upvotes: 1

Amir
Amir

Reputation: 1683

I tried this and I dont have any problem even though it is similar to yours:

local t = { {"a","b","c"}, {d,e,f}, {g,h,i}}

local tbl = t[math.random(#t)]  --tbl = random card drawn
print(tbl)
local indx = table.indexOf(t, tbl) --get the index of the removed
print(indx)
table.remove(t,indx) --remove that index
print(t[indx])

Upvotes: 0

Related Questions