Spry

Callback Functions

spry.arg(arg)

Define this callback function to read command line arguments before anything else runs.

You should return a table with console as the key, and a boolean result as the value. This enables/disables the console output on Windows. If the value of console is false, The value of win_console in spry.conf is used instead.

Example
function spry.arg(arg)
  local usage = false
  local console = false

  for _, a in ipairs(arg) do
    if a == '--help' or a == '-h' then
      usage = true
    elseif a == '--console' then
      console = true
    end
  end

  if usage then
    local str = ([[usage:
  %s [command...]
commands:
  --help, -h  show help
  --console   use console output
]]):format(spry.program_path())

    print(str)
    os.exit()
  end

  return { console = console }
end

Arguments

Name Type Description
arg table Command line arguments.

Returns table.

Callback Functions

spry.conf(t)

Define this callback function to configure various program options.

Example
function spry.conf(t)
  t.window_width = 1280
  t.window_height = 720
end

Arguments

Name Type Default Description
t table The table to edit options with.
.win_console boolean false Windows only. Use console output.
.hot_reload boolean true Enable/disable hot reloading of scripts and assets.
.startup_load_scripts boolean true Enable/disable loading all lua scripts in the project.
.fullscreen boolean false If true, start the program in fullscreen mode.
.reload_interval number 0.1 The time in seconds to update files for hot reloading.
.swap_interval number 1 Set the swap interval. Typically 1 for VSync, or 0 for no VSync.
.target_fps number 0 Set the maximum frames to render per second. No FPS limit if target is 0.
.window_width number 800 The window width.
.window_height number 600 The window height.
.window_title string 'Spry' The window title.

Returns nothing.

Callback Functions

spry.start(arg)

Define this callback function to perform initialization work, such as loading assets, or creating objects.

Example
function spry.start(arg)
  if os.getenv 'LOCAL_LUA_DEBUGGER_VSCODE' == '1' then
    unsafe_require('lldebugger').start()
  end

  img = spry.image_load 'tile.png'
  font = spry.font_load 'roboto.ttf'
end

Arguments

Name Type Description
arg table Command line arguments.

Returns nothing.

Callback Functions

spry.frame(dt)

Define this callback function to update program state and to draw things to the screen. This function is called every frame. This function typically gets called 60 times a second if VSync is on.

Example
function spry.start()
  img = spry.image_load 'tile.png'
  x = 0
end

function spry.frame(dt)
  x = x + dt * 4
  img:draw(x, 100)
end

Arguments

Name Type Description
dt number Delta time.

Returns nothing.


Core

spry.version()

Get the version of Spry.

Example
print(spry.version())

Returns string.

Core

spry.quit()

Exit the program.

Example
if player_wants_to_quit then
  spry.quit()
end

Returns nothing.

Core

spry.platform()

Returns the platform as a string. One of html5, windows, or linux.

Example
if spry.platform() ~= 'html5' then
  display_quit_button()
end

Returns string.

Core

spry.program_path()

Returns the path to this executable.

Example
if spry.platform() ~= 'html5' then
  print(spry.program_path())
end

Returns string.

Core

spry.dt()

Returns delta time. The time in seconds between this frame and last frame.

Example
self.x = self.x + vel_x * spry.dt()

Returns number.

Core

spry.fullscreen()

Returns true if program is fullscreen.

Example
local fs = spry.fullscreen()

Returns boolean.

Core

spry.toggle_fullscreen()

Toggle fullscreen.

Example
if spry.key_press 'f11' then
  spry.toggle_fullscreen()
end

Returns nothing.

Core

spry.window_width()

Get the width of the application window.

Example
x = clamp(x, 0, spry.window_width())

Returns number.

Core

spry.window_height()

Get the height of the application window.

Example
x = clamp(x, 0, spry.window_height())

Returns number.


Input

spry.key_down(key)

Check if a keyboard key is held down since last frame.

The key can be one of the following strings:

space ' , - . / 0 1 2 3 4 5 6 7 8 9 ; = a b c d e f g h i j k l m n o p q r s t u v w x y z [ \ ] ` world_1 world_2 esc enter tab backspace insert delete right left down up pg_up pg_down home end caps_lock scroll_lock num_lock print_screen pause f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 f15 f16 f17 f18 f19 f20 f21 f22 f23 f24 f25 kp0 kp1 kp2 kp3 kp4 kp5 kp6 kp7 kp8 kp9 kp. kp/ kp* kp- kp+ kp_enter kp= lshift lctrl lalt lsuper rshift rctrl ralt rsuper menu

Example
local vy = 0
if spry.key_down 'w' then vy = vy - 1 end
if spry.key_down 's' then vy = vy + 1 end

Arguments

Name Type Description
key string The key to check.

Returns boolean.

Input

spry.key_press(key)

Check if a keyboard key was pressed since last frame. The key can be any of the strings used in spry.key_down.

Example
if spry.key_press 'space' then
  self:jump()
end

Arguments

Name Type Description
key string The key to check.

Returns boolean.

Input

spry.key_release(key)

Check if a keyboard key was released since last frame. The key can be any of the strings used in spry.key_down.

Example
if spry.key_up 'e' then
  self:interact_with(nearest_object)
end

Arguments

Name Type Description
key string The key to check.

Returns boolean.

Input

spry.mouse_down(button)

Check if a mouse button is held down since last frame. Mouse button 0 is the left button, button 1 is the right button, and button 2 is the middle button.

Example
if spry.mouse_down(0) then
  aim_to(mx, my)
end

Arguments

Name Type Description
button number The mouse button.

Returns boolean.

Input

spry.mouse_click(button)

Check if a mouse button was clicked since last frame. Mouse button 0 is the left button, button 1 is the right button, and button 2 is the middle button.

Example
if spry.mouse_click(0) then
  spawn_block(mx, my)
end

Arguments

Name Type Description
button number The mouse button.

Returns boolean.

Input

spry.mouse_release(button)

Check if a mouse button was released since last frame. Mouse button 0 is the left button, button 1 is the right button, and button 2 is the middle button.

Example
if spry.mouse_release(1) then
  show_context_menu()
end

Arguments

Name Type Description
button number The mouse button.

Returns boolean.

Input

spry.mouse_pos()

Get the mouse's current position.

Example
local mx, my = spry.mouse_pos()

Returns number, number.

Input

spry.mouse_delta()

Get the mouse's movement since last frame.

Example
local dx, dy = spry.mouse_delta()

Returns number, number.

Input

spry.show_mouse(show)

Show/hide the mouse cursor.

Example
spry.show_mouse(false)

Arguments

Name Type Description
show boolean True if cursor should be shown. False if cursor should be hidden.

Returns nothing.

Input

spry.scroll_wheel()

Get the scroll wheel value since last frame.

Example
local scroll_x, scroll_y = spry.scroll_wheel()

Returns number, number.


Drawing

spry.scissor_rect(x, y, w, h)

Limit drawing within a rectangle.

Example
function Card:draw()
  spry.scissor_rect(self.px, self.py, self.pw, self.ph)
  font:draw(self.text, self.text_x, self.text_y, 24)
end

Arguments

Name Type Default Description
x number 0 The top left x position of the rectangle.
y number 0 The top left y position of the rectangle.
w number spry.window_width() The width of the rectangle.
h number spry.window_height() The height of the rectangle.

Returns nothing.

Drawing

spry.push_matrix()

Push a matrix onto the matrix transform stack.

Example
spry.push_matrix()
spry.translate(spry.window_width() / 2, spry.window_height() / 2)
spry.scale(self.scale, self.scale)
spry.translate(-self.x, -self.y)

Returns nothing.

Drawing

spry.pop_matrix()

Pop a matrix from the matrix transform stack. You should have a matching pop_matrix for every push_matrix.

Example
spry.push_matrix()
spry.translate(spry.window_width() / 2, spry.window_height() / 2)
draw_stuff()
spry.pop_matrix()

Returns nothing.

Drawing

spry.translate(x, y)

Apply a 2D translation for the current matrix transform.

Example
spry.push_matrix()
spry.translate(camera.x, camera.y)

Arguments

Name Type Description
x number The translation in the x direction.
y number The translation in the y direction.

Returns nothing.

Drawing

spry.rotate(angle)

Apply a rotation for the current matrix transform.

Example
spry.push_matrix()
spry.rotate(camera.tilt)

Arguments

Name Type Description
angle number The angle rotation in radians.

Returns nothing.

Drawing

spry.scale(x, y)

Apply a 2D scale for the current matrix transform.

Example
spry.push_matrix()
spry.scale(camera.zoom, camera.zoom)

Arguments

Name Type Description
x number The scale in the x direction.
y number The scale in the y direction.

Returns nothing.

Drawing

spry.clear_color(r, g, b, a)

Set the background clear color. Call this before drawing the frame.

Example
spry.clear_color(255, 255, 255, 255)

Arguments

Name Type Description
r number The color's red channel, in the range [0, 255].
g number The color's green channel, in the range [0, 255].
b number The color's blue channel, in the range [0, 255].
a number The color's alpha channel, in the range [0, 255].

Returns nothing.

Drawing

spry.push_color(r, g, b, a)

Add a color to the color stack. The color is used as a tint when drawing things to the screen.

Example
if damaged then
  spry.push_color(255, 0, 0, 255)
end
img:draw(x, y)

Arguments

Name Type Description
r number The color's red channel, in the range [0, 255].
g number The color's green channel, in the range [0, 255].
b number The color's blue channel, in the range [0, 255].
a number The color's alpha channel, in the range [0, 255].

Returns nothing.

Drawing

spry.pop_color()

Remove a color from the color stack. You should have a matching pop_color for every push_color.

Example
spry.push_color(255, 0, 0, 255)
img:draw(x, y)
spry.pop_color()

Returns nothing.

Drawing

spry.draw_filled_rect(x, y, w, h, rotation, sx, sy, ox, oy)

Draw a solid filled rectangle.

Example
spry.draw_filled_rect(self.x, self.y, w, h)

Arguments

Name Type Default Description
x number 0 The x position to draw at.
y number 0 The y position to draw at.
w number 0 The width of the rectangle.
h number 0 The height of the rectangle.
rotation number 0 The rotation angle in radians.
sx number 1 The x scale factor.
sy number 1 The y scale factor.
ox number 0 The x origin offset.
oy number 0 The y origin offset.

Returns nothing.

Drawing

spry.draw_line_rect(x, y, w, h, rotation, sx, sy, ox, oy)

Draw a rectangle outline.

Example
spry.draw_line_rect(self.x, self.y, w, h)

Arguments

Name Type Default Description
x number 0 The x position to draw at.
y number 0 The y position to draw at.
w number 0 The width of the rectangle.
h number 0 The height of the rectangle.
rotation number 0 The rotation angle in radians.
sx number 1 The x scale factor.
sy number 1 The y scale factor.
ox number 0 The x origin offset.
oy number 0 The y origin offset.

Returns nothing.

Drawing

spry.draw_line_circle(x, y, radius)

Draw a circle outline.

Example
spry.draw_line_circle(self.x, self.y, radius)

Arguments

Name Type Description
x number The x position to draw at.
y number The y position to draw at.
radius number The radius of the circle.

Returns nothing.

Drawing

spry.draw_line(x0, y0, x1, y1)

Draw a line between two points.

Example
local path = tilemap:astar(...)
for i = 1, #path - 1 do
  local x0 = path[i + 0].x + off
  local y0 = path[i + 0].y + off
  local x1 = path[i + 1].x + off
  local y1 = path[i + 1].y + off

  spry.draw_line(x0, y0, x1, y1)
end

Arguments

Name Type Description
x0 number The starting x position to draw at.
y0 number The starting y position to draw at.
x1 number The ending x position to draw at.
y1 number The ending y position to draw at.

Returns nothing.


Sampler

spry.make_sampler(t)

Create a sampler used with images and fonts.

min_filter and mag_filter can be set to:

  • linear, good for pixel art
  • nearest, suitable for larger/smoother images

wrap_u and wrap_v can be set to repeat, mirroredrepeat, or clamp.

Example
my_sampler = spry.make_sampler {
  min_filter = 'linear',
  mag_filter = 'linear',
  wrap_u = 'clamp',
  wrap_v = 'clamp',
}

Arguments

Name Type Description
t table Sampler options.
.min_filter string Filter mode when scaling down.
.mag_filter string Filter mode when scaling up.
.wrap_u string Wrap mode for the horizontal direction.
.wrap_v string Wrap mode for the vertical direction.

Returns Sampler.

Sampler

spry.default_sampler()

Get the default sampler, which uses nearest neighbor filtering, and repeat wrapping.

Example
spry.default_sampler():use()
player:draw(x, y, 0, sx, sy)

Returns Sampler.

Sampler

Sampler:use()

Use this sampler for future image/font drawing.

Example
wrap_sampler:use()
background:draw(x, y, r, sx, sy, ox, oy, u0, v0, u1, v1)

Returns nothing.


Image

spry.image_load(file)

Create an image object from an image file.

Example
local tree_img = spry.image_load 'tree.png'

Arguments

Name Type Description
file string The image file to open.

Returns Image.

Image

Image:draw(x, y, r, sx, sy, ox, oy, u0, v0, u1, v1)

Draw an image onto the screen.

Example
-- draw image at (100, 100)
img:draw(100, 100)

-- draw image rotated, origin center, flipped vertically
local ox = img:width() / 2
local oy = img:height() / 2
img:draw(x, y, angle, 1, -1, ox, oy)

Arguments

Name Type Default Description
x number 0 The x position to draw at.
y number 0 The y position to draw at.
r number 0 The rotation angle in radians.
sx number 1 The x scale factor.
sy number 1 The y scale factor.
ox number 0 The x origin offset.
oy number 0 The y origin offset.
u0 number 0 The top-left x texture coordinate in the range [0, 1].
v0 number 0 The top-left y texture coordinate in the range [0, 1].
u1 number 1 The bottom-right x texture coordinate.
v1 number 1 The bottom-right y texture coordinate.

Returns nothing.

Image

Image:width()

Get the width of an image.

Example
local w = img:width()

Returns number.

Image

Image:height()

Get the height of an image.

Example
local h = img:height()

Returns number.


Font

spry.font_load(file)

Create a font object from a .ttf file.

Example
local font = spry.font_load 'roboto.ttf'

Arguments

Name Type Description
file string The font file to open.

Returns Font.

Font

spry.default_font()

Get the application's default font object.

Example
local font = spry.default_font()

Returns Font.

Font

Font:width(text, size)

Get the width of the given text, drawn at a given size.

Example
local w = font:width('Hello, World!', 32)

Arguments

Name Type Description
text string The text to calucate the width with.
size number The font size to use.

Returns number.

Font

Font:draw(text, x, y, size, limit)

Draw text onto the screen. Returns the bottom y position of the text. If limit is positive, words wrap by limit width per line.

Example
font:draw('Hello, World!', 100, 100, 30)

Arguments

Name Type Default Description
text string The text to draw.
x number 0 The x position to draw at.
y number 0 The y position to draw at.
size number 12 The size of the text.
limit number -1 Word wrap width.

Returns number.


Sound

spry.set_master_volume(volume)

Set the master volume for the program.

Example
if muted then
  spry.set_master_volume(0)
end

Arguments

Name Type Description
volume number The volume in the range [0, 1].

Returns nothing.

Sound

spry.sound_load(file)

Create a sound source from a file.

Example
local sound = spry.sound_load 'click.ogg'

Arguments

Name Type Description
file string The audio file to open.

Returns Sound.

Sound

Sound:frames()

Returns the length of the sound in PCM frames.

Example
local frames = sound:frames()

Returns number.

Sound

Sound:secs()

Returns the length of the sound in seconds.

Example
local len = sound:secs()

Returns number.

Sound

Sound:start()

Start audio playback for this sound.

Example
if enemy:hurt() then
  grunt_sound:start()
end

Returns nothing.

Sound

Sound:stop()

Stop audio playback for this sound.

Example
if enter_door then
  bgm:stop()
end

Returns nothing.

Sound

Sound:seek(f)

Seek to the given PCM frame.

Example
if music_restart then
  music:seek(0)
  music:start()
end

Arguments

Name Type Description
f number The PCM frame.

Returns nothing.

Sound

Sound:vol()

Get the sound's volume in the range [0, 1].

Example
local v = sound:vol()

Returns number.

Sound

Sound:set_vol(vol)

Set the sound's volume.

Example
local v = sound:vol()

Arguments

Name Type Description
vol number The volume in the range [0, 1].

Returns nothing.

Sound

Sound:pan()

Get the sound's panning value in the range [-1, 1].

Example
local v = sound:pan()

Returns number.

Sound

Sound:set_pan(pan)

Set the sound's panning value.

Example
local v = sound:pan()

Arguments

Name Type Description
pan number The panning in the range [-1, 1].

Returns nothing.

Sound

Sound:pitch()

Get the sound's pitch.

Example
local v = sound:pitch()

Returns number.

Sound

Sound:set_pitch(pitch)

Set the sound's pitch. A pitch of 1 does not affect the sound.

Example
if slow_mo then
  sound:set_pitch(0.5)
end

Arguments

Name Type Description
pitch number The pitch value. Should be greater than 0.

Returns nothing.

Sound

Sound:loop()

Returns true if the sound is looping.

Example
local is_loop = sound:loop()

Returns boolean.

Sound

Sound:set_loop(loop)

Set sound looping.

Example
local bgm = music_audio:make_sound()
bgm:set_loop()
bgm:start()

Arguments

Name Type Description
loop boolean True if the sound should loop.

Returns nothing.

Sound

Sound:pos()

Get the sound's position.

Example
local x, y = sound:pos()

Returns number, number.

Sound

Sound:set_pos(x, y)

Set the sound's position.

Example
function Car:update()
  self.engine_sound:set_pos(self.x, self.y)
end

Arguments

Name Type Description
x number The x position of the sound in the range [-1, 1].
y number The y position of the sound in the range [-1, 1].

Returns nothing.

Sound

Sound:vel()

Get the sound's velocity.

Example
local x, y = sound:vel()

Returns number, number.

Sound

Sound:set_vel(x, y)

Set the sound's velocity used for doppler effect.

Example
whoosh:set_vel(self.x, self.y)

Arguments

Name Type Description
x number The x velocity of the sound.
y number The y velocity of the sound.

Returns nothing.

Sound

Sound:set_fade(from, to, ms)

Fade a sound in/out.

Example
wind:set_fade(-1, 0, 1000)

Arguments

Name Type Description
from number Starting volume. Set to -1 to use the current volume.
to number Ending volume.
ms number Number of milliseconds to fade.

Returns nothing.


Sprite

spry.sprite_load(file)

Create a sprite from an Aseprite file. Sprite data is cached, so calling this multiple tiles for the same file is cheap.

Example
function Player:new()
  self.sprite = spry.sprite_load 'player.ase'
end

Arguments

Name Type Description
file string The Aseprite file to open.

Returns Sprite.

Sprite

Sprite:play(tag, restart)

Play an animation loop with the given tag. If the sprite's animation loop is the same as the previous, then this function does nothing, unless restart is also set to true.

Example
if spry.key_down 'w' then
  spr:play 'walk_up'
end

Arguments

Name Type Description
tag string The tag name.
restart boolean Force the animation to start on the first frame of the loop.

Returns nothing.

Sprite

Sprite:update(dt)

Call this method every frame to update a sprite's animation state.

Example
spr:update(dt)

Arguments

Name Type Description
dt number Delta time.

Returns nothing.

Sprite

Sprite:draw(x, y, r, sx, sy, ox, oy)

Draw a sprite on the screen.

Example
spr:draw(x, y)

Arguments

Name Type Default Description
x number 0 The x position to draw at.
y number 0 The y position to draw at.
r number 0 The rotation angle in radians.
sx number 1 The x scale factor.
sy number 1 The y scale factor.
ox number 0 The x origin offset.
oy number 0 The y origin offset.

Returns nothing.

Sprite

Sprite:width()

Get the width of a sprite in pixels.

Example
local w = spr:width()

Returns number.

Sprite

Sprite:height()

Get the height of a sprite in pixels.

Example
local h = spr:height()

Returns number.

Sprite

Sprite:set_frame(frame)

Set the current frame index for a sprite.

Example
if spry.mouse_click(0) then
  sprite:set_frame(0)
end

Arguments

Name Type Description
frame number The frame index to set.

Returns nothing.

Sprite

Sprite:total_frames()

Get the total number of frames of a sprite.

Example
local frames = sprite:total_frames()

Returns number.


Texture Atlas

spry.atlas_load(file)

Create an atlas object from an .rtpa file, generated from rTexPacker. The atlas image (.png) is expected to be in the same directory as the .rtpa file.

Example
local atlas = spry.atlas_load 'atlas.rtpa'

Arguments

Name Type Description
file string The .rtpa file to open.

Returns Atlas.

Texture Atlas

Atlas:get_image(name)

Get an atlas image object with the given name. Atlas image objects store texture coordinates to draw a sub-section of a texture atlas.

Example
local ship = atlas:get_image 'ship_01'
ship:draw(...)

Arguments

Name Type Description
name string The image name to get.

Returns AtlasImage.

Texture Atlas

AtlasImage:draw(x, y, r, sx, sy, ox, oy)

Draw an atlas image to the screen.

Example
local ship = atlas:get_image 'ship_01'
ship:draw(x, y, angle, 1, 1, ship:width() / 2, ship:height() / 2)

Arguments

Name Type Default Description
x number 0 The x position to draw at.
y number 0 The y position to draw at.
r number 0 The rotation angle in radians.
sx number 1 The x scale factor.
sy number 1 The y scale factor.
ox number 0 The x origin offset.
oy number 0 The y origin offset.

Returns nothing.

Texture Atlas

AtlasImage:width()

Get the width of an atlas image.

Example
local offset_x = ship:width()

Returns number.

Texture Atlas

AtlasImage:height()

Get the height of an atlas image.

Example
local offset_y = ship:height()

Returns number.


Tilemap

spry.tilemap_load(file)

Create a tilemap object from a LDtk file. LDtk is a 2D level editor.

Example
local tilemap = spry.tilemap_load 'world.ldtk'

Arguments

Name Type Description
file string The tilemap file to open.

Returns Tilemap.

Tilemap

Tilemap:draw()

Draw an entire tilemap, including all of the map's levels and layers.

Example
camera:begin_draw()
tilemap:draw()
camera:end_draw()

Returns nothing.

Tilemap

Tilemap:entities()

Returns a list of entities for a tilemap.

Example
for _, v in ipairs(tilemap:entities()) do
  local Entity = lookup_entity_by_id(v.id)
  if Entity ~= nil then
    local obj = world:add(Entity(v.x, v.y))
    if v.id == 'Player' then
      player = obj
    end
  else
    print('no ' .. v.id .. ' entity exists')
  end
end

Returns table.

Tilemap

Tilemap:make_collision(world, layer, walls)

Create Box2D fixtures for a tilemap. Mark certain tiles for collision by providing an array of IntGrid values.

Example
b2 = spry.b2_world { gx = 0, gy = 0, meter = 16 }
tilemap = spry.tilemap_load 'map.ldtk'
tilemap:make_collision(b2, 16, 'Collision', { 1, 2 })

Arguments

Name Type Description
world b2World The Box2D physics world.
layer string The name of the IntGrid collision layer.
walls table An array of numbers used for collision.

Returns nothing.

Tilemap

Tilemap:draw_fixtures(world, layer)

Draw all box fixtures for a given tilemap layer.

Example
tilemap:draw_fixtures(b2, 'Collision')

Arguments

Name Type Description
world b2World The Box2D physics world.
layer string The name of the IntGrid collision layer.

Returns nothing.

Tilemap

Tilemap:make_graph(layer, costs, bloom)

Prepare a tilemap for pathfinding by internally constructing a graph.

The costs argument is required. The keys are the IntGrid values and the values are the costs to traverse to each tile. Any IntGrid values not in the costs table will be ignored.

The bloom argument determines the number of nodes to consider as neighbor nodes. For example, a bloom of 1 looks at adjacent tiles. A bloom of 2 looks for nodes in a 5x5 region, 2 nodes outwards. Bloom of 3 looks for nodes in a 7x7 region, 3 nodes outwards, etc.

Example
tilemap = spry.tilemap_load 'map.ldtk'
tilemap:make_graph('Floor', { [1] = 1, [2] = 1 }, 2)

Arguments

Name Type Default Description
layer string The name of the IntGrid collision layer.
costs table The costs to traverse to each tile.
bloom number 1 The number of nodes outwards to consider as neighbors.

Returns nothing.

Tilemap

Tilemap:astar(sx, sy, ex, ey)

Find the shortest path between two tiles.

Example
local path = tilemap:astar(start.x, start.y, goal.x, goal.y)
for k, v in ipairs(path) do
  spry.draw_filled_rect(v.x, v.y, 16, 16)
end

Arguments

Name Type Description
sx number The starting tile's x position.
sy number The starting tile's y position.
ex number The target tile's x position.
ey number The target tile's y position.

Returns table.


Box2D World

spry.b2_world(t)

Create a new Box2D World.

Example
local b2_world = spry.b2_world { gx = 0, gy = 9.81, meter = 80 }

Arguments

Name Type Description
t table World options.
.gx number The world's x component for gravity.
.gy number The world's y component for gravity.
.meter number The number of pixels for one meter.

Returns b2World.

Box2D World

b2World:step(dt, vel_iters, pos_iters)

Call this every frame to set the physics world in motion.

Example
function spry.frame(dt)
  -- update
  b2_world:step(dt)
  -- draw
  body:draw_fixtures()
end

Arguments

Name Type Default Description
dt number Delta time.
vel_iters number 6 Number of iterations in the constraint solver's velocity phase.
pos_iters number 2 Number of iterations in the constraint solver's position phase.

Returns b2World.

Box2D World

b2World:make_static_body(t)

Create a static physics body.

Example
b2_world:make_static_body { x = 300, y = 400 }

Arguments

Name Type Default Description
t table Body definition.
.x number The x position of the physics body.
.y number The y position of the physics body.
.vx number 0 The x velocity of the physics body.
.vy number 0 The y velocity of the physics body.
.angle number 0 The angle of the physics body in radians.
.linear_damping number 0 The linear damping of the physics body.
.fixed_rotation boolean false If true, prevent the physics body from rotating.
.udata string | number nil Custom user data for this body.

Returns b2Body.

Box2D World

b2World:make_kinematic_body(t)

Create a kinematic physics body.

Example
b2_world:make_kinematic_body { x = 300, y = 400, vx = 10 }

Arguments

Name Type Default Description
t table Body definition.
.x number The x position of the physics body.
.y number The y position of the physics body.
.vx number 0 The x velocity of the physics body.
.vy number 0 The y velocity of the physics body.
.angle number 0 The angle of the physics body in radians.
.linear_damping number 0 The linear damping of the physics body.
.fixed_rotation boolean false If true, prevent the physics body from rotating.
.udata string | number nil Custom user data for this body.

Returns b2Body.

Box2D World

b2World:make_dynamic_body(t)

Create a dynamic physics body.

Example
b2_world:make_dynamic_body { x = 300, y = 400 }

Arguments

Name Type Default Description
t table Body definition.
.x number The x position of the physics body.
.y number The y position of the physics body.
.vx number 0 The x velocity of the physics body.
.vy number 0 The y velocity of the physics body.
.angle number 0 The angle of the physics body in radians.
.linear_damping number 0 The linear damping of the physics body.
.fixed_rotation boolean false If true, prevent the physics body from rotating.
.udata string | number nil Custom user data for this body.

Returns b2Body.

Box2D World

b2World:begin_contact(fn)

Run a given callback function when two fixtures touch each other.

Example
b2_world:begin_contact(function(a, b)
  local sensor
  local other
  if a:udata() == 'sensor' then
    sensor, other = a, b
  elseif b:udata() == 'sensor' then
    sensor, other = b, a
  end

  if sensor ~= nil then
    sensor_box.count = sensor_box.count + 1
    get_actor(other):handle_sensor()
  end
end)

Arguments

Name Type Description
fn function The callback function to call on contact. Takes two arguments, both of which are fixtures.

Returns nothing.

Box2D World

b2World:end_contact(fn)

Run a given callback function when two fixtures stop touching each other.

Example
b2_world:end_contact(function(a, b)
  local sensor
  if a:udata() == 'sensor' then
    sensor = a
  elseif b:udata() == 'sensor' then
    sensor = b
  end

  if sensor ~= nil then
    sensor_box.count = sensor_box.count - 1
  end
end)

Arguments

Name Type Description
fn function The callback function to call after contact. Takes two arguments, both of which are fixtures.

Returns nothing.


Box2D Body

b2Body:destroy()

Immediately destroy a physics body.

Example
function Box:on_death()
  self.body:destroy()
end

Returns nothing.

Box2D Body

b2Body:make_box_fixture(t)

Attach a box shaped fixture to a body.

Example
ground.body:make_box_fixture { w = 100, h = 50, friction = 1 }

Arguments

Name Type Default Description
t table Fixture definition.
.x number 0 The box fixture's x offset from the center of the body.
.y number 0 The box fixture's y offset from the center of the body.
.w number The box fixture's width.
.h number The box fixture's height.
.angle number 0 The box fixture's angle in radians.
.sensor boolean false True if the fixture should be a sensor.
.density number 1 The fixture's density.
.friction number 0.2 The fixture's friction.
.restitution number 0 The fixture's restitution.
.udata string | number nil Custom user data for this fixture.
.begin_contact function nil Run a callback function when this fixture touches another.
.end_contact function nil Run a callback function when this fixture stops touching another.

Returns b2Fixture.

Box2D Body

b2Body:make_circle_fixture(t)

Attach a circle shaped fixture to a body.

Example
body:make_circle_fixture { radius = 3, density = 1, friction = 0.3 }

Arguments

Name Type Default Description
t table Fixture definition.
.x number 0 The box fixture's x offset from the center of the body.
.y number 0 The box fixture's y offset from the center of the body.
.radius number The circle fixture's radius.
.sensor boolean false True if the fixture should be a sensor.
.density number 1 The fixture's density.
.friction number 0.2 The fixture's friction.
.restitution number 0 The fixture's restitution.
.udata string | number nil Custom user data for this fixture.
.begin_contact function nil Run a callback function when this fixture touches another.
.end_contact function nil Run a callback function when this fixture stops touching another.

Returns b2Fixture.

Box2D Body

b2Body:position()

Get the position of a physics body.

Example
local x, y = body:position()

Returns number, number.

Box2D Body

b2Body:velocity()

Get the linear velocity of a physics body.

Example
local vx, vy = body:velocity()

Returns number, number.

Box2D Body

b2Body:angle()

Get the angle of a physics body in radians.

Example
local angle = body:angle()

Returns number.

Box2D Body

b2Body:linear_damping()

Get the linear damping of a physics body.

Example
local damping = body:linear_damping()

Returns number.

Box2D Body

b2Body:fixed_rotation()

See if the physics body uses fixed rotation.

Example
local fixed = body:fixed_rotation()

Returns boolean.

Box2D Body

b2Body:apply_force(x, y)

Apply the given force to the center of a body.

Example
body:apply_force(fx, fy)

Arguments

Name Type Description
x number The force x component.
y number The force y component.

Returns nothing.

Box2D Body

b2Body:apply_impulse(x, y)

Apply linear impulse (immediate force) to the center of a body.

Example
body:apply_impulse(fx, fy)

Arguments

Name Type Description
x number The linear impulse x component.
y number The linear impulse y component.

Returns nothing.

Box2D Body

b2Body:set_position(x, y)

Set the physics body's position.

Example
body:set_position(mouse_x, mouse_y)

Arguments

Name Type Description
x number The x position to move the body to.
y number The y position to move the body to.

Returns nothing.

Box2D Body

b2Body:set_velocity(x, y)

Set the physics body's velocity.

Example
body:set_velocity(move_x, move_y)

Arguments

Name Type Description
x number The x velocity.
y number The y velocity.

Returns nothing.

Box2D Body

b2Body:set_angle(angle)

Set the physics body's angle.

Example
body:set_angle(angle)

Arguments

Name Type Description
angle number The angle to set.

Returns nothing.

Box2D Body

b2Body:set_linear_damping(damping)

Set the physics body's linear damping.

Example
body:set_linear_damping(30)

Arguments

Name Type Description
damping number The linear damping to set.

Returns nothing.

Box2D Body

b2Body:set_fixed_rotation(angle)

Fix the rotation of a physics body.

Example
body:set_fixed_rotation(true)

Arguments

Name Type Description
angle boolean If true, prevent the body from rotating.

Returns nothing.

Box2D Body

b2Body:set_transform(x, y, angle)

Set the physics body's position and angle.

Example
body:set_transform(x, y, angle)

Arguments

Name Type Description
x number The x position to move the body to.
y number The y position to move the body to.
angle number The angle to set.

Returns nothing.

Box2D Body

b2Body:draw_fixtures()

Draws all fixtures attached to a physics body.

Example
if show_debug_info then
  show_fps()
  body:draw_fixtures()
end

Returns nothing.

Box2D Body

b2Body:udata()

Get the attached user data for a physics body.

Example
print(body:udata())

Returns string | number.


Box2D Fixture

b2Fixture:friction()

Get the friction value of a fixture.

Example
if fixture:friction() > 0.95 then
  actor.is_sandpaper = true
end

Returns number.

Box2D Fixture

b2Fixture:restitution()

Get the restitution value of a fixture.

Example
if fixture:restitution() > 0.9 then
  actor.is_bouncy = true
end

Returns number.

Box2D Fixture

b2Fixture:is_sensor()

Returns true if a fixture is a sensor.

Example
function on_begin_contact(a, b)
  if a:is_sensor() or b:is_sensor() then
    return
  end

  handle_contact(a, b)
end

Returns boolean.

Box2D Fixture

b2Fixture:set_friction(friction)

Set the fixture's friction value.

Example
function Ball:on_contact()
  self.fixture:set_friction(5)
end

Arguments

Name Type Description
friction number The friction value. Typically between [0, 1].

Returns nothing.

Box2D Fixture

b2Fixture:set_restitution(restitution)

Set the fixture's restitution value.

Example
function Ball:on_contact()
  self.fixture:set_restitution(0)
end

Arguments

Name Type Description
restitution number The restitution value. Typically between [0, 1].

Returns nothing.

Box2D Fixture

b2Fixture:set_sensor(sensor)

Set the fixture's sensor state.

Example
fixture:set_sensor(true)

Arguments

Name Type Description
sensor boolean True if the fixture should be a sensor.

Returns nothing.

Box2D Fixture

b2Fixture:body()

Get the physics body of a fixture.

Example
local str = fixture:body():udata()

Returns b2Body.

Box2D Fixture

b2Fixture:udata()

Get the attached user data for a fixture.

Example
print(fixture:udata())

Returns string | number.


LuaSocket

require('socket')

LuaSocket module. Visit https://lunarmodules.github.io/luasocket/introduction.html for details.

This module is not available for web builds.

Example
local socket = require 'socket'

function spry.start()
  sock = socket.udp()
  sock:setpeername('127.0.0.1', 3000)
  sock:send 'Hello from client to server'
end

microui

spry.microui

Namespace for the microui module. The API is similar to the one found in C. The microui.ref function is used for controls that used to rely on pointers.

This namespace contains following constants:

VERSION

COMMANDLIST_SIZE, ROOTLIST_SIZE, CONTAINERSTACK_SIZE, CLIPSTACK_SIZE, IDSTACK_SIZE, LAYOUTSTACK_SIZE, CONTAINERPOOL_SIZE, TREENODEPOOL_SIZE, MAX_WIDTHS, REAL_FMT, SLIDER_FMT, MAX_FMT

CLIP_PART, CLIP_ALL

COMMAND_JUMP, COMMAND_CLIP, COMMAND_RECT, COMMAND_TEXT, COMMAND_ICON

COLOR_TEXT, COLOR_BORDER, COLOR_WINDOWBG, COLOR_TITLEBG, COLOR_TITLETEXT, COLOR_PANELBG, COLOR_BUTTON, COLOR_BUTTONHOVER, COLOR_BUTTONFOCUS, COLOR_BASE, COLOR_BASEHOVER, COLOR_BASEFOCUS, COLOR_SCROLLBASE, COLOR_SCROLLTHUMB

ICON_CLOSE, ICON_CHECK, ICON_COLLAPSED, ICON_EXPANDED

RES_ACTIVE, RES_SUBMIT, RES_CHANGE

OPT_ALIGNCENTER, OPT_ALIGNRIGHT, OPT_NOINTERACT, OPT_NOFRAME, OPT_NORESIZE, OPT_NOSCROLL, OPT_NOCLOSE, OPT_NOTITLE, OPT_HOLDFOCUS, OPT_AUTOSIZE, OPT_POPUP, OPT_CLOSED, OPT_EXPANDED

Example
function spry.start()
  mu = spry.microui
end

function spry.frame(dt)
  if mu.begin_window('Test Window', mu.rect(40, 40, 300, 400)) then
    if mu.header('Test Buttons', mu.OPT_EXPANDED) then
      mu.layout_row({-1}, 0)
      mu.label 'Test buttons 1:'
      mu.layout_row({150, -1}, 0)
      if mu.button 'Button 1' then print 'Pressed button 1' end
      if mu.button 'Button 2' then print 'Pressed button 2' end
    end

    mu.end_window()
  end
end

microui

microui.set_focus(id)

Arguments

Name Type
id number

Returns nothing.

microui

microui.get_id(name)

Arguments

Name Type
name string

Returns number.

microui

microui.push_id(name)

Arguments

Name Type
name string

Returns nothing.

microui

microui.pop_id()

Returns nothing.

microui

microui.push_clip_rect(rect)

Arguments

Name Type Description
rect table Rectangle definition.
.x number The top left x position.
.y number The top left y position.
.w number The width of the rectangle.
.h number The height of the rectangle.

Returns nothing.

microui

microui.pop_clip_rect()

Returns nothing.

microui

microui.get_clip_rect()

Returns the clip rect with x, y, w, h keys.

Returns table.

microui

microui.check_clip(rect)

Check clip result by using mu.CLIP_PART and mu.CLIP_ALL.

Arguments

Name Type Description
rect table Rectangle definition.
.x number The top left x position.
.y number The top left y position.
.w number The width of the rectangle.
.h number The height of the rectangle.

Returns number.

microui

microui.get_current_container()

Returns mu_Container.

microui

microui.get_container(name)

Arguments

Name Type
name string

Returns mu_Container.

microui

microui.bring_to_front(container)

Arguments

Name Type
container mu_Container

Returns nothing.

microui

microui.set_clip(rect)

Arguments

Name Type Description
rect table Rectangle definition.
.x number The top left x position.
.y number The top left y position.
.w number The width of the rectangle.
.h number The height of the rectangle.

Returns nothing.

microui

microui.draw_rect(rect, color)

Arguments

Name Type Description
rect table Rectangle definition.
.x number The top left x position.
.y number The top left y position.
.w number The width of the rectangle.
.h number The height of the rectangle.
color table Color definition.
.r number The color's red channel, in the range [0, 255].
.g number The color's green channel, in the range [0, 255].
.b number The color's blue channel, in the range [0, 255].
.a number The color's alpha channel, in the range [0, 255].

Returns nothing.

microui

microui.draw_box(rect, color)

Arguments

Name Type Description
rect table Rectangle definition.
.x number The top left x position.
.y number The top left y position.
.w number The width of the rectangle.
.h number The height of the rectangle.
color table Color definition.
.r number The color's red channel, in the range [0, 255].
.g number The color's green channel, in the range [0, 255].
.b number The color's blue channel, in the range [0, 255].
.a number The color's alpha channel, in the range [0, 255].

Returns nothing.

microui

microui.draw_text(str, x, y, color)

Arguments

Name Type Description
str string
x number
y number
color table Color definition.
.r number The color's red channel, in the range [0, 255].
.g number The color's green channel, in the range [0, 255].
.b number The color's blue channel, in the range [0, 255].
.a number The color's alpha channel, in the range [0, 255].

Returns nothing.

microui

microui.draw_icon(id, rect, color)

Arguments

Name Type Description
id number
rect table Rectangle definition.
.x number The top left x position.
.y number The top left y position.
.w number The width of the rectangle.
.h number The height of the rectangle.
color table Color definition.
.r number The color's red channel, in the range [0, 255].
.g number The color's green channel, in the range [0, 255].
.b number The color's blue channel, in the range [0, 255].
.a number The color's alpha channel, in the range [0, 255].

Returns nothing.

microui

microui.layout_row(widths, height)

Similar to C's version of mu_layout_row, takes two arguments instead of three.

Arguments

Name Type Description
widths table Widths of each item in the row.
height number Height of the row.

Returns nothing.

microui

microui.layout_width(width)

Arguments

Name Type
width number

Returns nothing.

microui

microui.layout_height(height)

Arguments

Name Type
height number

Returns nothing.

microui

microui.layout_begin_column()

Returns nothing.

microui

microui.layout_end_column()

Returns nothing.

microui

microui.layout_set_next(rect, relative)

Arguments

Name Type Description
rect table Rectangle definition.
.x number The top left x position.
.y number The top left y position.
.w number The width of the rectangle.
.h number The height of the rectangle.
relative boolean

Returns nothing.

microui

microui.draw_control_frame(id, rect, colorid, opt)

Arguments

Name Type Description
id number
rect table Rectangle definition.
.x number The top left x position.
.y number The top left y position.
.w number The width of the rectangle.
.h number The height of the rectangle.
colorid number
opt number

Returns nothing.

microui

microui.draw_control_text(str, rect, colorid, opt)

Arguments

Name Type Description
str string
rect table Rectangle definition.
.x number The top left x position.
.y number The top left y position.
.w number The width of the rectangle.
.h number The height of the rectangle.
colorid number
opt number

Returns nothing.

microui

microui.mouse_over(rect)

Arguments

Name Type Description
rect table Rectangle definition.
.x number The top left x position.
.y number The top left y position.
.w number The width of the rectangle.
.h number The height of the rectangle.

Returns boolean.

microui

microui.update_control(id, rect, opt)

Arguments

Name Type Description
id number
rect table Rectangle definition.
.x number The top left x position.
.y number The top left y position.
.w number The width of the rectangle.
.h number The height of the rectangle.
opt number

Returns nothing.

microui

microui.text(text)

Arguments

Name Type
text string

Returns nothing.

microui

microui.label(text)

Arguments

Name Type
text string

Returns nothing.

microui

microui.button(text, icon, opt)

Arguments

Name Type Default
text string
icon number 0
opt number microui.OPT_ALIGNCENTER

Returns boolean.

microui

microui.checkbox(text, ref)

Arguments

Name Type
text string
ref mu_Ref

Returns number.

microui

microui.textbox_raw(ref, id, rect, opt)

Arguments

Name Type Default Description
ref mu_Ref
id number
rect table Rectangle definition.
.x number The top left x position.
.y number The top left y position.
.w number The width of the rectangle.
.h number The height of the rectangle.
opt number 0

Returns number.

microui

microui.textbox(ref, opt)

Arguments

Name Type Default
ref mu_Ref
opt number 0

Returns number.

microui

microui.slider(ref, low, high, step, fmt, opt)

Arguments

Name Type Default
ref mu_Ref
low number
high number
step number 0
fmt string microui.SLIDER_FMT
opt number microui.OPT_ALIGNCENTER

Returns number.

microui

microui.number(ref, step, fmt, opt)

Arguments

Name Type Default
ref mu_Ref
step number
fmt string microui.SLIDER_FMT
opt number microui.OPT_ALIGNCENTER

Returns number.

microui

microui.header(text, opt)

Arguments

Name Type Default
text string
opt number 0

Returns boolean.

microui

microui.begin_treenode(label, opt)

Arguments

Name Type Default
label string
opt number 0

Returns boolean.

microui

microui.end_treenode()

Returns nothing.

microui

microui.begin_window(title, rect, opt)

Arguments

Name Type Default Description
title string
rect table Rectangle definition.
.x number The top left x position.
.y number The top left y position.
.w number The width of the rectangle.
.h number The height of the rectangle.
opt number 0

Returns boolean.

microui

microui.end_window()

Returns nothing.

microui

microui.open_popup(name)

Arguments

Name Type
name string

Returns nothing.

microui

microui.begin_popup(name)

Arguments

Name Type
name string

Returns boolean.

microui

microui.end_popup()

Returns nothing.

microui

microui.begin_panel(name, opt)

Arguments

Name Type Default
name string
opt number 0

Returns nothing.

microui

microui.end_panel()

Returns nothing.

microui

microui.get_hover()

Accessor for mu_Context.hover.

Returns number.

microui

microui.get_focus()

Accessor for mu_Context.focus.

Returns number.

microui

microui.get_last_id()

Accessor for mu_Context.last_id.

Returns number.

microui

microui.get_style()

Accessor for mu_Context.style.

Returns mu_Style.

microui

microui.rect(x, y, w, h)

Create a table with x, y, w, h keys.

Example
local rect0 = spry.microui.rect(10, 10, 400, 300)
local rect1 = { x = 10, y = 10, w = 400, h = 300 }

assert(rect0.x == rect1.x)
assert(rect0.y == rect1.y)
assert(rect0.w == rect1.w)
assert(rect0.h == rect1.h)

Arguments

Name Type Description
x number The top left x position.
y number The top left y position.
w number The width of the rectangle.
h number The height of the rectangle.

Returns table.

microui

microui.color(r, g, b, a)

Create a table with r, g, b, a keys.

Example
local col0 = spry.microui.col(128, 128, 128, 255)
local col1 = { r = 128, g = 128, b = 128, a = 255 }

assert(col0.r == col1.r)
assert(col0.g == col1.g)
assert(col0.b == col1.b)
assert(col0.a == col1.a)

Arguments

Name Type Description
r number The color's red channel, in the range [0, 255].
g number The color's green channel, in the range [0, 255].
b number The color's blue channel, in the range [0, 255].
a number The color's alpha channel, in the range [0, 255].

Returns table.


microui Container

mu_Container:rect()

Get the container rectangle with x, y, w, h keys.

Returns table.

microui Container

mu_Container:set_rect(rect)

Arguments

Name Type Description
rect table Rectangle definition.
.x number The top left x position.
.y number The top left y position.
.w number The width of the rectangle.
.h number The height of the rectangle.

Returns nothing.

microui Container

mu_Container:body()

Get the container body with x, y, w, h keys.

Returns table.

microui Container

mu_Container:content_size()

Returns number, number.

microui Container

mu_Container:scroll()

Returns number, number.

microui Container

mu_Container:set_scroll(x, y)

Arguments

Name Type Description
x number The x scroll position.
y number The y scroll position.

Returns nothing.

microui Container

mu_Container:zindex()

Returns number.

microui Container

mu_Container:open()

Returns boolean.


microui Style

mu_Style:size()

Returns number, number.

microui Style

mu_Style:set_size(x, y)

Arguments

Name Type
x number
y number

Returns nothing.

microui Style

mu_Style:padding()

Returns number.

microui Style

mu_Style:set_padding(padding)

Arguments

Name Type
padding number

Returns nothing.

microui Style

mu_Style:spacing()

Returns number.

microui Style

mu_Style:set_spacing(spacing)

Arguments

Name Type
spacing number

Returns nothing.

microui Style

mu_Style:indent()

Returns number.

microui Style

mu_Style:set_indent(indent)

Arguments

Name Type
indent number

Returns nothing.

microui Style

mu_Style:title_height()

Returns number.

microui Style

mu_Style:set_title_height(title_height)

Arguments

Name Type
title_height number

Returns nothing.

microui Style

mu_Style:scrollbar_size()

Returns number.

microui Style

mu_Style:set_scrollbar_size(scrollbar_size)

Arguments

Name Type
scrollbar_size number

Returns nothing.

microui Style

mu_Style:thumb_size()

Returns number.

microui Style

mu_Style:set_thumb_size(thumb_size)

Arguments

Name Type
thumb_size number

Returns nothing.

microui Style

mu_Style:color(colorid)

Get the color with r, g, b, a keys using given id.

Arguments

Name Type
colorid number

Returns table.

microui Style

mu_Style:set_color(colorid, color)

Arguments

Name Type Description
colorid number
color table Color definition.
.r number The color's red channel, in the range [0, 255].
.g number The color's green channel, in the range [0, 255].
.b number The color's blue channel, in the range [0, 255].
.a number The color's alpha channel, in the range [0, 255].

Returns nothing.


microui Ref

microui.ref(value)

Returns userdata value that can be passed into several microui functions.

Example
function spry.start()
  mu = spry.microui

  check = mu.ref(false)
  text = mu.ref 'Hello, World!'
  color = {
    r = mu.ref(90),
    g = mu.ref(95),
    b = mu.ref(100),
  }
end

function spry.frame(dt)
  local col = {
    r = color.r:get(),
    g = color.g:get(),
    b = color.b:get(),
    a = 255,
  }
  spry.clear_color(col.r, col.g, col.b, col.a)

  font:draw(text:get(), 400, 100, 24)

  if mu.begin_window('Window', mu.rect(40, 40, 300, 400)) then
    if mu.header('Inputs', mu.OPT_EXPANDED) then
      mu.checkbox('My Checkbox', check)
      mu.textbox(text)

      mu.layout_row({50, -1}, 0)
      mu.label 'Red:'; mu.slider(color.r, 0, 255)
      mu.label 'Green:'; mu.slider(color.g, 0, 255)
      mu.label 'Blue:'; mu.slider(color.b, 0, 255)
    end

    mu.end_window()
  end
end

Arguments

Name Type Description
value any A boolean, number, or string value.

Returns mu_Ref.

microui Ref

mu_Ref:get()

Get the internal value of this object.

Example
function spry.start()
  mu = spry.microui
  text = mu.ref 'Hello, World!'
end

function spry.frame(dt)
  font:draw(text:get(), 400, 100, 24)
end

Returns any.

microui Ref

mu_Ref:set(value)

Set the internal value of this object.

Example
if (mu.textbox(text) & mu.RES_SUBMIT) ~= 0 then
  mu.set_focus(mu.get_last_id())
  text:set ''
end

Arguments

Name Type Description
value any A boolean, number, or string value.

Returns nothing.


2D Vector

vec2(x, y)

Create a new 2D vector.

Example
local a = vec2(self.x, self.y)
local b = vec2(other.x, other.y)
local c = a + b
print(c.x, c.y)

Arguments

Name Type Description
x number The vector's x component.
y number The vector's y component.

Returns vec2.

2D Vector

vec2:normalize()

Get a vector with length 1, or vec2(0, 0) if this vector is also vec2(0, 0).

Example
local move_dir = input_axes:normalize()

Returns vec2.

2D Vector

vec2:distance(rhs)

Return the distance between two vectors.

Example
local dist = pos:distance(enemy)

Arguments

Name Type Description
rhs vec2 Another vector.

Returns number.

2D Vector

vec2:direction(rhs)

Return the direction from this vector to rhs in radians.

Example
local angle = pos:angle(enemy)

Arguments

Name Type Description
rhs vec2 Another vector.

Returns number.

2D Vector

vec2:lerp(rhs, t)

Linearly interpolate between this vector and rhs. Produces a new vector.

Example
pos = pos:lerp(other, t)

Arguments

Name Type Description
rhs vec2 Another vector.
t number The interpolation amount.

Returns vec2.

2D Vector

vec2:dot(rhs)

The dot product of this vector and rhs.

Example
local dp = vel:dot(normal)

Arguments

Name Type Description
rhs vec2 Another vector.

Returns number.

2D Vector

vec2:unpack()

Returns the x and y components of this vector.

Example
local x, y = vel:unpack()

Returns number, number.

2D Vector

vec2.__add(lhs, rhs)

Add two vectors.

Example
local v3 = v1 + v2

Arguments

Name Type Description
lhs vec2 Left hand side vector.
rhs vec2 Right hand side vector.

Returns vec2.

2D Vector

vec2.__sub(lhs, rhs)

Subtract two vectors.

Example
local v3 = v1 - v2

Arguments

Name Type Description
lhs vec2 Left hand side vector.
rhs vec2 Right hand side vector.

Returns vec2.

2D Vector

vec2.__mul(lhs, rhs)

Multiply two vectors.

Example
local v3 = v1 * v2

Arguments

Name Type Description
lhs vec2 Left hand side vector.
rhs vec2 Right hand side vector.

Returns vec2.

2D Vector

vec2.__div(lhs, rhs)

Divide two vectors.

Example
local v3 = v1 / v2

Arguments

Name Type Description
lhs vec2 Left hand side vector.
rhs vec2 Right hand side vector.

Returns vec2.

2D Vector

vec2:__len()

Get the length of a vector.

Example
local length = #vel

Returns number.

2D Vector

vec2.__eq(lhs, rhs)

Check if two vectors are the same.

Example
print(v1 == v2)

Arguments

Name Type Description
lhs vec2 Left hand side vector.
rhs vec2 Right hand side vector.

Returns boolean.


World

World()

Create a new world object, which manages object/actor creation, updates, and destruction. An actor is a class with a constructor, an update method and a draw method.

Example
function spry.start()
  world = World()

  interval(2, function()
    world:add(Enemy())
  end)

  player = world:add(Player())
end

function spry.frame(dt)
  world:update(dt)
  world:draw()
end

-- example Player class

class 'Player'

function Player:new(x, y)
  self.x, self.y = x, y
end

function Player:on_create()
  -- optional. called after object is inserted into the world.
  -- use this to get the id before the first object update.
end

function Player:on_death()
  -- optional. called right before the object is removed.
  -- use this to clean up things like physics bodies.
end

function Player:update(dt)
  -- required. called during world update phase.
end

function Player:draw()
  -- required. called during world draw phase.
end

Returns World.

World

World:add(obj)

Add a new actor to the world, returns the actor passed in. When adding an actor, they are assigned an unique id.

Example
local player = world:add(Player())
print(player.id)

Arguments

Name Type Description
obj table The actor to add. It should have an update and draw method.

Returns table.

World

World:kill(obj)

Remove an actor from the world given an actor's id, or the actor itself.

Example
if bullet_hit_enemy then
  world:kill(enemy)
  world:kill(self)
end

Arguments

Name Type Description
obj number | table The actor to remove.

Returns nothing.

World

World:query_id(id)

Find an actor with the given id.

Example
local enemy = world:query_id(self.enemy_id)

Arguments

Name Type Description
id number The actor id.

Returns table.

World

World:query_mt(mt)

Find actors with the given metatable. Returns a table of entities.

Example
local bullets = world:query_mt(Bullet)
for id, bullet in pairs(bullets) do
  bullet_stuff(bullet)
end

Arguments

Name Type Description
mt table The metatable to search with.

Returns table.

World

World:update(dt)

Call this method every frame to update the world's state.

Example
world:update(dt)

Arguments

Name Type Description
dt number Delta time.

Returns nothing.

World

World:draw()

Call this method every frame to draw all entities in the world.

Example
world:draw()

Returns nothing.


Entity Component System

ECS()

Create a new ECS object. Entities are created and removed after ECS:update().

Example
function spry.start()
  ecs = ECS()

  for i = 1, 100 do
    ecs:add {
      pos = { x = 200, y = 200 },
      vel = { x = random(-100, 100), y = random(-100, 100) },
    }
  end
end

function spry.frame(dt)
  ecs:update()

  for id, e in ecs:select { 'pos', 'vel' } do
    e.pos.x = e.pos.x + e.vel.x * dt
    e.pos.y = e.pos.y + e.vel.y * dt

    -- adding a component
    if add_accel then
      e.accel = { x = ax, y = ay }
    end

    -- removing a component
    if remove_vel then
      e.vel = nil
    end
  end
end

Returns ECS.

Entity Component System

ECS:update()

Call this method every frame so that entities are created and removed properly.

Example
function spry.frame(dt)
  ecs:update()
  -- the rest of the frame
end

Returns nothing.

Entity Component System

ECS:add(entity)

Create a new entity. Returns the entity id and the given entity itself.

Example
ecs:add {
  pos = { x = spry.window_width() / 2, y = spry.window_height() / 2 },
  vel = { x = random(-100, 100), y = random(-100, 100) },
}

Arguments

Name Type Description
entity table The entity to add, where each table entry is a component.

Returns number, table.

Entity Component System

ECS:kill(id)

Given an entity id, remove an entity.

Example
if e.stats.hp == 0 then
  ecs:kill(id)
end

Arguments

Name Type Description
id number The entity id.

Returns nothing.

Entity Component System

ECS:get(id)

Returns the entity with the given id, or nil if it doesn't exist.

Example
local other = ecs:get(e.owner.id)
if other ~= nil then
  other.ammo.amount = other.ammo.amount - 1
end

Arguments

Name Type Description
id number The entity id.

Returns table.

Entity Component System

ECS:query(t)

Returns an iterator over entities that match the given query. The iterator returns the id and entity of each element.

Example
for id, e in ecs:query {
  select = { 'pos', 'img', 'z_index' },
  where = function(e)
    return e.pos.x < spry.window_width() / 2
  end,
  order_by = function(lhs, rhs)
    return lhs.entity.z_index < rhs.entity.z_index
  end,
} do
  e.pos = e.pos + e.vel * vec2(dt, dt)
  e.img:draw(e.pos.x, e.pos.y)
end

Arguments

Name Type Default Description
t table Query definition.
.select table The names of each component.
.where function nil A function used to filter out entities.
.order_by function nil A function used to sort entities.

Returns iterator.

Entity Component System

ECS:select(columns)

Returns an iterator over entities with the given components.

Example
for id, e in ecs:select { 'pos', 'vel' } do
  e.pos = e.pos + e.vel * vec2(dt, dt)
end

Arguments

Name Type Description
columns table The names of each component.

Returns iterator.


Spring

Spring(k, d)

Create a new spring object, which can simulate bouncy behaviour.

Example
function Thing:new()
  self.spring = Spring()
end

function Thing:on_hit()
  self.spring:pull(0.5)
end

function Thing:update(dt)
  self.spring:update(dt)
end

function Thing:draw()
  local sx = 1 + self.spring.x
  local sy = 1 - self.spring.x
  img:draw(self.x, self.y, 0, sx, sy)
end

Arguments

Name Type Default Description
k number 400 The spring's stiffness.
d number 28 The spring's damping.

Returns Spring.

Spring

Spring:update(dt)

Call this method every frame to update a spring's state.

Example
spring:update(dt)

Arguments

Name Type Description
dt number Delta time.

Returns nothing.

Spring

Spring:pull(f)

Pull on a string with given force.

Example
if damage_hit then
  self.spring:pull(5)
end

Arguments

Name Type Description
f number The force to pull with.

Returns nothing.


Timer

interval(sec, action)

Repeat a callback function for a given amount of seconds.

Example
interval(5, function()
  spawn_enemy()
end)

Arguments

Name Type Description
sec number Number of seconds.
action function The callback function.

Returns number.

Timer

timeout(sec, action)

After a given amount of seconds, execute a callback once.

Example
timeout(3, function()
  after_countdown()
end)

Arguments

Name Type Description
sec number Number of seconds.
action function The callback function.

Returns number.

Timer

stop_interval(id)

Stop executing the callback from interval.

Example
local timer = interval(3, fn)
stop_interval(timer)

Arguments

Name Type Description
id number The return value from calling the interval function.

Returns nothing.

Timer

stop_timeout(id)

Cancel a timeout.

Example
local timer = timeout(3, fn)
stop_timeout(timer)

Arguments

Name Type Description
id number The return value from calling the timeout function.

Returns nothing.


Object Oriented

class(name, parent)

Create a new class.

Example
-- create a global table called Player
class 'Player'

function Player:new(x, y)
  self.x = x
  self.y = y
end

function Player:update(dt)
  self.x = self.x + dt * 10
end

function Player:draw()
  img:draw(self.x, self.y)
end

function spry.start()
  img = spry.image_load 'player.png'

  -- create an instance of Player
  player = Player(200, 200)
  assert(getmetatable(player) == Player)
end

function spry.frame(dt)
  -- update position and draw
  player:update(dt)
  player:draw()
end

Arguments

Name Type Default Description
name string The name of the class.
parent table Object the parent class to inherit from.

Returns nothing.

Object Oriented

Object:__call(...)

Call the object's constructor.

Example
class 'Enemy'

function Enemy:new(x, y)
  self.x, self.y = x, y
end

e = Enemy(100, 200)

Arguments

Name Type Description
... N/A The arguments to pass to the constructor.

Returns table.

Object Oriented

Object:is(T)

Check if this object has the given metatable.

Example
class 'Car'
class 'Animal'
class('Cat', Animal)

local cat = Cat()

assert(cat:is(Animal))
assert(cat:is(Cat))
assert(not cat:is(Car))

Arguments

Name Type Description
T table The metatable.

Returns boolean.


Utility Functions

require(name)

Loads a Lua module. This is not the same function in standard Lua. It ignores package.searchers, and it uses the virtual file system, searching for files relative to the root of the project directory or zip archive.

When searching for files, path separators are . instead of /, and the .lua extension is excluded, similar to the standard version of this function.

Example
local lume = require 'deps.lume'

function spry.start()
  print(lume.serialize({ one = 1, arr = { 1, 2, 3 } }))
end

Arguments

Name Type Description
name string The module to load.

Returns any.

Utility Functions

unsafe_require(name)

This is the require function from standard Lua, renamed because it bypasses the virtual file system. This function can be used to load files in the LUA_PATH environment variable, for debugging purposes.

Example
if os.getenv 'LOCAL_LUA_DEBUGGER_VSCODE' == '1' then
  unsafe_require 'lldebugger'.start()
end

Arguments

Name Type Description
name string The module to load.

Returns any.

Utility Functions

stringify(value)

Get a string representation of a value, table fields included (unlike tostring).

Example
print(stringify(value))

Arguments

Name Type Description
value any A value to convert to a string.

Returns string.

Utility Functions

clamp(n, min, max)

Clamp a number to the range [min, max].

Example
local speed = clamp(speed, 1, 10)

Arguments

Name Type Description
n number The number to clamp.
min number The min number in the range.
max number The max number in the range.

Returns number.

Utility Functions

sign(x)

Get the sign of a number. Returns -1, 1, or 0.

Example
local dir_x = sign(dst_x - src_x)

Arguments

Name Type Description
x number The number to get the sign of.

Returns number.

Utility Functions

lerp(src, dest, t)

Linearly interpolate between two numbers.

Example
x = lerp(x, other_x, dt)

Arguments

Name Type Description
src number The value at t = 0.
dest number The value at t = 1.
t number The interpolation amount.

Returns number.

Utility Functions

direction(x0, y0, x1, y1)

Direction from (x0, y0) to (x1, y1) in radians.

Example
local angle = direction(self.x, self.y, x, y)

Arguments

Name Type Description
x0 number The source x component.
y0 number The source y component.
x1 number The destination x component.
y1 number The destination y component.

Returns number.

Utility Functions

heading(angle, mag)

Return x and y coordinates for a heading vector described by an angle and magnitude.

Example
local move_x, move_y = heading(angle_to_mouse, speed)

Arguments

Name Type Description
angle number The angle of the vector.
mag number The magnitude of the vector.

Returns number, number.

Utility Functions

delta_angle(src, dst)

Get angle difference between two angles in the range [-pi, pi).

Example
local angle = delta_angle(self.angle, angle_to_mouse)

Arguments

Name Type Description
src number The source angle in radians.
dst number The destination angle in radians.

Returns number.

Utility Functions

distance(x0, y0, x1, y1)

Get distance between two points.

Example
local length = distance(self.x, self.y, x, y)

Arguments

Name Type Description
x0 number The source x component.
y0 number The source y component.
x1 number The destination x component.
y1 number The destination y component.

Returns number.

Utility Functions

normalize(x, y)

Get a point representing a 2D vector with length of 1, or (0, 0) if length of (x, y) is 0.

Example
x, y = normalize(x, y)

Arguments

Name Type Description
x number The point's x component.
y number The point's y component.

Returns number, number.

Utility Functions

dot(x0, y0, x1, y1)

Get the dot product of two vectors.

Example
local dp = dot(vel_x, vel_y, other_x, other_y)

Arguments

Name Type Description
x0 number The x component of a vector.
y0 number The y component of a vector.
x1 number The x component of another vector.
y1 number The y component of another vector.

Returns number.

Utility Functions

random(min, max)

Get a random number in the range [min, max). Equivalent to math.random() if min = 0 and max = 1.

Example
local r = random(1, 100)

Arguments

Name Type Description
min number The smallest number than can be generated.
max number The largest number than can be generated.

Returns number.

Utility Functions

aabb_overlap(ax0, ay0, ax1, ay1, bx0, by0, bx1, by1)

Checks if an AABB overlaps another AABB. An AABB is defined by its top, left, bottom, and right edges.

Example
local overlap = aabb_overlap(
  left.x0, left.y0, left.x1, left.y1,
  right.x0, right.y0, right.x1, right.y1
)

Arguments

Name Type Default Description
ax0 number First box's left position.
ay0 number First box's top position.
ax1 number First box's right position.
ay1 number First box's bottom position.
bx0 number Second box's left position.
by0 number Second box's top position.
bx1 number bx0 Second box's right position.
by1 number by0 Second box's bottom position.

Returns boolean.

Utility Functions

rect_overlap(ax, ay, aw, ah, bx, by, bw, bh)

Checks if a rectangle overlaps another rectangle. A rectangle is defined by its top left point, width, and height.

Example
local overlap = rect_overlap(b.x, b.y, b.w, b.h, spry.mouse_pos())
local button_click = overlap and spry.mouse_click(0)

Arguments

Name Type Default Description
ax number First rectangle's x position.
ay number First rectangle's y position.
aw number First rectangle's width.
ah number First rectangle's height.
bx number Second rectangle's x position.
by number Second rectangle's y position.
bw number 0 Second rectangle's width.
bh number 0 Second rectangle's height.

Returns boolean.

Utility Functions

clone(t)

Creates a new shallow copy of a table.

Example
local bullets_copy = clone(bullets)

Arguments

Name Type Description
t table The table to clone.

Returns table.

Utility Functions

push(arr, x)

Add a value to the end of a table.

Example
push(bullets, bullet)

Arguments

Name Type Description
arr table The table to push a value to.
x any The value to push.

Returns nothing.

Utility Functions

map(arr, fn)

Create a new table with the result of calling a function on each item.

Example
local nums = {1, 2, 3, 4, 5}
local doubled = map(nums, function(n) return n * 2 end)

Arguments

Name Type Description
arr table The array to apply a callback function to.
fn any The callback function.

Returns table.

Utility Functions

filter(arr, fn)

Create a new table with items that pass the given function.

Example
local nums = {1, 2, 3, 4, 5}
local odd_nums = filter(nums, function(n) return n % 2 == 1 end)

Arguments

Name Type Description
arr table The array to filter items with.
fn any The predicate function.

Returns table.

Utility Functions

zip(lhs, rhs)

Return a table where each element is a pair of items from two other tables. If table lengths differ, the shortest table's length is used.

Example
local nums = zip({1, 2, 3}, {'one', 'two', 'three'})
-- nums == {{1, 'one'}, {2, 'two'}, {3, 'three'}}

Arguments

Name Type Description
lhs table The first array.
rhs table The second array.

Returns table.

Utility Functions

choose(arr)

Choose a random value in an array.

Example
card = choose(cards)

Arguments

Name Type Description
arr table The array to pick from.

Returns any.

Utility Functions

find(arr, x)

Find the key in an array associated with the given value. Returns nil if value wasn't found.

Example
local index = find(cards, 'queen:hearts')
if index ~= nil then
  print('Queen of Hearts at index ' .. index)
end

Arguments

Name Type Description
arr table The array to search.
x any The value to search for.

Returns any.

Utility Functions

sortpairs(t)

Returns an iterator over a table sorted by key.

Example
local t = {
  c = 'third',
  b = 'second',
  a = 'first',
}

for k, v in sortpairs(t) do
  print(v)
end

-- first
-- second
-- third

Arguments

Name Type Description
t table The table to iterate.

Returns iterator.

Utility Functions

create_thread(fn)

Creates a coroutine.

Example
local update_thread = create_thread(co_update)

Arguments

Name Type Description
fn function The function to create the coroutine with.

Returns thread.

Utility Functions

resume(co, ...)

Runs a coroutine, raising an error if the coroutine ran with an error.

Example
resume(thread, self, dt)

Arguments

Name Type Description
co thread The coroutine to resume.
... N/A Arguments to pass to the coroutine.

Returns nothing.

Utility Functions

yield(...)

Suspend a coroutine. Similar to coroutine.yield(...) but it ignores the first return value. This is useful when the first argument passed to the coroutine doesn't change (for example, when passing self).

Example
function Enemy:new()
  self.thread = create_thread(self.wander)
end

function Enemy:wander(dt)
  while true do
    -- stuff
    dt = yield()
  end
end

function Enemy:update(dt)
  resume(self.thread, self, dt)
end

Arguments

Name Type Description
... N/A Arguments to pass to whoever resumed the coroutine.

Returns any.

Utility Functions

sleep(secs)

Pause a coroutine for given number of seconds. Returns the next delta time.

Example
function Camera:begin_cutscene()
  -- call cutscene_thread
  resume(self.thread, self)
end

function Camera:cutscene_thread()
  self:move_to(door.x, door.y)
  door:open()
  sleep(3)
  self:move_to(player.x, player.y)
end

Arguments

Name Type Description
secs number The number of seconds to sleep for.

Returns number.