un~


Tables in Pico8

Image Description

This blog posts discusses two common techniques when working with objects in Lua for games especially when working with Pico8.

The Concatenation Trick

2D movement on a grid is so common in games that I use this trick all the time. It’s easy to implement and and easy to use.

Let’s look at an example. Create a new object in a cell at (i,j) in myArray with the following code:

myArray[i..","..j] = {}

This makes it incredibly easy to retrieve an object at a certain cell. Want to know if there is an item laying on the floor on the map tile in x/y? Just check if the coordinates! local item = myArray[i..","..j] and then if item then pickup(item).

To iterate over all objects in myArray you can use the pairs iterator. Caution: the objects are not ordered when using pairs!

for k,v in pairs(myArray) do
	-- v is the cell object
	-- k is a string in the form of "i,j"
end

If we want to access the objects in a particular order we should use nested for loops:

for i=1, 8 do
	for j=1, 8 do
		local cell = myArray[i..","..j]
		-- do stuff with the cell
	end
end

Objects And Container

Image Description

Entities like the spaceship in this GIF are objects. Containers for objects are special in Pico-8 because we have a couple of built-in functions to help us manage insertion and deletion. I strongly propose to use add(), del() and all() for container and entity management.

Create and add an object to a table with add():

local entities = {}
local player = {
	x = 3,
	y = 3,
	sprite = 5
}
add(entities, player)

In your _update or _draw callbacks, you will most likely want to loop over all objects. You should use all() for that:

for entity in all(entities) do
	-- do stuff here
end

You can use del() to remove an object from the container even while iterating over the container:

for entity in all(entities) do
	del(entities, entity)
end

This only works with all() and del()! This is great for games where you have objects such as bullets, effects or timed events that are added and removed dynamically.

I hope that these two hints help you to get started with objects and tables for games. For advanced users, other methods might be more efficient. I recommend reading the Pico-8 Docs or PIL for more information.