Add: Difference between revisions

From Pico-8 Wiki
Jump to navigation Jump to search
imported>Felice Enellen
(mention how to combine this with deli() to emulate a stack)
imported>Felice Enellen
(mention stacks, add another example)
Line 2: Line 2:
|name=add
|name=add
|shortdesc=Adds a element to the end of a sequence in a table.
|shortdesc=Adds a element to the end of a sequence in a table.
|tbl||The table.
|table||The table.
|v||The value to add.
|value||The value to add.
|i|optional|The index for the value to be inserted.
|index|optional|The index for the value to be inserted.
}}
}}
The <code>add()</code> function appends an element to the end of a sequence in a table.
The <code>add()</code> function adds an element to a sequence in a table.


This always adds the new element immediately after the current final index. It does ''not'' check for available gaps between the start and the end.
If an <var>index</var> is not supplied, it is assumed to be <code>#table+1</code> and the value is appended to the end of the table.


The <code>add()</code> function returns the object being added. You can ignore this return value, or pass it back to your own caller.
The <code>add()</code> function returns the object being added. You can ignore this return value if you don't need it.


A stack can be easily emulated by using <code>add(s,v)</code> to push and <code>[[Deli|v=deli(s)]]</code> to pop.
A stack can be easily emulated by using <code>add(s,v)</code> to push and <code>[[Deli|v=deli(s)]]</code> to pop.
Line 20: Line 20:
add(t, 9)  -- t = {1, 5, 7, 9}
add(t, 9)  -- t = {1, 5, 7, 9}
add(t, 3, 2)  -- t = {1, 3, 5, 7, 9}
add(t, 3, 2)  -- t = {1, 3, 5, 7, 9}
-- used to create and keep track of all players
players = {}
function new_player(pad_index, name)
  return add(players, {pad_index, name})
end
</syntaxhighlight>
</syntaxhighlight>



Revision as of 11:43, 29 June 2021

add( table, value, [index] )
Adds a element to the end of a sequence in a table.
table
The table.

value
The value to add.

index
The index for the value to be inserted.

The add() function adds an element to a sequence in a table.

If an index is not supplied, it is assumed to be #table+1 and the value is appended to the end of the table.

The add() function returns the object being added. You can ignore this return value if you don't need it.

A stack can be easily emulated by using add(s,v) to push and v=deli(s) to pop.

Examples

t = {1, 5}
add(t, 7)  -- t = {1, 5, 7}
add(t, 9)  -- t = {1, 5, 7, 9}
add(t, 3, 2)  -- t = {1, 3, 5, 7, 9}

-- used to create and keep track of all players
players = {}
function new_player(pad_index, name)
  return add(players, {pad_index, name})
end

See also