Build a mod

Events and timers

Run your code when something happens in the game, after a delay, or over and over.

Advertisement

Almost every mod is a list of reactions. When the game ticks, update something. When a key is pressed, do something. When a chat message comes in, maybe hide it. These moments are called events.

Listen for an event

Call on with the event's name and a function. The game calls your function every time the event happens.

on("world_join", function(e)
  chat.print("Welcome back, " .. player.name())
end)

on is short for events.on. Both do the same thing.

Register your events at the top level of main.lua. That code runs once when your mod loads, so every listener is set up right away.

Stop listening

on gives you back a handle. Call remove on it when you are done listening.

local handle = on("tick", function()
  chat.print("tick")
end)

timer.after(1, function()
  handle:remove()
end)

events.off(handle) does the same thing.

If you only care about the next time an event happens, use events.once. It removes itself before it runs.

events.once("world_join", function(e)
  chat.print("This only shows the first time you join a world")
end)

Priority

When your mod listens to the same event more than once, the listener with the higher priority runs first. Pass the priority as the third argument. It has to be a whole number, and the default is 0.

on("chat_receive", function(e) end, 10)

Priority only sorts your own listeners. Between mods, the order of the Mods list decides who hears an event first.

Cancel an event

Some events can be cancelled. Cancelling stops the game from doing the normal thing, like showing a chat message or reacting to a key. Call e:cancel(), with a colon.

on("chat_receive", function(e)
  if e.message:find("spam") then
    e:cancel()
  end
end)

That hides every chat message with the word "spam" in it. Once one listener cancels an event, no other listener hears it, in your mod or any other. The list of events below says which events you can cancel.

Change an event

A few events let you change what happens instead of cancelling it. For chat, you can assign a new message.

on("chat_send", function(e)
  e.message = e.message:gsub("brb", "be right back")
end)

Your own events

Mods can send their own events with events.emit. Every mod hears them, including yours, so this is an easy way for two mods to work together. Put your mod's id at the front of the name so it never clashes with someone else's.

events.emit("coolhud:ready", 123)
on("coolhud:ready", function(value)
  chat.print("Cool HUD is ready: " .. value)
end)

events.emit runs every listener right away, before it returns. Custom events cannot be cancelled.

All events

Some events hand you a table, called e here, with named fields. Others hand you values directly.

EventWhat you getNotes
ticknothing20 times a second, even on the title screen and in menus
framedt, the seconds since the last frameevery rendered frame
resizewidth, heightthe window changed size, in GUI pixels
hudctx, partialTickdraw on the HUD (see The HUD)
screen_renderscreen, ctx, mouseX, mouseY, deltaafter any screen draws
overlayctxon top of all 2D drawing, every frame
render_worldviewraw WebGL in the world (see WebGL)
render_overlayviewraw WebGL over the finished frame
keye.key, e.code, e.action, e.shift, e.ctrl, e.alt, e.screencan be cancelled
chare.char, e.codepointa typed character. Can be cancelled
mouse_clicke.button, e.action, e.x, e.y, e.screencan be cancelled
mouse_scrolle.dx, e.dy, e.screencan be cancelled
chat_receivee.messagecancel to hide it, or assign a new e.message
chat_sende.message, e.commandcancel to block it, or assign a new e.message
screen_opene.screen, e.titlecancel to stop the screen from opening
screen_initscreenadd or change buttons (see Screens and menus)
screen_closescreen
world_joine.singleplayer, e.serveryou joined a world
world_leavenothingyou left a world
setting_changedkey, value, oldone of your own settings changed
mod_loadedida mod finished loading, even if it failed
mod_unloadedida mod was turned off, reloaded, updated or deleted
unloadnothingyour mod is about to unload, so save anything you need

A few details that are easy to miss:

  • e.action is "press", "release" or "repeat" for keys, and "press" or "release" for the mouse.
  • e.button is "left", "right" or "middle".
  • e.screen is the id of the open screen, like "inventory", or nil while you are playing.
  • chat_receive fires for every chat line, including the ones mods print with chat.print. If you print from inside chat_receive, check the message first or you will keep printing forever.
  • chat_send fires for what the player types in chat. It does not fire for mod commands or for chat.send.
  • e.message in chat_receive is plain text. Colors and formatting are gone, and a message you assign shows up as plain text too (§ color codes still work).
  • world_join does not fire if your mod loads while you are already in a world. See How mods run.

Run code later

timer.after runs a function once, after a number of seconds.

timer.after(2, function()
  chat.print("Two seconds later")
end)

timer.every runs a function over and over. Both give you back a timer you can cancel.

local t = timer.every(0.5, function()
  chat.print("Every half second")
end)

timer.after(5, function()
  t:cancel()
end)

Timers are checked once per frame, so they fire on the first frame after their time is up. t.active tells you whether a timer is still going.

Two more helpers tell you about time. timer.time() is the current time in seconds (the same clock as os.time, but with milliseconds), which is good for measuring how long something took. timer.ticks() is the number of game ticks since the game started.

Wait in the middle of your code

Sometimes you want to do one thing, wait, and then do the next thing. Wrap that code in async, and use wait inside it.

async(function()
  chat.print("3...")
  wait(1)
  chat.print("2...")
  wait(1)
  chat.print("1...")
  wait(1)
  chat.print("Go!")
end)

wait(seconds) pauses for that many seconds and waitTicks(n) pauses for n game ticks. The rest of the game keeps running while your code waits. wait only works inside async.

async and wait are Lua only. In a WebAssembly mod, use timer.after instead.