PICO-8 Wiki
Advertisement
Important
Previously, this function was considered undocumented and deprecated, but as of version 0.2.4c, it was officially documented, with additional functionality, and is thus safe to use.
count( table, [value] )
Returns the length of a table, or the number of occurrences of a value within a table.
table
The table.

value
Value to count occurrences of. The default is to count all non-nil values.

return-value
The number of occurrences.

The count() function counts the elements in the sequence section of the table in one of two ways:

  1. Counts the number of non-nil elements, or
  2. Counts the number of times the specified value appears.

Note that this will not count elements which are outside of the sequence section of the table. See the example below for a demonstration.

The # operator and count() behave differently. The correct one to use depends on what is needed:

  • The # operator returns the highest non-nil element's index, and is a quick operation that simply fetches a value that Lua tracks interally.
  • The count() function laboriously walks over the table's sequence section while it counts the non-nil (or specified) elements.

In a proper, contiguous sequence with no nil gaps, the two methods will return the same number. In this case, the # operator is the ideal, performant choice. However, with nil elements present among the table elements, the results may differ. It is important to choose the most suitable method.

Examples[]

t = {1,2,nil,4,nil,6,7}
print(count(t))
--> 5

-- this is not in t[1 ... #t] and will not be seen by count(t)
t.x = 123
print(count(t))
--> 5

-- this is not in t[1 ... #t] and will not be seen by count(t)
t[true] = "true"
print(count(t))
--> 5

-- count the number of times a value appears in a sequence-style table.
t2 = {
 'cats',
 'dogs',
 'living',
 'together',
 'mass',
 'hysteria',
 'cool',
 'cats'
}
print(count(t2, 'cats'))
--> 2

Technical Notes[]

See also[]

Advertisement