Delete a table element

Verified
Added by iNTERFACEWARE

Use table.remove() to delete an element from a table

Source Code
   -- remove the last element in the table = default
   t = {[1]='one',[2]='two',[3]='three'}
   table.remove(t)
   trace(t[3]) --> nil
   trace(t)    --> {[1]='one',[2]='two'}
   
   -- remove the second element
   t = {[1]='one',[2]='I am an impostor',[3]='two'}
   table.remove(t,2)
   trace(t[2]) --> "two"   
   trace(t)    --> {[1]='one',[2]='two'}
   
   -- alternatively you can remove an element by setting it to nil

   -- remove the last element by setting it to nil
   t = {[1]='one',[2]='two',[3]='three'}
   t[3] = nil
   trace(t)
   
   -- remove the second element by setting it to nil
   t = {[1]='one',[2]='I am an impostor',[3]='two'}
   t[2] = nil
   trace(t)
   
   -- sparse tables/arrays may not behave as expected
   
   -- only one element [3] is empty 
   -- then [4] is decremented to [3]
   t = {[1]='one',[2]='two',[4]='three'}
   table.remove(t,2)
   trace(t[2]) --> nil
   trace(t)    --> {[1]='one',[3]='three'}
   
   -- two empty elements [3] & [4]
   -- then [5] is not decremented to [4]
   t = {[1]='one',[2]='two',[5]='three'}
   table.remove(t,2)
   trace(t[2]) --> nil
   trace(t[3]) --> nil
   trace(t[4]) --> nil
   trace(t)    --> {[1]='one',[5]='three'}
Description
Use table.remove() to delete an element from a table
Usage Details

Use table.remove() to delete an element from a table. If an index is not supplied then the last element is removed by default. Any following elements are shifted down to close the space (under some circumstances see the code sample).

How to use the snippet:

  • Paste the code into your script

Note: You may also want to look at the node.remove() function to delete elements from node trees.