PICO-8 Wiki
foreach( tbl, func )
Calls a function for each element in a sequence in a table.
The table.

The function to call. The function should accept an element as its sole argument.

The foreach() function calls a given function for each element in a sequence in a table.

Specifically, it starts with the element at index 1, calls func() with the element as an argument, then increments the index until it reaches an unassigned index (nil).


A simple example that calls the built-in print function for each element in a sequence of simple values:

t = {1, 3, 'hello', 5, 7}
foreach(t, print)

A common technique for a game is to maintain a sequence of objects that need to be drawn to the screen, with a general purpose function that can draw an object:

function draw_obj(o)
  -- draws an object...

game_objs = {}
add(game_objs, make_player_obj())
add(game_objs, make_enemy_obj())
add(game_objs, make_enemy_obj())
add(game_objs, make_enemy_obj())

foreach(game_objs, draw_obj)

If the game objects have their own obj:draw() method, you can use an anonymous function to make this a method call:

foreach(game_objs, function(obj) obj:draw() end)

See also[]