PICO-8 Wiki
Advertisement
del( table, value )
Deletes the first occurrence of a value from a sequence in a table.
table
The table.

value
The value to match and remove.

The del() function searches a sequence in a table for an element that equals the given value then removes it. All subsequent values in the sequence shift down by one slot to keep the sequence contiguous.

Specifically, del() starts with the element at index 1, then increments the index while comparing elements to the given value. When it finds the first element that is equal to the value, it reassigns the indexes of the subsequent values until it reaches an unassigned index (nil).

The del() function returns the object being removed. This can be ignored, tested it to see if the removal was successful, or used as needed.

Examples[]

Deleting elements using literal values:

t = {1, 3, 5, 3, 7, 5}
del(t, 3)  -- t = {1, 5, 3, 7, 5}
del(t, 7)  -- t = {1, 5, 3, 5}
del(t, 5)  -- t = {1, 3, 5}

del(t, 9)  -- not found, no changes to t

Deleting elements using their own value:

evens = {1, 2, 3, 4, 5, 6}
del(evens, evens[1])  -- evens = {2, 3, 4, 5, 6}
del(evens, evens[2])  -- evens = {2, 4, 5, 6}
del(evens, evens[3])  -- evens = {2, 4, 6}

In Lua, tables are compared by reference (memory location), not by contents. To delete a sub-table from a table, the right reference must be supplied:

-- create a table in 'f' so we can refer to it more than once
f = {"foo"}
 
-- create a table of tables
t = {}
add(t, {"bar"})
add(t, {"foo"}) -- this 1st "foo" table only *looks* like the one we created
add(t, {"baz"})
add(t, f)       -- this 2nd "foo" table *is* the one we created
add(t, {"bat"})

-- print the table
for v in all(t) do print(v[1]) end  -- bar foo baz foo bat

-- this fails to delete anything because the search parameter 
-- only *looks* like the two "foo" tables in 't'
del(t, {"foo"})
for v in all(t) do print(v[1]) end  -- bar foo baz foo bat

-- this deletes the 2nd "foo" table because the search parameter 'f'
-- *is* the 2nd "foo" table
del(t, f)
for v in all(t) do print(v[1]) end  -- bar foo baz bat

-- this deletes the 1st "foo" table by using its reference,
-- taken directly from the parent table
del(t, t[2])
for v in all(t) do print(v[1]) end  -- bar baz bat

See also[]

Advertisement