Docs Quick code
Libraries, data tables and object values
Sharing functions across a script and across the game, keeping game data in tables, and objects' starting values.
#Functions shared by a script
A function written at the top of one Code node can be called from every other Code node of the same script (on the same object). A good habit: one Code node at the side of the graph, not connected to anything, holding the script's helper functions.
#Libraries: functions for the whole game
Make a script (Scripts tab) — say Utils — and put functions in its Code nodes:
-- In the script "Utils":
function clamp_hp(n)
return clamp(n, 0, 100)
end
function greet(name)
popup("Welcome, " .. name .. "!")
end
Any code can then use it:
local u = require("Utils")
u.greet("Mira")
local hp = u.clamp_hp(140) -- 100
requirefinds the script by its name or id.- Its Code nodes run once, all at once (no waiting), the first time it's required in a level;
later
requires give the same table. - It gives the table the library
returns, if it returns one — otherwise a table of the functions it defines. - Libraries can
requireother libraries (not in a circle).
Returning a table makes a tidy module with its own settings:
-- In the script "Combat":
local M = {crit_chance = 15}
function M.damage(base)
if chance(M.crit_chance) then return base * 2 end
return base
end
return M
#Data tables
The Data tab holds spreadsheet-like tables of game data — enemy stats, loot drops, shop prices, lines of text — so numbers live in one place instead of inside code. Each row's first column is its key; cells are numbers, text or true / false (typed as they look).
| name | hp | speed | loot |
|---|---|---|---|
| Goblin | 10 | 2.5 | Coin |
| Troll | 40 | 1 | Gem |
local enemies = data("Enemies")
local g = enemies["Goblin"]
self.hp = g.hp -- 10
for name, row in data("Enemies") do
print(name .. ": " .. row.hp .. " hp")
end
data(name) gives nil when there's no table with that name (or id). Data tables are part of
the project, so they're in exported games too.
#Objects' starting values
Select an object, then Properties ▸ Values for code — one per line:
hp = 10
loot = ["Coin", "Gem"]
angry = false
Code reads them as the object's own values (self.hp, object("name").loot) and can change
them while the game runs; the changes are saved with the game. Two copies of the same model can
start differently. See Objects.