Writing a Script
A script is a text file of Lua 5.4
in your autoscript/custom/ folder. This page walks through one
from the first line; the Function
Reference lists everything a script can call.
Your first script
Create a file called hello.lua in
autoscript/custom/ inside your game folder, with this in
it:
script {
name = "Hello",
description = "Says where you are and lists your pets.",
}
function main(cfg)
local m = me()
log("I am " .. m.name .. ", level " .. m.level
.. ", on " .. mapName(m.map) .. ".")
for _, p in ipairs(pets()) do
local tag = p.marching and " (marching)" or ""
log(p.name .. ", level " .. p.level .. tag)
end
endIn the game, open Action → Script, press
Reload, pick Hello and press Start.
Each log line appears in chat as
[Hello] I am ….
Every script has the same two parts:
- The header,
script { ... }: the name and description the Script window shows, and the script's settings. - The
main(cfg)function, where the work happens. It runs once; when it returns, the script has finished.
File names may use only letters, digits and underscores,
and must end in .lua. A file called
my-script.lua or my script.lua is not listed at
all.
Do the work inside main. The game reads the
top of every file to build the script list, and the game functions are not
available then. A script that calls one outside a function shows as
(broken).
Settings
Each entry in settings becomes a row in the Script window, and
the value the player chose arrives in cfg under its
key:
script {
name = "Example",
description = "Shows the four kinds of setting.",
settings = {
{ key = "runs", label = "How many times",
type = "int", default = 5, min = 1, max = 100 },
{ key = "heal", label = "Heal between",
type = "bool", default = true },
{ key = "who", label = "Leader's name",
type = "text", default = "" },
{ key = "chest", label = "Which chest",
type = "choice", default = "Middle",
choices = { "Left", "Middle", "Right" } },
},
}
function main(cfg)
log("runs = " .. cfg.runs .. ", chest = " .. cfg.chest)
if cfg.heal then log("will heal") end
end| Type | Shown as | Arrives as |
|---|---|---|
int | A number field | A whole number. With min and max set, it
is held between them. |
bool | A tick box | true or
false |
text | A text field | A string |
choice | A drop-down of choices |
The chosen string — always one of the choices |
A key may use letters, digits and underscores. The Script window has room for ten settings.
How a script waits
Many functions take time: walking somewhere, talking to an NPC, a fight. When your script calls one, the script pauses on that line until the game has the answer, then carries on with the result. The game itself keeps running smoothly the whole time, so you can write plain step-by-step code with no callbacks.
These functions return what they produced when they succeed, and
false plus a reason when they do not:
local ok, why = travel(100001) -- Water City
if not ok then
log("could not get there: " .. why)
endMost of the time a failure means the script cannot sensibly go on, and
expect says exactly that in one line. It passes the results
through when the call worked, and stops the script with the reason when it
did not:
expect(travel(100001)) -- stops with the reason
local d = expect(talk(96)) -- d is the dialogue
expect(itemCount("DiamondSutra") > 0,
"the Sage did not hand over the sutra")
Talking to NPCs
talk(npc) takes the id or the name of an NPC on your map,
walks closer if it is far away, and clicks it. It returns the dialogue that opened: what the NPC
said in text, and the answers on offer in
options.
answer(choice) picks one of those answers, by its text or by
its number in the list (1 is the first). Text is matched exactly first, then
ignoring capitals, then as part of an answer — so
answer("retire") works when only one answer mentions retiring.
If nothing matches, or more than one answer does, it fails and the reason
lists the answers that were on offer.
answer returns a table describing everything that happened
next. Several things can happen at once — a new dialogue and a fight,
say — so check each one you care about:
| Field | Set when |
|---|---|
dialogue | The NPC said more. Holds the new dialogue. |
battle | A fight started. |
map | You were moved to another map; holds its id. |
moved | You were moved on the same map. |
shop | A shop window opened. |
refused | The server turned the answer down. |
chat | Always present: the system lines that arrived meanwhile, as a list of strings. |
none | Nothing happened at all. |
expect(travel(100001)) -- Water City
local d = expect(talk(96)) -- the Sage
local r = expect(answer("I'm weary of it. I want to retire."))
if r.dialogue then
r = expect(answer("All right, thank you."))
endThe game's own common module has a shortcut for exactly this,
converse, which talks and gives a list of answers in order:
local common = import("common")
expect(common.converse(96, {
"I'm weary of it. I want to retire.",
"All right, thank you.",
}))
Closing a dialogue is not an answer.
closeDialogue() only takes the box off your screen; the NPC is
never told. That matters, because some NPCs treat the box's close button
as a reply: on the Sky Trial from floor 21, and with the Brothers' guards,
closing it throws you out. A script never sends that reply, so
closeDialogue() is always safe.
Fights
When an answer starts a fight, fight() waits for it to finish
and returns "won", "lost" or "fled",
followed by whatever the NPC said once it was over:
local r = expect(answer("Let's fight")) -- the challenge
if r.battle then
local result, after = fight()
if result ~= "won" then stop("lost the fight") end
if after then expect(answer("You flatter me.")) end
endThe fight itself is played by the script's battle plan.
It starts as your Battlemation settings, and battlePolicy
changes any part of it for the rest of the run:
battlePolicy{ player = "defend", pet = "attack", healPet = 60 }For ordinary fights against wild monsters, grind fights where
you stand until a goal is met, restocking medicine on its own the way
Battlemation does:
-- twenty fights
expect(grind{ battles = 20 })
-- catch one Cindyfly of level 3 or 4
expect(grind{ capture = {
name = "Cindyfly", level = 3, maxLevel = 4, count = 1,
} })
Waiting for something to happen
The functions you call just to wait take a time limit in milliseconds, and
return false, "timeout" when it runs out:
sleep(2000) -- two seconds
local d = waitDialogue(5000) -- the next dialogue
expect(waitMap(120000, 10000)) -- arriving on a map
-- the next system line that matches a Lua pattern
local line = waitChat("every grudge is wiped", 3000)These clocks stop while a fight is on, so a long fight never makes a wait run out.
Errors and stopping
stop("reason")ends the script with that message;stop()ends it quietly.- A mistake in the script — calling something that does not exist,
adding a number to
nil— stops it with the file and line number in chat, for example custom/hello.lua:7: attempt to concatenate a nil value. - Lua's
pcallworks, and waiting functions may be called inside it. It cannot catchstopor a failedexpect: those always end the script.
Scripts that pick up where they left off
A script can be stopped at any moment — by you, by a full pet list, by a lost connection. The library scripts are written so that starting them again simply carries on, and yours are easier to live with written the same way: before each step, check whether it is already done.
if itemCount("DiamondSutra") == 0 then
expect(common.converse(96, {
"I'm weary of it. I want to retire.",
"All right, thank you.",
}))
end
-- From here on, the sutra is in the bag either way.
Shared modules
import(name) loads one of the game's own helper modules. Two
ship with the game:
| Module | What it has |
|---|---|
common |
converse(npc, answers) — talk, then give each
answer in turn; findPet(test),
marchingPet(), rosterHasRoom();
topUp(percent) — heal you and every pet to that
share of their life with the life medicine in your bag;
logf(format, ...). |
passes |
The Sky Trial, Couples Pass and Friends Pass data the library scripts use: maps, guards, chests and the answers they expect. |
import reads only the game's own modules. To share code
between scripts of your own, copy it into each one.
Limits
Scripts run in a closed-off copy of Lua, so a script cannot harm your computer:
- No files, programs or internet. Lua's
io,os,require,coroutineanddebugare not there.string,table,mathandutf8are.loadaccepts Lua source text only. - Loops must wait. A script that runs for about twenty
million steps without calling a waiting function is stopped with
“the script ran too long without waiting”. A loop
that checks for something over and over needs a
sleep()in it. - 64 MB of memory per script, far more than any real script uses.
- A few places cannot wait: inside a
table.sortcomparison, astring.gsubfunction, or the top level of an imported module. Calling a waiting function there is an error.
A complete example
This script raises your marching pet to a chosen level where you stand,
healing everyone between batches of fights and letting the pet take the
kills. Save it as autoscript/custom/raise_pet.lua.
script {
name = "Raise Pet",
description = "Fights until the marching pet reaches a level.",
settings = {
{ key = "level", label = "Stop at pet level",
type = "int", default = 100, min = 2, max = 1400 },
{ key = "batch", label = "Fights between heals",
type = "int", default = 10, min = 1, max = 100 },
{ key = "defend", label = "Let the pet take the kills",
type = "bool", default = true },
},
}
local common = import("common")
function main(cfg)
expect(common.marchingPet(), "march the pet to raise first")
if cfg.defend then
battlePolicy{ player = "defend", pet = "attack" }
end
while true do
local pet = expect(common.marchingPet(),
"the marching pet is gone")
if pet.level >= cfg.level then
log(pet.name .. " reached level " .. pet.level)
return
end
status(pet.name .. ": level " .. pet.level
.. " of " .. cfg.level)
common.topUp(90)
expect(grind{ battles = cfg.batch })
end
endThings worth noticing:
- It reads the pet afresh every time round the loop. A table from
pets()is a snapshot; it does not change when the pet levels. statussets the line shown in the Script window and by/script status;logwrites to chat.grindwaits, so the loop never runs too long without waiting.