Lua Game loop


Example

It's entirely possible to use PICO-8 as an interactive shell, but you probably want to tap into the game loop. In order to do that, you must create at least one of these callback functions:

  • _update()
  • _update60() (after v0.1.8)
  • _draw()

A minimal "game" might simply draw something on the screen:

function _draw()
  cls()
  print("a winner is you")
end

If you define _update60(), the game loop tries to run at 60fps and ignores update() (which runs at 30fps). Either update function is called before _draw(). If the system detects dropped frames, it'll skip the draw function every other frame, so it's best to keep game logic and player input in the update function:

function _init()
  x = 63
  y = 63

  cls()  
end

function _update()
  local dx = 0 dy = 0

  if (btn(0)) dx-=1
  if (btn(1)) dx+=1 
  if (btn(2)) dy-=1 
  if (btn(3)) dy+=1 

  x+=dx
  y+=dy
  x%=128
  y%=128
end

function _draw()
  pset(x,y)
end

The _init() function is, strictly speaking, optional as commands outside of any function are run at startup. But it's a handy way to reset the game to initial conditions without rebooting the cartridge:

if (btn(4)) _init()