• Announcement: Lua.org now officially recommends this forum as a meeting place for the Lua community

How do I remove an entry from a table by its index? (1 Viewer)

TheAlmightyGuru

Newcomer
Joined
Aug 18, 2021
Messages
2
Reaction score
0
I've read that the correct way to remove an entry from a table is to simply set it to nil. However, when I try to do this, I inadvertently remove all subsequent entries as well. Here is my sample code:

Code:
arr = {'a', 'b', 'c', 'd'}

for index, row in ipairs(arr) do
    print(index, row)
end

arr[2] = nil  -- Remove the second entry.

print("remaining:")
for index, row in ipairs(arr) do
    print(index, row)
end

I would expect the remaining output to look like this:
1 a
3 c
4 d

But, it only prints the first record:
1 a

Does anyone know what I'm doing wrong?
 

stetre

Member
Rank: I
Joined
Jan 8, 2020
Messages
89
Reaction score
49
Location
Italy
Website
github.com
Your subsequent entries are still there. However, by removing the entry you insert a hole in the table, so it is no more a sequence and ipairs( ) won't work any more. You have to iterate with pairs( ) instead. See the linked manual entries for more details.
 

TheAlmightyGuru

Newcomer
Joined
Aug 18, 2021
Messages
2
Reaction score
0
Thank you stetre!

Your response helped me find another way of removing a table entry. Using the following code:
Code:
table.remove(arr, 2)
allows me to remove the entry and also keeps the ipairs loop working.
 

stetre

Member
Rank: I
Joined
Jan 8, 2020
Messages
89
Reaction score
49
Location
Italy
Website
github.com
Yes, that's also an option. Keep in mind, however, that table.remove changes the keys (the indices) of all the entries that come after the entry you remove.
 
Top