Scripting basics

Script mods are written in Lua 5.4, a small language that is quick to learn. If you have never used it, the first chapters of Programming in Lua (lua.org/pil) cover all you need; this page covers how Lua meets the game.

How a script mod runs

  1. At start (and on every reload) the game runs each enabled mod's main.lua once, in load order.
  2. That first run sets things up: it registers event handlers (on(...)), key binds, timers, mod menu panels, settings. It should not wait or loop; there is nothing to wait for yet.
  3. After every mod has loaded, the mods_loaded event fires.
  4. From then on the game calls your handlers when things happen: every frame, when a hunt starts, when a dinosaur is shot, when a key is pressed, when the screen is drawn.
-- main.lua runs once: register what you need
on("hunt_start", function() print("hunt!") end)
timer.every(30, function() print("half a minute passed") end)
keys.bind("F5", function() world.killAll() end)

Events

on(name, handler) calls handler(e) whenever the event happens. e is a table describing it:

on("hit", function(e)
  print(e.creature.name, "took", e.damage, "damage from weapon", e.weapon)
end)

Some fields are writable: the game reads them back after the handlers ran. Some events are cancellable: e.cancelled = true stops what they announce.

on("hit", function(e)
  e.damage = e.damage * 2           -- double damage
end)

on("player_death", function(e)
  if e.cause == "environment" then
    e.cancelled = true              -- no drowning
  end
end)

Every event, with its fields, is on the Events page. Mods can invent their own events with events.emit and listen with the same on, which is the way mods talk to each other.

Creatures

Every creature in a hunt is a Creature handle: e.creature in events, the result of world.spawn, world.nearest, world.creatures. Read and write its fields like a table:

local rex = world.nearest("trex")
if rex then
  print(rex.name, rex.health, rex.x, rex.z)
  rex.scale = 2          -- twice as big
  rex.health = 3000      -- and much tougher
  rex.team = 1           -- for creature fights
end

A handle stays the same object for the same creature, so it works as a table key, and c.data is a table for your own notes about it. When a creature is removed, or a new hunt begins, its handle goes stale: c.valid becomes false and using it raises an error. Keep creatures you track in a table and check valid:

local tracked = {}
on("spawn", function(e) tracked[#tracked + 1] = e.creature end)
on("frame", function()
  for i = #tracked, 1, -1 do
    if not tracked[i].valid then table.remove(tracked, i) end
  end
end)

c.id is a number that identifies the creature for as long as it exists; world.byId(id) finds it again. Use it to save references or send them over the network.

Taking over a creature's AI

The Creature behaviour page goes much further: brains (c.brain) that replace a species' AI while the game keeps everything around it, the game's own walking, senses and attacks as creature methods, and Ice Age's AI toolkit. The simplest takeover is this one:

Set c.ai = false and the game's AI stops running for it; your script moves (c:move, c.x, c.yaw) and animates it (c.anim, c:animate). For a frame-by-frame decision use the creature_ai event and cancel it for the creatures you drive.

-- a T-Rex that slowly walks to the hunter, whatever happens
local rex = world.spawnNear("trex", 4000)
rex.ai = false
rex.anim = rex:findAnim("walk") or 0
on("frame", function(e)
  if not rex.valid or not rex.alive then return end
  local x, _, z = player.pos()
  rex.yaw = math.yaw(rex.x, rex.z, x, z)
  if rex:distanceTo(x, z) > 600 then rex:move(400 * e.dt) end
  rex:animate(e.dt)
end)

Coordinates, distances, angles

Time

draw.* paints text and shapes over the game; ui.* makes windows with buttons, sliders, tables and tabs (Dear ImGui). Both work inside the draw event; ui.panel adds a tab to the mod menu (F1), the best place for a mod's options. mod.setting makes a setting with an automatic widget in the mod menu's Settings tab and saves it.

mod.setting("labels", true, {label = "Show creature labels"})

on("draw", function()
  if not (game.inHunt() and mod.settings.labels) then return end
  for _, c in ipairs(world.creatures({radius = 6000})) do
    local sx, sy = c:screen()
    if sx then
      draw.text(sx, sy - 22, c.name, "white", 18, "center")
      draw.bar(sx - 35, sy - 4, 70, 6, c.health / c.maxHealth, "red")
    end
  end
end)

The game's own HUD

The game's HUD — the MENU tab, the health bar, the ammo count, the compass, the trophy window and the rest — is yours to change too. hud hides, moves and resizes its parts, so a mod can replace one with its own drawing, and Esc comes to the mods first as the back event:

-- no MENU tab (Esc opens the menu, and closes it again) and an ammo counter of our own
hud.hide("menu", "ammo")

on("draw", function(e)
  local total, loaded = player.ammo()
  if game.inHunt() and total then
    draw.text(e.width - 30, e.height - 50, loaded .. " / " .. total, "#ffd040", 26, "right")
  end
end)

-- a bigger compass, a little higher
hud.scale("compass", 1.6)
hud.offset("compass", 0, -40)

Hidden parts come back with hud.show, hud.reset or a reload (F9). Clean HUD is a complete example.

The game's menus

The menus are open to mods as well, in the game's own style: menu adds buttons of the game's kind to the main menu, MORE, the hunt menu's pages and the hunt's menu, hides or moves the game's buttons, and opens whole pages drawn with the game's backgrounds, fonts and buttons; menu_action hears a menu button before the game does, and the gui event draws with the game's sprites and fonts (draw.sprite). Menus and pages is the guide:

local page = menu.page("mymod:about", {title = "My mod"})
page:text("Made for the hunters of the PC port.", {width = 300})
menu.button("main", "MY MOD", function() page:open() end)

Phones: touch buttons

The Android edition plays with the original touch controls: no keyboard, so a key your mod binds cannot be pressed there. Give it an on-screen button: keys.bind's touch option makes one that presses the key, or touch.button makes one with a key, a function, or both. On the PC nothing changes (the buttons never show there, the key works as before).

keys.bind("B", function()
  if game.inHunt() then spawnBoss() end
end, {touch = {label = "BOSS"}})                      -- B on a PC, a BOSS button on a phone

touch.button({label = "FLARE", x = -100, y = -260, size = 80, onTap = fireFlare})   -- a phone only

Buttons are placed in mod pixels (x / y below 0: from the right / bottom edge) and show in a hunt while nothing covers the 3D view (when = "menus" or "always" for elsewhere). The finger on a button never reaches the game. Other phone notes: Back is the game's back key (the back event), the mod menu and the console are tabs of the MODS screen, and game.platform() is "android". touch.available() tells whether buttons show.

Sharing between mods

The sandbox

Each mod has its own globals; the API tables are copies. Mods cannot touch the computer outside the game: no io, no os.execute, no loading of binary code. Files come from your own mod folder (mod.read), data goes to your save file (mod.save). Endless loops are stopped after 3 seconds with an error instead of freezing the game.

Performance

Both games

The PC port runs Carnivores: Dinosaur Hunter HD and Carnivores: Ice Age, each its own copy of the game; a script mod runs in the games its mod.json lists in "games" (Games). The API is the same in both: every function, event and field. What differs is the game's content, and a mod made for both games picks it with game.id() ("dinohunter" or "iceage"):

Per game Dinosaur Hunter Ice Age
species ids and type numbers (world.spawn, c.species, content packs) dinosaurs: trex 24, velociraptor 21 ... animals: mammoth 123, wolf 118 ...
animation numbers (c.anim, c:findAnim finds nothing by name in either game's files) per species walk 0, run 1, then idles, attack, lunge
maps (game.area()) 0-6 0-4
texts (game.text, game.setText) strings.csv keys strings_ia.csv first, then strings.csv
content registry built-ins, menu entries of content packs yes yes (each game's own built-ins; Content packs)
save folder (mod data, settings) carnivores carnivores-iceage

The species tables with their animations are on the world page.

-- one mod, both games
local PREY = { dinohunter = "parasaurolophus", iceage = "deer" }
keys.bind("F6", function() world.spawnNear(PREY[game.id()], 3000) end)

API versions

The modding API grows over time; nothing is ever removed or changed in a way that breaks a working mod. Every release that adds to it raises game.apiVersion() by one, and the reference marks what came later with since API N. A mod that needs newer functions puts "api": N into its mod.json: older games then show it as failed with the reason ("needs API version N") instead of running into missing functions. Inside a mod you can also check at run time:

if game.apiVersion() >= 2 then
  -- use something newer
end
API Release Added
1 2.0.1 the first API
2 2.1.0 game.id(), the games field of mods.list() entries
3 2.2.0 (PC and the Android edition) every value of the game's objects: creature and species fields, weapons and slots, the hunter, equipment, weather, wind, the hunt, the profile, the raw layer (Game data); creature behaviour: brains, the game's creature functions, ai.*, the behaviour events (Creature behaviour); zones, populations, herds and packs (zone.*, population.*, group.*, World); menu.*, draw.sprite, the gui event and the menu events (Menus and pages); equipment and Ice Age hunt-menu entries in content packs, per-game content folders (Content packs); touch.* (on-screen buttons on a phone), keys.bind's options table (touch, priority)
4 2.3.0 the picture: shader.world, shader.screen, shader.targets, shader.post, shader.setSource (Shaders); weather: weather.* (rain, thunderstorms, snow, cover, presets that fade), the lightning event, world.weather.snow in Dinosaur Hunter (Weather)

Reloading

F9 (or Reload scripts in the mod menu, or reload() in the console) unloads every script mod and runs them again: handlers, timers, windows and panels are dropped, unload fires first so mods can save. The game world stays as it is; creatures your mod spawned are still there (find them again with world.creatures). What the scripts switched on goes back to the game's own: API 3's definition changes (the journal), and the world switches world.god, world.invisible, world.frozen, world.fights, a possession and camera.follow (the hunter stays where the follow camera took him). The same happens when a mod is switched off in the Mods screen and when the game quits.