PICO-8 Wiki
Register
(Adding categories)
(→‎See also: testing: if I put the code tags around the link instead of inside of it, can I make code a different color without overriding the link color?)
Line 42: Line 42:
 
* [[Lua]]
 
* [[Lua]]
 
* [[Tables]]
 
* [[Tables]]
* [[Add|<code>add()</code>]]
+
* <code>[[Add|add()]]</code>
* [[All|<code>all()</code>]]
+
* <code>[[All|all()]]</code>
* [[Del|<code>del()</code>]]
+
* <code>[[Del|del()]]</code>
* [[Foreach|<code>foreach()</code>]]
+
* <code>[[Foreach|foreach()]]</code>
 
[[Category:API]]
 
[[Category:API]]
 
[[Category:Reference]]
 
[[Category:Reference]]

Revision as of 13:45, 20 May 2020

next( tbl, [key] )
A stateless iterator of key-value pairs for all elements in a table.
tbl
The table.

key
The current key.

The next() function is the stateless iterator that underpins pairs(), as used in for k,v in pairs(t) to iterate over all elements in a table. It takes the table and the current key and returns the next key/value pair, or nil if there isn't one. The key passed in may be omitted or nil to retrieve the first key/value pair of the table.

Under normal conditions, next() is not referred to directly, instead being supplied under the hood by pairs(). However, it has its uses. For instance, it can be called with just the table to get the first key/value pair, and thus determine quickly whether nor not the table is empty:

function empty(tbl)
  -- note that we compare to nil, since 'false' is a legal key
  return next(tbl) == nil
end

As noted with pairs(), this will iterate over every value in the table, not just those with sequential indexes. It can return keys and values for tables being used as mappings (dictionaries) or objects.

Also note that the concept of "next" here is based on the next value in the internal representation of the table (an unordered hash table). This does not guarantee the order in which the results are returned, only that you will see all entries in the table exactly once.

Examples

t = {n=42, x=100, y=200}

-- write "for k, v in pairs(t) do ... end" manually
local k, v
while true do
  k,v = next(t, k)
  if(k == nil) break
  print(k..': '..v)
end

-- output:
-- x: 100
-- y: 200
-- n: 42

See also