This is the abridged developer documentation for KCD Multiplayer (KCD:MP) scripting reference # Getting started > What a KCD:MP server, a game mode and a client script are, which languages write them, and the order to read this documentation in. A KCD:MP **server** is one program that the players' games connect to. It runs one **game mode** - the rules of that server: where players spawn, what the chat and the commands do, who may hurt whom, what stands in the world. A game mode is a script or a plugin you write; the server calls it when something happens (a player joins, dies, types a command) and the script calls the server back (send a message, move a player, spawn a horse). A mode may also have a **client script**: its own half that runs inside each player's game, for the things only the player's screen can show. | Piece | What it is | Written in | |---|---|---| | **The server** | the dedicated server program, a folder you run on Windows or Linux: `server.toml`, the game modes, the data it keeps | - | | **A game mode** | the rules of one server; one per server, reloaded without a restart | [Lua](/lua/server/) or [C#](/csharp/) | | **A client script** | the mode's half on the player's game: a marker, a sound, a bit of UI, a value read from the game; sent to the players by the server | [Lua](/lua/client/) | | **The world data** | the level's tables, terrain, navigation mesh and collision geometry, exported from your own copy of the game | - | The server works out of the box: the two modes that ship with it, `freeroam.lua` and `duel_arena.lua`, are complete servers, and a mode that defines nothing is a valid mode - the server spawns everyone at its default point and answers its own chat commands. Everything on these pages is what you add. ## The pages, in order 1. [Setting up](/getting-started/setting-up/) - the server folder, the first run, joining it, picking a mode, giving the server the game's data, your editor. Step by step, whatever language you script in. 2. [AI assistants](/getting-started/ai-assistants/) - this documentation as plain text and as language-server definitions, and a `CLAUDE.md` that starts a game-mode project with a coding agent. 3. [Server configuration](/getting-started/server-config/) - every key of `server.toml`, with its default. 4. [Guides](/guides/) - one job per page: exporting the game's tables, the terrain, the navigation mesh and the collision geometry from your game; putting a server on the public list. 5. The API for your language: [Lua](/lua/) (the server and the client side, every callback and function on its own page) or [C#](/csharp/) (the same server API as typed interfaces). 6. [The reference](/reference/) - the game's lists: every item, soul, buff, mesh, preset, animation clip, door and container, by the keys the functions take. ## Conventions The same everywhere, whatever the language: - **metres** in the level's world space, as the game's own console reports positions; `z` below `0` when spawning or teleporting means "on the terrain"; - **degrees** for a yaw, `0` = facing +Y, counter-clockwise; - **`0xRRGGBBAA`** colours - `0xFF0000FF` is opaque red; - **milliseconds** for times and timers; the world clock in hours (`13.5` = 13:30); - a **player** is a `pid` (`0` to the slot count minus one, reused after a disconnect); a **world entity** - a horse, a pickup, a prop, an NPC actor, a dog - is an `id`, unique while it lives; - the **keys of game things** - items, souls, buffs, meshes - are an id, a name or a GUID from [the reference](/reference/); a call given an unknown key fails quietly (`nil`, `false`) and the server log says why. # Setting up > Step by step from the server folder to a running server with your own game mode - the first run, joining it, picking and writing a mode, the game's data, admins, and an editor that knows the API. Everything on this page holds whatever language you script in; the language pages start where this one ends. ## 1. What you need - **The game** - Kingdom Come: Deliverance II on Steam, the build the current KCD:MP release was made for (the release notes say which). The server itself does not need the game, but the [world data](#5-give-the-server-the-games-data) it wants is exported from a copy of it. - **The KCD:MP client** - the launcher and the client, from the download page at [kcd-mp.com](https://kcd-mp.com/download), on every machine that plays. The launcher starts the game with KCD:MP inside it and connects it to a server. Unpack it anywhere once; from then on the launcher tells you when a newer release is out and updates itself on your say-so. - **The server folder** - the dedicated server, from the same [download page](https://kcd-mp.com/download) under *Host your own*: one archive with a `windows/` and a `linux/` folder inside; unpack it and take the folder for your system. It is a .NET 10 program: the machine that runs it installs the .NET 10 runtime once. A server needs one UDP port (7777 by default). ## 2. The server folder The folder is the same on both systems: ``` KcdMp.Server (.exe) the server server.toml every setting, every key documented; the server reads it from the folder it runs in gamemodes/ the game modes: freeroam.lua, duel_arena.lua, the marker example (a mode with a client half) and a README sdk/ what your editor and a C# project use: KcdMp.Api.dll + .xml, KcdMp.d.lua, KcdMp-client.d.lua data/ what the server keeps (the player records) and reads (the game's tables, the world data) - with a README tools/ Windows only: the exporters that make the game's data from your own copy of the game ``` `server.toml` is read from the working directory (or `--config `); every key is optional and [Server configuration](/getting-started/server-config/) lists them all with their defaults. A command-line flag overrides the file (`--max-players 64` beats `[server] max_players`). ## 3. The first run Run the server in its folder - `KcdMp.Server.exe` on Windows, `./KcdMp.Server` on Linux - and read its first lines: the version and the protocol number, the tick rate, which game mode it loaded, and one line per data file it found or could not use (`combat tables: ...`, `heightmap: ...`, `navmesh: ...`, `collision: ...`). A missing file turns one thing off and nothing else; the server runs without any of them. `Ctrl+C` stops it; `--version` prints the version and exits. Two settings are worth a look before anyone else joins: ```toml [server] name = "KCD:MP dev server" # what the players see in the launcher password = "" # "" = anyone may join [master] url = "https://kcd-mp.com/server-list" # the public list; "" = announce nowhere, a private server ``` A server announces itself to the public list by default, so a test server is best made private (`url = ""`) or passworded until it is meant to be found. [Putting a server on the list](/guides/public-server/) has the rest - the port, the address the list should show, what players see. ## 4. Join it Open the launcher with Steam running, type the name the other players will see, and connect: **Servers** lists the public list, **Direct connect** takes an address - `127.0.0.1:7777` for a server on the same machine, the machine's address on a LAN. The launcher asks the server for its level and boots the game onto it; the first load takes a little longer than usual. In the game, **T** opens the chat, **Tab** the scoreboard, **Esc** the menu; `/help` in the chat lists the commands the server answers. ## 5. Give the server the game's data The server does not have the game. Four files, each made once from your own copy of it with the tools in `tools/` (Windows - the machine the game is installed on) and put under `data/`, give it what it lacks; a server on Linux gets the files copied over. Each is one job, one guide: | File | What it turns on | Guide | |---|---|---| | `data/combat/items.json` | damage from the game's own weapon and armour tables; items, souls, buffs and meshes by **name** (`/give shortswordBroad`, a horse breed by name, a potion the server owns); the reference lists as the server resolves them | [Exporting the game's tables](/guides/game-tables/) | | `data/heightmaps/.hmap` | the terrain check - a player far under or over the ground is pulled back - and the terrain height for a game mode | [Exporting the terrain](/guides/terrain/) | | `data/navmesh/.knav` | NPC actors that walk around walls instead of into them; paths and reachability for a game mode | [Exporting the navigation mesh](/guides/navigation/) | | `data/collision/.kcol` | line of sight on hits and shots, the floor under a player as the ground, rays for a game mode | [Exporting the collision geometry](/guides/collision/) | Do the tables first: without them the server knows items, souls and buffs by their GUIDs only and takes the damage the players' games report. The other three are per level and can wait until the server needs them. ## 6. Pick a game mode `[gamemode] script` names it; the command line (`--gamemode gamemodes/duel_arena.lua`) wins over the file: ```toml [gamemode] script = "gamemodes/freeroam.lua" # everyone in one world around the spawn, global chat, parties, the NPC actor demo # script = "gamemodes/duel_arena.lua" # /duel queues you; two at a time fight in the arena, nobody else can be hurt # script = "gamemodes/marker/marker.lua" # the example with a client half: a checkpoint run drawn in each player's game # script = "gamemodes/arena/Arena.dll" # a C# plugin, in a folder of its own # script = "" # the built-in freeroam watch = false # true: a changed script is reloaded by itself (a development server) ``` A mode is reloaded without a restart by `/reload` in the chat (admins), by the mode itself, or by `watch = true` whenever its file changes on disk. ## 7. Write your own - **In Lua**: a file next to the shipped modes, named in `server.toml`. [Getting started on the server](/lua/server/getting-started/) is the first script, the tick, ids and units and what happens on an error; the [Server API index](/lua/server/) has every callback and function. A mode that wants something on the players' screens adds a [client script](/lua/client/getting-started/) in a `client/` folder next to itself. - **In C#**: a class library compiled against `sdk/KcdMp.Api.dll`, published into a folder of its own under `gamemodes/`. [The C# server API](/csharp/server/) has the project file, the loading, a database behind a plugin and every interface. A C# mode's client half is a Lua client script all the same. Whichever it is, the mode runs on the server's simulation thread, one tick at a time, 30 times a second: a slow callback stalls every player, and the server log says so when it happens. ## 8. Admins The server's own commands - `/give`, `/tp`, `/horse`, `/time`, `/weather`, `/kick`, `/reload` and the rest - answer **admins** only. An admin is a registered name that `[accounts] admins` lists, once its owner has logged in: ```toml [accounts] admins = ["Henry"] ``` Join, `/register ` to claim the name, and from the next visit `/login `; a name in the list becomes an admin the moment it is registered. [Chat commands](/reference/chat-commands/) lists every built-in and who may use it; a game mode can promote a player itself. ## 9. Your editor The server folder carries the whole API in the two forms editors read, so completion, documentation on hover and a warning for a wrong name or argument are there before the server ever runs a line: - **Lua** - `sdk/KcdMp.d.lua` (the game mode API) and `sdk/KcdMp-client.d.lua` (the client script API) are definitions for the **Lua language server** (LuaLS). In VS Code install the "Lua" extension (sumneko) and open the `gamemodes` folder: its `.luarc.json` already points the language server at `../sdk`. Any other editor that runs the Lua language server takes the same file. For a mode in a folder of its own, put a `.luarc.json` next to the script: ```json { "runtime.version": "Lua 5.4", "workspace.library": ["../../sdk"], "workspace.checkThirdParty": false } ``` or copy the `.d.lua` file into the folder and point `workspace.library` at `"."`. `lua-language-server --check .` in that folder is the same check from a terminal: an unknown name or a wrong argument type is a diagnostic there and a silent `nil` on the server. The files are also downloadable from this site: [KcdMp.d.lua](https://docs.kcd-mp.com/KcdMp.d.lua), [KcdMp-client.d.lua](https://docs.kcd-mp.com/KcdMp-client.d.lua). - **C#** - `sdk/KcdMp.Api.dll` with `KcdMp.Api.xml` next to it: a project that references the DLL gets IntelliSense with every member's description in Visual Studio, Rider or VS Code with the C# extension. The project file is on [the C# page](/csharp/server/#the-project). The same files are what a coding assistant reads: [AI assistants](/getting-started/ai-assistants/) says how to give one the whole reference. # AI assistants > This documentation as plain text for AI assistants - llms.txt, one file per API and per reference list, the Markdown behind every page, the API as language-server definitions - and a CLAUDE.md that starts a game-mode project with Claude Code or another coding agent. Every page here is written once, as Markdown, and published twice: as the page you are reading and as plain text an assistant can read whole. Point a coding agent at the files below and it works from the same reference you do - the real syntax of every function, the real keys of every item - instead of what it remembers of some other game's API. ## The files - [`/llms.txt`](https://docs.kcd-mp.com/llms.txt) - the index: what KCD:MP is, how to read the rest, links to every file below. A few KB. - [`/llms-small.txt`](https://docs.kcd-mp.com/llms-small.txt) - **the one to give a game-mode project**: these getting-started pages, the guides, every server callback and function, the client API, the map of the reference lists. About 360 KB, ~90k tokens - one context window. - [`/_llms-txt/lua-server-api.txt`](https://docs.kcd-mp.com/_llms-txt/lua-server-api.txt) - the Lua server API alone: the guides, every callback and function. About 300 KB. - [`/_llms-txt/lua-client-api.txt`](https://docs.kcd-mp.com/_llms-txt/lua-client-api.txt) - the client API alone. About 25 KB. - [`/_llms-txt/reference-overview.txt`](https://docs.kcd-mp.com/_llms-txt/reference-overview.txt) - the map of the reference lists, the weather presets, the built-in chat commands, every `server.toml` key, stats and skills. About 25 KB. - `/_llms-txt/reference-.txt` - one file per reference list, 100 KB to 1.5 MB each: [`items`](https://docs.kcd-mp.com/_llms-txt/reference-items.txt), [`souls`](https://docs.kcd-mp.com/_llms-txt/reference-souls.txt), [`buffs`](https://docs.kcd-mp.com/_llms-txt/reference-buffs.txt), [`meshes`](https://docs.kcd-mp.com/_llms-txt/reference-meshes.txt), [`clothing-presets`](https://docs.kcd-mp.com/_llms-txt/reference-clothing-presets.txt), [`animations`](https://docs.kcd-mp.com/_llms-txt/reference-animations.txt), [`particle-effects`](https://docs.kcd-mp.com/_llms-txt/reference-particle-effects.txt), [`audio-triggers`](https://docs.kcd-mp.com/_llms-txt/reference-audio-triggers.txt), [`levels`](https://docs.kcd-mp.com/_llms-txt/reference-levels.txt). - [`/_llms-txt/c-plugins.txt`](https://docs.kcd-mp.com/_llms-txt/c-plugins.txt) - the C# tier. About 30 KB. - [`/llms-full.txt`](https://docs.kcd-mp.com/llms-full.txt) - everything, the reference lists included. Over 6 MB - more than a context window holds; use the sets. - [`/KcdMp.d.lua`](https://docs.kcd-mp.com/KcdMp.d.lua) and [`/KcdMp-client.d.lua`](https://docs.kcd-mp.com/KcdMp-client.d.lua) - **the API as Lua language server definitions**: every function, callback and constant with its types and documentation, in LuaLS `---@param` / `---@return` form. About 125 KB and 8 KB. The same files ship in the server folder's `sdk/` ([Setting up](/getting-started/setting-up/#9-your-editor)). **Every page has a Markdown twin.** Replace the trailing `/` of a page's address with `.md`: `/lua/server/functions/setspawninfo/` is also `/lua/server/functions/setspawninfo.md` - the source of the page, without the navigation, in one request. Names are lowercase in addresses (`SetSpawnInfo` → `setspawninfo`). An agent that looks pages up as it works should fetch these, not the HTML. The files follow [llmstxt.org](https://llmstxt.org/) and are built from the same source as the site on every publish, so they cannot fall behind it. Nothing here is behind a login or a rate limit; a plain `curl` gets any of them. ## A game mode with Claude Code A game mode is one Lua file next to the server, named in its `server.toml` ([Setting up](/getting-started/setting-up/)). Two files in the folder the mode lives in - the server's `gamemodes/` folder or a repository of its own - turn a coding agent from a guesser into a colleague who has read the manual: **The definitions.** The server's `gamemodes/` folder already carries a `.luarc.json` that points the Lua language server at `sdk/KcdMp.d.lua`. For a mode in a folder of its own, copy the file (or download it, above) next to the script and add: ```json { "runtime.version": "Lua 5.4", "workspace.library": ["."], "workspace.checkThirdParty": false } ``` An editor with the "Lua" extension (sumneko / LuaLS) then completes every name and flags one that does not exist; an agent working in the folder reads the same file and can run the same check. **The instructions.** Save this as `CLAUDE.md` - Claude Code reads it at the start of every session; the same file as `AGENTS.md` serves Codex, Cursor and the others. It tells the agent where the API is, what it must not invent, and the handful of rules a mode lives by. ```md # - a KCD:MP game mode This is a game mode for KCD:MP (KCD Multiplayer), the multiplayer platform for Kingdom Come: Deliverance II: one Lua 5.4 script the dedicated server runs. The server calls the script's callbacks (`OnPlayerConnect`, `OnPlayerDeath`, `OnTick` ...) and the script calls the server's functions (`SendClientMessage`, `SetSpawnInfo`, `CreateActor` ...). ## The API is documented, never guessed - `KcdMp.d.lua` in this folder is the whole game mode API - every function, callback and constant with its types and documentation, in Lua language server form. Read it before writing; it is the reference that is always at hand. If it is missing, fetch https://docs.kcd-mp.com/KcdMp.d.lua. - For the guides and the examples read https://docs.kcd-mp.com/llms-small.txt once per session: how the server runs a script, the tick, combat, an example for every callback and function, the client API, the map of the reference lists. - For one function or callback fetch its page as Markdown: https://docs.kcd-mp.com/lua/server/functions/.md or https://docs.kcd-mp.com/lua/server/callbacks/.md, the name in lowercase (`SetSpawnInfo` → `setspawninfo.md`). - Only the functions and callbacks the documentation lists exist. There is no `Player` object, no event emitter, no `require("KcdMp")`, no API from any other game. If a function is not on https://docs.kcd-mp.com/lua/server/ it does not exist - say so rather than inventing one. - Keys of game things - items, souls, buffs, meshes, outfits, animation clips, sounds, doors - come from the reference lists (https://docs.kcd-mp.com/reference/; one file per list at https://docs.kcd-mp.com/_llms-txt/reference-.txt - they are big, fetch the one you need). Never make a key up. Keep the name or the GUID in the script, not the numeric id: ids shift with game patches. ## How the server runs the script - Plain Lua 5.4 with the standard library; one file, or a folder of files joined by `require` (relative to the script). The API is globals the server registers before the script runs; the callbacks are globals the script defines. - Everything runs on the simulation thread, one tick at a time, 30 times a second. No threads, no locks, no races - and a slow callback stalls every player. Heavy work goes on a timer (`SetTimer`), not in `OnTick`. - `pid` is a player, `0` to `GetMaxPlayers() - 1`, reused after a disconnect: keep the pid while a player is on, check `IsPlayerConnected(pid)` before trusting one kept across ticks. `id` is a world entity (a horse, a prop, an NPC actor), `nil` from every getter once it is gone. - Positions are metres in the level's world space (`z < 0` = on the terrain), yaw is degrees, colours are `0xRRGGBBAA` (the constants name the usual ones), times are milliseconds, the world clock is hours. - A bad key or id never raises: the call returns `nil` or `false` and the server log says why. Check returns. - A runtime error inside a callback is logged and that callback's effect is skipped; a syntax error stops the server at start (after a `/reload` it leaves the built-in freeroam in charge until the next reload). - Chat commands arrive in `OnPlayerCommandText(pid, cmd, args)`; parse `args` with `sscanf(args, "ud")` (`u` a player, `d` a whole number, `f` a number, `s` a word, `z` the rest of the line, `?` optional). Return `true` when handled, `false` to let the server's built-in commands have it. - `Log(...)` writes to the server log with a `[lua]` prefix. ## Working here - The mode is `.lua` in this folder. `server.toml` names it under `[gamemode] script`; `watch = true` there reloads it on save, `/reload` in chat does the same by hand. - Before calling a change done, run the Lua language server's check over the folder (`lua-language-server --check .` - `.luarc.json` points it at `KcdMp.d.lua`): an unknown name or a wrong argument type is a diagnostic there and a silent `nil` on the server. Zero diagnostics is the bar. - Run a local server with `KcdMp.Server --gamemode .lua` and read its log for `[lua]` lines. - The modes that ship with the server - `freeroam.lua`, `duel_arena.lua` and the `marker` example with its client half - are the style to follow. ``` Then ask for the mode in plain words - *a capture-the-flag with two teams, a flag prop in each camp, ten minutes on the HUD clock* - and the agent fetches what it needs. Claude Code fetches the URLs itself; for an assistant without web access, paste `llms-small.txt` into the conversation, or keep a copy beside the mode: ```bash curl -O https://docs.kcd-mp.com/llms-small.txt ``` A **C# plugin** project works the same way with `sdk/KcdMp.Api.dll` and its `.xml` in place of the definitions file - the agent reads the interfaces and their summaries from the project's reference - and `c-plugins.txt` in place of the Lua API in the instructions. ## Other assistants - **ChatGPT, Gemini, a chat window**: attach or paste `llms-small.txt`; add the reference list the mode needs. - **Cursor**: *Settings → Indexing & Docs → Add Doc* with `https://docs.kcd-mp.com/llms-small.txt`, then `@Docs` in a prompt. - **Anything that crawls**: `robots.txt` allows every agent, and `/sitemap-index.xml` lists every page. # Server configuration > Every key of server.toml - the server, the game mode and its client scripts, rates, area of interest, the world, persistence, validation, the master list, accounts, commands, the audit, combat, parties, effects, actors and the spawn. The server reads `server.toml` from its working directory (or `--config `). Every key is optional and the values below are the defaults; a command-line flag overrides the file (`--max-players 64` beats `[server] max_players`). The file the server ships carries the same keys with a line per group and a link here; without any `server.toml` the server runs on the defaults alone, which for two keys - the player records and the game's tables - means less than the shipped file gives (noted below). Where a key shapes what a game mode sees, its API page is linked. ## [server] | Key | Default | | |---|---|---| | `name` | `"KCD:MP dev server"` | the server's name in the browser and the welcome | | `motd` | `""` | a message shown to every joining player | | `port` | `7777` | UDP | | `max_players` | `32` | the slot count; player ids run to `max_players - 1` ([`GetMaxPlayers`](/lua/server/functions/getmaxplayers/)). Fifty players walking, riding and fighting at once cost the server about a tenth of one core and 1.5 MB/s outbound; the count is yours to choose | | `password` | `""` | players must send it to join; `""` = open | | `level` | `"klaster"` | the level every client boots - `klaster`, `trosecko` or `kutnohorsko` ([levels](/reference/levels/), [`GetLevel`](/lua/server/functions/getlevel/)) | | `build_hash` | `""` | require this game build; `""` = any | | `stale_session_seconds` | `5.0` | a fresh join under a name in use replaces its holder once that client has been silent this long; `0` = never | | `log_file` | `"server.log"` | every line the console shows is written to this file too, next to the server; the previous run's file is kept as `server.log.1`. `""` = the console only | ## [gamemode] | Key | Default | | |---|---|---| | `script` | `"gamemodes/freeroam.lua"` | a `.lua` script or a `.dll` compiled against `KcdMp.Api` (`path.dll:TypeName` picks a type); `""` = the built-in freeroam | | `watch` | `false` | `true` re-reads the script when its file changes on disk - a development server ([`ReloadGameMode`](/lua/server/functions/reloadgamemode/)); the client scripts' folder is watched too | ## [client] The game mode's client half: Lua files the server sends to every joining player and runs in their game, in a sandbox that reaches nothing outside the game ([the client guide](/lua/client/getting-started/)). A mode without one needs nothing here. | Key | Default | | |---|---|---| | `scripts` | `""` | a folder of `.lua` files, sent in name order; `""` = the `client/` folder next to the game mode's script or plugin (`gamemodes/arena/arena.lua` + `gamemodes/arena/client/*.lua`) - the built-in mode has none unless a folder is named. At most 64 files, 256 KB each, 2 MB together. `/reload` sends the folder again | | `console` | `false` | `true` lets the players open the **F9** window of the KCD:MP overlay on this server - the console line and the debug view. A convenience for a development server, not a security boundary: the server never trusts what a client says either way | ## [rates] | Key | Default | | |---|---|---| | `tick_hz` | `30` | the simulation rate - how often `OnTick` runs | | `snapshot_hz` | `30` | snapshot rounds per second, at most `tick_hz` | | `workers` | `0` | threads for the per-client phase; `0` = the cores minus two | ## [aoi] | Key | Default | | |---|---|---| | `radius` | `200.0` | metres a client sees around itself; `0` = everyone sees everyone | | `cell` | `64.0` | the grid cell size, metres | ## [world] | Key | Default | | |---|---|---| | `time` | `"07:30"` | the world clock at start ([`SetWorldTime`](/lua/server/functions/setworldtime/)) | | `time_ratio` | `15.0` | game seconds per real second; `0` freezes the clock ([`SetTimeRatio`](/lua/server/functions/settimeratio/)) | | `rain` | `-1.0` | rain forced on every client, `0` .. `1`; below `0` = the weather's own ([`SetRain`](/lua/server/functions/setrain/)) | | `weather` | `""` | the sky every client follows - a [preset or a profile](/reference/weather/); `""` = the level's own ([`SetWeather`](/lua/server/functions/setweather/)) | | `weather_blend` | `10.0` | seconds a weather change blends in over | | `max_entities` | `256` | horses, pickups, props, actors and dogs the world holds at once | ## [persistence] | Key | Default | | |---|---|---| | `file` | `"data/players.json"` | the player records - visits, play time, last position, the mode's saved data ([`GetSavedPlayer`](/lua/server/functions/getsavedplayer/)); `""` = memory only (the value without a `server.toml`). The server store (`server.json`) and the bans (`bans.json`) live beside it | ## [validation] | Key | Default | | |---|---|---| | `max_speed` | `12.0` | metres per second a report may move a player; faster is refused and the client pulled back; `0` = off | | `heightmap` | `""` | the level's terrain, e.g. `"data/heightmaps/{level}.hmap"` - the files `tools/KcdMp.ExportHeightmap.exe` writes from your own game ([Exporting the terrain](/guides/terrain/)); `""` = no terrain check ([`GetTerrainHeight`](/lua/server/functions/getterrainheight/)) | | `navmesh` | `""` | the level's navigation mesh, e.g. `"data/navmesh/{level}.knav"` - the files `tools/KcdMp.ExportNavmesh.exe` writes from your own game ([Exporting the navigation mesh](/guides/navigation/)); with it the NPC actors walk around walls and [`FindPath`](/lua/server/functions/findpath/) answers; `""` = straight lines | | `collision` | `""` | the level's collision geometry, e.g. `"data/collision/{level}.kcol"` - the files `tools/KcdMp.ExportCollision.exe` writes from your own game ([Exporting the collision geometry](/guides/collision/)); with it [`RayCast`](/lua/server/functions/raycast/) answers and the floor under a player counts as the ground; `""` = none | | `line_of_sight` | `false` | with the geometry: a hit or shot claimed through a wall (or a closed door) is refused; off, the server only logs what it would have refused | | `no_clip` | `false` | with the geometry: a player whose reported step goes through a wall (or a closed door) is pulled back to the last accepted position; off, the server only logs what it would have refused | | `max_below_terrain` | `6.0` | metres a player may be under the terrain (cellars, mines) | | `max_above_terrain` | `60.0` | metres over it (towers, cliffs); with the collision geometry the floor under the player - a bridge, an upper storey - is the ground, so a storey's worth (`10`) does | ## [master] The server list: the server announces itself there every `interval_seconds` and shows up in every launcher's *Servers* tab. The environment variables `KCDMP_MASTER_URL` and `KCDMP_MASTER_ADDRESS` replace the two addresses when set, and the command line's `--master` / `--master-address` beat both. | Key | Default | | |---|---|---| | `url` | `"https://kcd-mp.com/server-list"` | the public list; another list's address, or `""` = announce nowhere (a private server) | | `interval_seconds` | `60` | how often | | `public_address` | `""` | the address the list should show; `""` = the one the master sees the heartbeat come from | ## [accounts] | Key | Default | | |---|---|---| | `registration` | `true` | `false` = no new `/register` (existing names still log in) | | `login_grace_seconds` | `180` | a registered name has this long after joining to `/login` | | `login_hold` | `true` | a registered name waits frozen in a world of its own until its login; `false` = it plays as a guest among everyone meanwhile | | `min_password_length` | `4` | | | `admins` | `[]` | registered names whose owners are admins once logged in ([`IsPlayerAdmin`](/lua/server/functions/isplayeradmin/)); a name not registered yet becomes an admin the moment its owner registers it | ## [commands] | Key | Default | | |---|---|---| | `builtin` | `true` | `false` = no [built-in chat commands](/reference/chat-commands/) at all; the mode answers everything | | `public` | `["help", "pos", "players", "items", "uptime"]` | the built-ins anyone may use; every other one answers admins only | | `disabled` | `[]` | built-ins switched off by name, e.g. `["horse", "rain"]`; the mode may still answer them | ## [audit] The inventory audit ([`OnPlayerAuditViolation`](/lua/server/callbacks/onplayerauditviolation/)): the server keeps a shadow of what each player's records explain and compares it with the inventory the client reports. | Key | Default | | |---|---|---| | `enabled` | `true` | | | `action` | `"log"` | `log`, `kick` or `ban` when a violation stands | | `strikes` | `2` | reports in a row a discrepancy must show in | | `ban_seconds` | `0` | for `action = "ban"`; `0` = for good | | `guarded_categories` | `"Armor,MeleeWeapon,MissileWeapon,Ammo,Helmet,Hood"` | the item categories judged ([items](/reference/items/)); the rest are learned, never judged | ## [combat] The model is the [Combat guide](/lua/server/combat/). | Key | Default | | |---|---|---| | `pvp` | `true` | `false`: players cannot lock on to or hurt each other | | `respawn_seconds` | `10` | a dead player stands up again at their spawn after this; `0` = the mode calls `SpawnPlayer` | | `max_reach` | `4.0` | metres the attacker and the target may be apart for a claim to count | | `fight_timeout` | `30.0` | seconds without a blow that end a fight; `0` = never by time | | `claim_window_ms` | `1500` | a hit counts only this long after the attacker's swing; `0` = always | | `damage_scale` | `1.0` | a multiplier on every hit | | `max_claim_damage` | `80.0` | without the tables, a claim above this is clamped | | `tables` | `"data/combat/items.json"` | the game's tables: weapons, armour, the item, soul, buff and mesh catalogues - the file `tools/KcdMp.ExportTables.exe` writes from your own copy of the game ([Exporting the game's tables](/guides/game-tables/)); `""` (the value without a `server.toml`) = no tables: the damage the clients report, clamped by `max_claim_damage`, and the catalogues by GUID only | | `claimed_buffs` | `[]` | the buff classes the server takes over ([buffs](/reference/buffs/), [`ClaimBuffClasses`](/lua/server/functions/claimbuffclasses/)) | | `potion_speed` | `2.0` | a potion's regeneration runs this many times faster than the game's own | | `alcohol_per_content` | `0.01` | a drink's alcohol content × this on the blood-alcohol level | | `alcohol_decay` | `0.00125` | taken off the level per second | | `drunk_threshold` | `0.32` | drunk from here up; sober again from half of it down | | `hangover_seconds` | `120.0` | the hangover after sobering | | `attack_scale` | `0.32` | a weapon's table attack × this = its damage before armour | | `ranged_scale` | `0.0077` | an ammunition's attack × the launch speed × this = a projectile's damage before armour | | `armour_pivot` | `50.0` | the armour on the struck part that halves a hit (`d / (d + pivot)`, 85 % at most) | | `fist_damage` | `6.0` | bare-handed, before armour | | `body_parts` | `""` | rewrites of the claim's body part, `"claim=part,..."`; normally empty | | `max_stamina` | `100.0` | | | `stamina_regen` | `15.0` | per second, after 1.5 s without a cost; halved with an injured head or torso | | `attack_stamina_cost` | `10.0` | a swing (× 1.2 slash or smash, × 0.5 bare-handed, × 1.25 with an injured arm) | | `hit_stamina_damage` | `12.0` | a hit taken | | `shot_stamina` | `15.0` | a shot | | `shot_interval_ms` | `400` | shots closer than this are refused | | `shot_window_seconds` | `6.0` | a ranged hit counts within the flight time plus this | | `block_stamina_cost` | `10.0` | a swing blocked | | `sprint_stamina_cost` | `4.0` | per second at a sprint | | `jump_stamina_cost` | `6.0` | per jump | | `injury_threshold` | `15.0` | a hit of at least this injures the part struck | | `bleed_per_damage` | `0.015` | a stab or a slash bleeds this × the damage in health per second | | `max_bleed` | `1.0` | health per second at most | | `bleed_seconds` | `40.0` | how long a bleed lasts | ## [party] The groups the server keeps for the game mode's own commands ([the parties guide](/lua/server/parties/)): the invitation, the frames on the members' screens, the no-friendly-fire rule. The commands themselves - `/invite`, `/accept`, `/p` - are the mode's; the shipped freeroam mode has them. | Key | Default | | |---|---|---| | `max_size` | `5` | members per party (at least 2) | | `invite_timeout` | `30` | seconds until an unanswered invitation runs out | | `frames` | `true` | the party frames on every player's screen; a mode can switch them per player ([`ShowPartyFrames`](/lua/server/functions/showpartyframes/)) | | `leader_leaves` | `"next"` | what the leader's leaving does: `"next"` hands the lead to the next member in join order, `"disband"` ends the party | | `friendly_fire` | `false` | `true` lets members hurt each other; off, a hit between members is refused before the mode hears of it, like one between teammates | ## [effects] | Key | Default | | |---|---|---| | `range` | `150.0` | metres from the point within which players get a mode's effect, decal or sound ([`SpawnEffect`](/lua/server/functions/spawneffect/), [`SpawnDecal`](/lua/server/functions/spawndecal/), [`PlaySound`](/lua/server/functions/playsound/)); `0` = everyone in that virtual world | ## [actors] How an [NPC actor](/lua/server/#npc-actors) fights back and blocks; its wounds follow the `[combat]` injury and bleeding keys like a player's. | Key | Default | | |---|---|---| | `fight_back` | `true` | a blow on an actor makes the attacker its opponent | | `swing_interval` | `1.8` | seconds between its swings | | `reach` | `2.2` | metres it swings from; an unarmed actor closes to 0.7 of it | | `chase_speed` | `2.0` | metres per second after its opponent | | `chase_range` | `30.0` | an opponent farther than this is given up | | `attack_scale` | `1.0` | a multiplier on the blow the victim's game computed | | `max_damage` | `60.0` | a blow does at most this | | `block_chance` | `0.5` | how often an armed actor raises its guard against a swing; `0` never, `1` every time | | `block_hold` | `0.7` | seconds the guard stays up | | `drop_weapons` | `true` | a dying actor's held weapon and shield fall as pickups everyone can take (its preset's first melee weapon and first shield); `false` = it drops nothing | ## [spawn] | Key | Default | | |---|---|---| | `x`, `y`, `z`, `yaw` | `1280.0`, `1088.0`, `-1.0`, `0.0` | the default spawn ([`GetDefaultSpawn`](/lua/server/functions/getdefaultspawn/)); `z` below `0` = on the terrain | | `horse_soul` | `Horse2`'s GUID | the breed of horses made without one ([horses](/reference/souls/horse/); a name or an id works too) | | `clothing_preset` | `UC_HenryTrosky`'s GUID | the outfit players spawn in ([clothing presets](/reference/clothing-presets/)) | | `weapon_preset` | `sword_shield_4_01`'s GUID | their weapons ([weapon presets](/reference/weapon-presets/)) | | `items` | `["torch_weapon"]` | given at a player's first spawn of a session, on top of the presets ([items](/reference/items/)) | | `stat_level` | `15` | strength, agility, vitality and speech raised to this at the spawn; `0` = the level's own 5 | | `appearances` | thirteen generic men | the souls whose faces players get, one each by a hash of the name, unless the mode sets one ([souls](/reference/souls/), [`SetSpawnInfo`](/lua/server/functions/setspawninfo/)) | # Guides > One job per page, for any scripting language - exporting the game's tables, the terrain, the navigation mesh and the collision geometry from your own copy of the game, and putting a server on the public list. Each guide is one job, start to finish, and holds whatever language the game mode is written in. The [setting-up page](/getting-started/setting-up/) says where each fits. ## The game's data The server does not have the game. It knows what the players' games report, but not what a sword does against a brigandine, where the ground is, where the walls are or how to walk around them. The files below are the parts of the game a server needs for that, **exported from your own copy of the game** with the tools in the Windows server folder's `tools/`. They are never shipped with the server - they are the game's own data, and every server owner has the game - so each owner makes them once and puts them under `data/`; a server on Linux gets the files copied over. Without a file the server runs exactly as before: each one turns on one thing, and the server log says at start which it found. | Guide | File | What it turns on | |---|---|---| | [Exporting the game's tables](/guides/game-tables/) | `data/combat/items.json` | damage from the game's own weapon and armour tables; items, souls, buffs and meshes by name - `/give shortswordBroad`, a horse breed by name, the potions and buffs the server owns | | [Exporting the terrain](/guides/terrain/) | `data/heightmaps/.hmap` | the terrain check - a player far under or over the ground is pulled back - and the terrain height for a game mode | | [Exporting the navigation mesh](/guides/navigation/) | `data/navmesh/.knav` | NPC actors that walk around walls instead of into them; paths, reachability, floors and the nearest walkable spot for a game mode | | [Exporting the collision geometry](/guides/collision/) | `data/collision/.kcol` | line of sight on hits and shots, a step through a wall caught, the floor under a player as the ground; rays for a game mode | The three level files are one per level per game build: a server that runs `klaster` needs `klaster.hmap`, `klaster.knav`, `klaster.kcol`, and after a game update they are exported again. The tools do all three levels by default, so the files are there whichever level the server switches to. ## Running a server | Guide | | |---|---| | [Putting a server on the public list](/guides/public-server/) | the port, the address the list should show, the name and the password, and what players see in the launcher | # Exporting the game's tables > Making data/combat/items.json from your own copy of the game - the weapon and armour numbers behind every hit, and the item, soul, buff, consumable and mesh lists the server names things from. The server judges every hit itself - the attacker's weapon against the armour on the part it struck - and resolves the keys a game mode and the chat commands use: an item by name, a horse breed by name, a buff by its class. Both need the game's own tables, which the server does not have. `data/combat/items.json` is that export: the weapon and armour numbers and the lists of items, souls, buffs, consumables, weapon presets and prop meshes, read straight from the game's files. With it: - a hit does what the game's tables say it does (`[combat] attack_scale`, `armour_pivot` and the rest scale it - [the combat model](/lua/server/combat/)); - items, souls, buffs and meshes answer to their **names** and ids as well as their GUIDs - `/give shortswordBroad`, `/horse Horse2`, `GivePlayerBuff(pid, "potion_marigold_decoction")`, `/prop barrel_a` - with the English names too (`/give duelling longsword`); - the server owns potions, drink and the buffs it claims, and knows what each consumable does. Without it the server takes the damage the players' games report (clamped by `[combat] max_claim_damage`) and knows items, souls and buffs by their GUIDs only. It says so at start: `combat tables: ... not usable` or nothing at all. ## Exporting it On the machine that has the game, run `tools/KcdMp.ExportTables.exe` from the Windows server folder - double-click it, or from a terminal. It finds the game through Steam (or asks for the folder in a dialog), reads the game's tables, the English names and the object files, and writes `data/combat/items.json` into the server folder in a few seconds; the last lines say what it counted and where the file went. The game does not start. ``` KcdMp.ExportTables [--game ] [--out ] [--no-names] [--no-meshes] ``` `--game` names the game's folder when Steam does not; `--out` writes elsewhere; `--no-names` leaves the English names out (`/give` by English name stops working); `--no-meshes` skips the object files (a few seconds faster, no props by name). `--help` prints the same. ## Installing it The tool puts the file where the server reads it. For a server on **Linux**, copy it into that server's data folder - the one that holds the player records - as `combat/items.json`. The configuration names it: ```toml [combat] tables = "data/combat/items.json" ``` The server log confirms it at start: `combat tables: data/combat/items.json (... weapons, ... armour pieces): damage from the tables`. ## The ids The reference lists on this site - [items](/reference/items/), [souls](/reference/souls/), [buffs](/reference/buffs/), [meshes](/reference/meshes/) and the rest - are the same export of the same game build, so their numeric **ids** are the ones your server resolves. An id is a row number of a name-sorted export: the same for one game build, shifted by a game patch that adds things. Keep the **name** or the **GUID** in a game mode and in anything else durable; use the id at the chat line. One export per game build: after a game update, export again, and the server picks the new file up at its next start. # Exporting the terrain > Making data/heightmaps/.hmap from your own copy of the game - the level's ground heights that turn on the terrain check and GetTerrainHeight. The terrain is the level's heightmap: the height of the ground at every point, without buildings. With it the server refuses a position more than `[validation] max_below_terrain` metres under the ground (cellars and mines are allowed for) or `max_above_terrain` over it (towers and cliffs), and pulls the client back to where it last stood - a fly hack or a fall through the world ends there. A game mode gets [`GetTerrainHeight`](/lua/server/functions/getterrainheight/), the ground under any point; a spawn or a teleport with `z` below `0` lands on it. Without it the terrain check is off for that level and the function answers `nil`. ## Exporting it The Windows server folder carries the tool for it: run `tools/KcdMp.ExportHeightmap.exe` on the machine that has the game and the KCD:MP client (Steam running, the game closed). The terrain lives in the engine, so the tool **starts the game** once per level through the KCD:MP launcher, samples the terrain when the level is loaded and closes it again - about a minute per level; the files land in the server folder's `data/heightmaps/`. Leave the game alone while it runs. ``` KcdMp.ExportHeightmap [--level |all] [--step ] [--game ] [--client ] ``` All three levels by default; `--level klaster` does one. `--step 2` samples every 2 metres instead of 4 (a finer map, four times the size). The game is found through Steam or `--game`; the KCD:MP client is looked for next to the tool, then `--client`, then asked for in a dialog. `--help` prints the same. By hand, from inside the game: stand in the world on the level, open the KCD:MP console (**F9**, where the server allows it) and run `KcdMp_heightmap`. The file `heightmap-.hmap` lands in your KCD:MP data folder (`%LOCALAPPDATA%\KcdMp`) in under a second; the client log there says so, with how many samples it holds. The default samples every 4 metres over the level's 4096 × 4096 m (about 2 MB); `KcdMp_heightmap 2` samples every 2 metres, `KcdMp_heightmap 4 0 0 8192 8192` covers a larger area. ## Installing it The tool puts the files where the server reads them. For a file made by hand, or for a server on **Linux**, put it in the server's data folder - the one that holds the player records - under `heightmaps/`, named after the level (`klaster.hmap`), and point the configuration at it: ```toml [validation] heightmap = "data/heightmaps/{level}.hmap" max_below_terrain = 6.0 max_above_terrain = 60.0 ``` `{level}` is replaced by the level the server runs, so one line serves every level you export. The server log confirms the map at start (`heightmap: ... samples every 4 m ...`) or says why it could not use it. With the [collision geometry](/guides/collision/) as well, the floor under a player - a bridge, an upper storey - counts as the ground, so `max_above_terrain` can be a storey's worth (`10`) rather than a tower's. One heightmap per level per game build: after a game update, export it again. # Exporting the navigation mesh > Making data/navmesh/.knav from your own copy of the game - the game's own walkable surface, on which NPC actors walk around walls and a game mode asks for paths. The navigation mesh is the game's own: the walkable surface of the level - every yard, road, floor, stair and bridge - as polygons, the way the game's own people walk it. With it an NPC actor sent somewhere ([`MoveActor`](/lua/server/functions/moveactor/)) walks there around the walls instead of straight through them, an actor chasing a player goes around the corner after them, and a game mode can ask for a walk between two points ([`FindPath`](/lua/server/functions/findpath/)), whether one is reachable from the other ([`IsReachable`](/lua/server/functions/isreachable/)), where the floor is - indoors, on a bridge, where the terrain says otherwise ([`GetNavmeshHeight`](/lua/server/functions/getnavmeshheight/)) - and the nearest walkable spot to a point ([`NearestNavmeshPoint`](/lua/server/functions/nearestnavmeshpoint/)). Without it the actors walk straight lines - the body stops at a wall and catches up when the line comes out - and the functions answer `nil` / `false`; [`HasNavmesh`](/lua/server/functions/hasnavmesh/) tells a mode which it is. ## Exporting it Run `tools/KcdMp.ExportNavmesh.exe` from the Windows server folder on a machine that has the game. It reads the mesh straight from the level's own files - the game does not start, it takes a second per level - and writes the files into the server folder's `data/navmesh/`. ``` KcdMp.ExportNavmesh [--level |all] [--variant ] [--game ] [--out ] ``` All three levels by default; `--level klaster` does one. The game keeps a mesh for the level as the story leaves it - doors bricked up, a ruin cleared, a camp built - and the tool takes the state a fresh world starts in; `--variant ` picks another of the level's states, for a server that stages one (`-1` is the base mesh alone). The game is found through Steam or `--game`; `--out` writes elsewhere. `--help` prints the same. ## Installing it The tool puts the files where the server reads them. For a server on **Linux**, copy them into its data folder under `navmesh/`, named after the level (`klaster.knav`), and point the configuration at them: ```toml [validation] navmesh = "data/navmesh/{level}.knav" ``` `{level}` is replaced by the level the server runs. The server log confirms the mesh at start (`navmesh: ... tiles, ... polygons ...: the actors walk paths, FindPath is live`) or says why it could not use it. One mesh per level per game build: after a game update, export it again. # Exporting the collision geometry > Making data/collision/.kcol from your own copy of the game - the level's walls, roofs, floors and trees as the game's physics knows them, for line of sight, the true ground and a game mode's rays. The collision geometry is the level as the game's own physics knows it: every wall, roof, floor, stair, fence, rock and tree trunk, the way arrows and people bump into them. With it the server can shoot rays of its own: - a blow or a shot claimed through a wall is caught - `[validation] line_of_sight` turns the refusal on; the log says what it would refuse either way; - a player walking through a wall or a closed door is caught the same way - `[validation] no_clip`: the step from the last accepted position to the reported one is checked against the geometry and pulled back; - the floor under a player - a bridge, a roof, an upper storey - counts as the ground of the [terrain check](/guides/terrain/), so the allowance over the terrain can be a storey rather than a tower; - a game mode gets [`RayCast`](/lua/server/functions/raycast/), [`IsLineOfSight`](/lua/server/functions/islineofsight/) and [`GetGroundZ`](/lua/server/functions/getgroundz/) - a wall ahead, a shot's clearance, the floor to put a spawn on. The doors the server knows are open let a ray through. Players, actors and horses are not part of it, and neither is anything the game lets you push or knock over - crates, barrels, buckets, carts, a brazier: the server could not follow them once moved, so the geometry holds the level as built. Standing on a barrel, `GetGroundZ` gives the floor under it. Without it the rays answer nothing, no line of sight is checked and the ground is the terrain's; [`HasCollision`](/lua/server/functions/hascollision/) tells a mode which it is. ## Exporting it Run `tools/KcdMp.ExportCollision.exe` from the Windows server folder on a machine that has the game and the KCD:MP client (Steam running, the game closed). The geometry lives in the running game, so the tool **starts the game** once per level through the KCD:MP launcher: it loads the level, waits half a minute for the level's objects to settle, walks the physics world in a few passes - seconds, on top of the game's own loading time, which is minutes on the big levels - and closes by itself. The tool prints the progress; leave the game alone while it runs. The file lands in the server folder's `data/collision/`. ``` KcdMp.ExportCollision [--level |all] [--wait ] [--game ] [--client ] ``` All three levels by default, one game run each; `--level klaster` does one. `--wait` changes the settling time (30 s by default). The game is found through Steam or `--game`; the KCD:MP client is looked for next to the tool, then `--client`, then asked for in a dialog. `--help` prints the same. ## Installing it The tool puts the files where the server reads them. For a server on **Linux**, copy them into its data folder under `collision/`, named after the level (`klaster.kcol`), and point the configuration at them: ```toml [validation] collision = "data/collision/{level}.kcol" line_of_sight = false # true: a hit or shot claimed through a wall is refused no_clip = false # true: a step through a wall is pulled back ``` Both rules start off: the server logs what they would have refused, so an owner can watch a few sessions for false alarms (a doorway the geometry has narrower than the game, a fence the horse takes) before turning them on. The server log confirms the geometry at start (`collision: ... parts, ... triangles ...: RayCast and the ground are live ...`) or says why it could not use it. Loading a level takes under a second and 150-270 MB of memory (the files are 11-21 MB; the monastery has 280 000 parts, the two big levels 100 000-300 000 parts and 1.2 million triangles each). One file per level per game build: after a game update, export it again. # Putting a server on the public list > What it takes for players to find and join your server - the port, the address the list should show, the name and the password, and what the launcher shows them. A server announces itself to the **public list** at kcd-mp.com once a minute, and every launcher's *Servers* tab shows what the list has. Nothing has to be registered: a server that can be reached is on the list from its first minute and off it three minutes after its last announcement. The settings are `[master]` and `[server]` in `server.toml` ([Server configuration](/getting-started/server-config/)). ## 1. The port The server takes one **UDP** port, `[server] port` (7777 by default). Open it on the machine's firewall and, behind a home router, forward it to the machine - UDP, not TCP. Two servers on one machine take two ports. ## 2. The address The list shows a server under the address it sees the announcement come from - the machine's public address, which is right for a server on a rented box or behind a plain home connection. When it is not - a server that should be found under a hostname, or one behind an address the list cannot see - name it: ```toml [master] url = "https://kcd-mp.com/server-list" # the public list; "" = announce nowhere (a private server) interval_seconds = 60 # how often public_address = "" # "" = the address the list sees; else a hostname or an address ``` `url = ""` keeps a server off the list altogether - a test server, a private one for friends who connect by address. The environment variables `KCDMP_MASTER_URL` and `KCDMP_MASTER_ADDRESS` stand in for the two addresses when set, and the command line's `--master` / `--master-address` beat both. ## 3. What players see The list carries the server's **name**, its **level**, the players on it against `max_players`, the game mode's name, the server's version and whether a **password** is needed: ```toml [server] name = "KCD:MP dev server" # the name in the list and in the welcome motd = "" # a line shown to every joining player password = "" # players must type it to join; "" = open max_players = 32 level = "klaster" # klaster, trosecko or kutnohorsko ``` A player picks the server in the launcher's *Servers* tab (or types its address under *Direct connect*), gives the password if there is one, and the launcher boots their game onto the server's level. A client and a server only play together on the same **protocol number** - the release notes give it - so a server is updated together with the client release; `[server] build_hash` can further require one game build. The list is also a page on the website, [kcd-mp.com/server-list](https://kcd-mp.com/server-list), with the same entries. ## 4. Keeping it yours - **Admins**: `[accounts] admins` lists the registered names whose owners may use the server's own commands after `/login` ([Setting up](/getting-started/setting-up/#8-admins)); `[commands] public` names the built-ins anyone may use, `disabled` switches some off. - **Registration**: `[accounts] registration = false` stops new `/register` claims once your regulars have theirs; `login_hold` keeps a registered name frozen in a world of its own until it logs in, so nobody plays under it meanwhile. - **Bans**: `/kickban [minutes]` and `/unban` in the chat, or a game mode's own rules; the bans live next to the player records. - **Cheating**: the server owns every player's health, stamina, items and position - it judges what the clients report against its own record, and the [world data](/guides/#the-games-data) sharpens that judgement: the terrain and the collision geometry catch a player through a wall or in the air, the tables make a hit what the game says it is, and the inventory audit (`[audit]`) catches items a player cannot explain. # Lua > Scripting KCD:MP in Lua - a game mode on the server, a client script on the player's game, and where each API lives. Lua 5.4 is the scripting language of KCD:MP. It runs in two places, and the two talk to each other: | Where | What | Runs | API | |---|---|---|---| | **Server** | a **game mode** - the rules of one server: who spawns where, what chat and commands do, zones, timers, NPC actors, the world clock | inside the dedicated server, one script per server, on the simulation thread | [Server API](/lua/server/) | | **Client** | a **client script** - the mode's own half on a player's game: a marker, a sound, a bit of UI, a value read from the game | inside the player's game, loaded by the player, in the game's own Lua state | [Client API](/lua/client/) | A game mode alone makes a server: `freeroam.lua` and `duel_arena.lua` ship with it. A client script is optional and belongs to a mode that needs something on the player's screen the server cannot draw itself; the two halves talk through [script events](/lua/server/#script-events) and [state bags](/lua/server/#state-bags). The `marker` example that ships with the server is a mode with both halves. ## Where to start 1. [Getting started on the server](/lua/server/getting-started/) - running a mode, the tick model, ids and units, what happens on an error; then the [Server API index](/lua/server/): every callback and function by topic, each on its own page with its syntax, arguments, return value and an example. 2. [The combat guide](/lua/server/combat/) - the model behind the combat callbacks; [Constants](/lua/server/constants/); [Parties](/lua/server/parties/) - the party model: what the server keeps and the API a mode builds its commands on. 3. [Getting started on the client](/lua/client/getting-started/) and the [Client API index](/lua/client/) - when a mode needs its own half on the player's screen. 4. [The reference lists](/reference/) - every item, soul, buff, mesh, preset, clip, door and container the game has, by the keys these functions take. 5. [Your editor](/lua/server/getting-started/#your-editor) - the whole API as Lua language server definitions (`sdk/KcdMp.d.lua` in the server folder): completion, documentation on hover and a warning for a wrong name or argument while you write. The server folder, the first run and the game's data come before any of it: [Setting up](/getting-started/setting-up/). The same functions exist for [C# plugins](/csharp/), the native tier the Lua maps onto. # Getting started > What a game mode is, how the server runs one, the tick model, ids and units, and what happens when a script fails. A KCD:MP server runs one **game mode**: a Lua script that defines the rules of that server - where players spawn, what the chat and the commands do, who may hurt whom, what stands in the world. The server calls the script's [callbacks](/lua/server/) when something happens (`OnPlayerConnect`, `OnPlayerDeath`, `OnTick` ...) and the script calls the server back through the functions on the other pages (`SendClientMessage`, `SetPlayerPos`, `CreateHorse` ...). A mode that defines nothing is a valid mode: the server spawns everyone at its default point and answers its own chat commands. ## Running a mode The script is named in `server.toml` or on the command line; the command line wins: ```toml [gamemode] script = "gamemodes/freeroam.lua" # relative to the server's working directory; "" = the built-in freeroam watch = false # true: the file is re-read when it changes on disk (a development server) ``` ```bash KcdMp.Server --gamemode gamemodes/my_mode.lua ``` The server ships with `server.toml` and the example modes beside it ([Setting up](/getting-started/setting-up/) has the folder and the first run); your own mode is a file next to them, named in your `server.toml`. `require` resolves relative to the script's directory, so a mode may be a folder of files. Three modes ship with the server and are the best examples: `gamemodes/freeroam.lua` (spawns, greetings, a HUD clock, a greeting zone, the party commands, the NPC actor demo), `gamemodes/duel_arena.lua` (a queue, two players at a time in an arena, the rest untouchable) and `gamemodes/marker/marker.lua` (a checkpoint run with a [client script](/lua/client/getting-started/) that draws the marker in each player's game). A mode is reloaded without a restart by `/reload` (admins), by [`ReloadGameMode()`](/lua/server/functions/reloadgamemode/) from the script itself or by `[gamemode] watch = true`. ## The script Plain Lua 5.4 with the standard libraries. The server registers the API as globals before the script runs; the script defines the callbacks it cares about as globals too: ```lua SetGameModeText("hello") local spawnX, spawnY, spawnZ, spawnYaw = GetDefaultSpawn() function OnPlayerConnect(pid) SendClientMessageToAll(COLOUR_SERVER, GetPlayerName(pid) .. " joined") end function OnPlayerRequestSpawn(pid) SetSpawnInfo(pid, spawnX + 1.5 * (pid % 8), spawnY, spawnZ, spawnYaw) -- a step per player, so nobody spawns inside anyone return true end function OnPlayerCommandText(pid, cmd, args) if cmd == "hello" then SendClientMessage(pid, COLOUR_SERVER, "Hello, " .. GetPlayerName(pid)) return true -- handled end return false -- the server's built-in commands, then "Unknown command" end ``` Scripts are trusted - the server admin wrote them - so the `luanet` table NLua adds is there too (`luanet.import_type("System.IO.File")` gives a script the .NET class library: files, a database, HTTP). ### A command with arguments Every `/` line a player types reaches [`OnPlayerCommandText`](/lua/server/callbacks/onplayercommandtext/) as the command word and the rest of the line. [`sscanf`](/lua/server/functions/sscanf/) turns that rest into typed values - one letter per argument - and tells you what is wrong when it cannot, so a command is a handful of lines: ```lua function OnPlayerCommandText(pid, cmd, args) if cmd == "pay" then local target, amount = sscanf(args, "ud") -- u = a player, d = a whole number if target == false then SendClientMessage(pid, COLOUR_RED, "usage: /pay - " .. amount) -- amount holds the reason return true end if amount <= 0 then SendClientMessage(pid, COLOUR_RED, "the amount must be positive") return true end SendClientMessage(target, COLOUR_GREEN, GetPlayerName(pid) .. " paid you " .. amount) SendClientMessage(pid, COLOUR_SERVER, "you paid " .. GetPlayerName(target) .. " " .. amount) return true end return false end ``` `/pay hans 50` gives Hans's pid and `50` - `hans`, `Hans`, `ha` or his pid all name him, as long as only one player matches ([`GetPlayerId`](/lua/server/functions/getplayerid/) does the matching). `/pay hans abc` gives `false` and `"argument 2 (abc) is not a whole number"`, `/pay nobody 50` gives `"no player called nobody"`, `/pay hans` gives `"argument 2 is missing"`. The letters: `u` a player, `d` a whole number, `f` a number, `s` one word (or a `"quoted string"`), `z` the rest of the line; a `?` after a letter makes it optional. So `/whisper ` is `"uz"`, `/kick [reason]` is `"uz?"`, `/setspawn [yaw]` is `"fffd?"`. The shipped modes do it this way: `freeroam.lua`'s `/hurt [player] [amount]` and `duel_arena.lua`'s `/arena x y z [yaw]`. ## The tick Everything a mode does happens on the server's **simulation thread**, one tick at a time, 30 times a second (`[rates] tick_hz`). The callbacks run from inside a tick; the calls a callback makes take effect in that tick's output. Two consequences: - a script never races with anything - no locks, no threads, a timer's function runs where `OnTick` would; - a slow callback delays the whole tick for every player. The server log says so while it happens (`the slowest tick took 41 ms against a 33 ms budget`); an `OnTick` that does real work every tick is the first place to look when players stutter. Do the heavy things on a [timer](/lua/server/functions/settimer/) every second instead. ## Ids and units | | | |---|---| | **`pid`** | a player: `0` to `GetMaxPlayers() - 1`, given at the handshake and **reused after a disconnect**. Keep the pid, not the name, while a player is on; check `IsPlayerConnected(pid)` before trusting a pid kept across ticks | | **`id`** | a world entity - a horse, a pickup, a prop, an NPC actor, a dog: the protocol's net id, unique while it lives, `nil` from every getter once it is gone | | **positions** | metres in the level's world space, as the game's own console reports them (`GetPlayerPos` ↔ the game's `pos`). `z < 0` when spawning or teleporting means "on the terrain" | | **yaw** | degrees, `0` = facing +Y, counter-clockwise (the game's convention) | | **colours** | `0xRRGGBBAA` - `0xFF0000FF` is opaque red; the [constants](/lua/server/constants/) name the usual ones | | **time** | `GetServerTime()` in milliseconds; timers in milliseconds; the world clock in hours (`13.5` = 13:30) | | **strings** | UTF-8; chat lines and names as the players typed them | | **keys of game things** | items, souls, buffs and meshes are named by **id, name or GUID** from [the reference lists](/reference/); a call given an unknown key fails quietly (`nil`, `false`) and logs why | A function that reads a player who is not connected returns `nil` (positions, names) or a neutral value (`-1` for a ping); one that acts on them returns `false`. Nothing raises an error for a bad id. ## When a script fails - A **runtime error** inside a callback is logged (`[lua] error in OnPlayerText: ...`, the first fifty in full, then counted) and that callback's effect is skipped - the server keeps running, the player keeps playing. - A **syntax error** or an error while the script loads stops the server at **startup** with the message, so a broken mode is found before players join. On a **reload** the same error leaves the built-in freeroam in charge until the next reload (`game mode: x.lua failed to load (...); the built-in freeroam runs until the next reload`). - `Log(...)` writes to the server log with a `[lua]` prefix; `print` is the same function. ## Your editor The server folder's `sdk/KcdMp.d.lua` describes this whole API - every function, callback and constant, with its documentation and types - for the Lua language server: completion as you type, the page's text on hover, and a warning for a name that does not exist or an argument of the wrong type, before the server ever runs the script. In VS Code install the "Lua" extension (sumneko / LuaLS) and open the `gamemodes` folder - it comes with a `.luarc.json` that points the language server at the file. For a mode in a folder of its own, put a `.luarc.json` next to the script: ```json { "runtime.version": "Lua 5.4", "workspace.library": ["../../sdk"] } ``` or copy `KcdMp.d.lua` into the folder. A coding assistant working in that folder reads the same file, so it knows the API instead of guessing at it ([AI assistants](/getting-started/ai-assistants/) has a `CLAUDE.md` to start from); `sdk/KcdMp-client.d.lua` is the same for a [client script](/lua/client/). Other editors and the C# side: [Setting up](/getting-started/setting-up/#9-your-editor). ## Where next The [Server API index](/lua/server/) lists every callback and function by topic, each with its own page; the [Combat guide](/lua/server/combat/) explains the model behind the combat callbacks; [Constants](/lua/server/constants/) lists every constant. The keys that name game things - items, souls, buffs, meshes, presets, clips, doors - are in [the reference](/reference/). # Server API > Every callback and function a Lua game mode has, by topic, each with its own page - syntax, arguments, return value and an example. A game mode is a Lua script the server runs: it defines the **callbacks** it cares about (`OnPlayerConnect`, `OnPlayerDamage` ...) and calls the **functions** below to act. Every name here has its own page with the syntax, the arguments and their types, what it returns and an example. New to it? Read the guides first, then come back to the index. The keys that name game things - items, souls, buffs, meshes, presets, clips - are listed in [the reference](/reference/). | Guide | | |---|---| | [Getting started](/lua/server/getting-started/) | what a game mode is, running one, the tick, ids and units, what happens on an error | | [Combat](/lua/server/combat/) | how a swing or a shot becomes damage, stamina, injuries, fights, teams - the model behind the combat callbacks | | [Constants](/lua/server/constants/) | every constant the API defines - colours, body parts, entity kinds, HUD alignments, the pose aliases | | [Parties](/lua/server/parties/) | parties with a leader, frames and invitations - what the server does by itself and the callbacks and functions a mode builds its party commands around | | Topic | | |---|---| | [Server and timers](#server-and-timers) | 3 callbacks, 10 functions | | [Players](#players) | 4 callbacks, 30 functions | | [Chat and commands](#chat-and-commands) | 2 callbacks, 3 functions | | [Vitals, stats and skills](#vitals-stats-and-skills) | 17 functions | | [Combat](#combat) | 5 callbacks, 5 functions | | [Buffs and the drink](#buffs-and-the-drink) | 2 callbacks, 10 functions | | [Items and inventory](#items-and-inventory) | 2 callbacks, 4 functions | | [GameText and HUD](#gametext-and-hud) | 16 functions | | [Effects and sounds](#effects-and-sounds) | 3 functions | | [Script events](#script-events) | 1 callback, 2 functions | | [State bags](#state-bags) | 9 functions | | [Storage and persistence](#storage-and-persistence) | 9 functions | | [World entities](#world-entities) | 14 functions | | [Horses](#horses) | 2 callbacks, 4 functions | | [Props](#props) | 5 functions | | [Dogs](#dogs) | 4 functions | | [NPC actors](#npc-actors) | 5 callbacks, 15 functions | | [Zones](#zones) | 2 callbacks, 11 functions | | [The world - clock, weather, terrain, the navmesh, the geometry](#the-world---clock-weather-terrain-the-navmesh-the-geometry) | 20 functions | | [Doors and containers](#doors-and-containers) | 3 callbacks, 7 functions | | [Accounts, admins, bans and the audit](#accounts-admins-bans-and-the-audit) | 2 callbacks, 11 functions | | [Catalogues](#catalogues) | 10 functions | | [Parties](#parties) | 7 callbacks, 23 functions | ## Server and timers The mode's own lifecycle, the server's facts, timers and the log. Everything a mode does happens on the simulation thread, one tick at a time, thirty times a second - the callbacks run inside a tick, the timers run in the tick they fall due, and a slow callback delays the tick for every player ([Getting started](/lua/server/getting-started/#the-tick)). | Callback | When | |---|---| | [`OnGameModeInit`](/lua/server/callbacks/ongamemodeinit/) | The script is loaded and the API is ready - the place to create zones, HUD texts, timers and actors. | | [`OnGameModeExit`](/lua/server/callbacks/ongamemodeexit/) | The server shuts down or the mode is about to be reloaded. | | [`OnTick`](/lua/server/callbacks/ontick/) | Every simulation tick, with the time since the last one. | | Function | What it does | |---|---| | [`SetGameModeText`](/lua/server/functions/setgamemodetext/) | Names the mode in the server log and the server browser. | | [`GetServerTick`](/lua/server/functions/getservertick/) | The number of the simulation tick being processed. | | [`GetServerTime`](/lua/server/functions/getservertime/) | The server's clock in milliseconds. | | [`GetMaxPlayers`](/lua/server/functions/getmaxplayers/) | How many players the server holds (`[server] max_players`). | | [`GetLevel`](/lua/server/functions/getlevel/) | The name of the level the server runs. | | [`GetLevelName`](/lua/server/functions/getlevelname/) | The level as a player reads it. | | [`Log`](/lua/server/functions/log/) | Writes a line to the server log, prefixed `[lua]`. | | [`SetTimer`](/lua/server/functions/settimer/) | Calls a function after a delay, once or repeatedly. | | [`KillTimer`](/lua/server/functions/killtimer/) | Stops a timer. | | [`ReloadGameMode`](/lua/server/functions/reloadgamemode/) | Reloads this mode at the end of the tick, without restarting the server. | ## Players A player is a `pid` from `0` to `GetMaxPlayers() - 1`, given at the handshake and **reused after a disconnect**: keep the pid while a player is on, and check [`IsPlayerConnected`](/lua/server/functions/isplayerconnected/) before trusting a pid kept across ticks. Readers return `nil` for a pid that is not connected; setters return `false`. Positions are metres, yaw is degrees (`0` = facing +Y, counter-clockwise); a mounted player's position and velocity are the horse's. | Callback | When | |---|---| | [`OnPlayerConnect`](/lua/server/callbacks/onplayerconnect/) | The handshake is done and the client is loading the level. | | [`OnPlayerRequestSpawn`](/lua/server/callbacks/onplayerrequestspawn/) | The client's level is ready - decide where the player spawns, or hold them. | | [`OnPlayerSpawn`](/lua/server/callbacks/onplayerspawn/) | The player stands in the world and the others see them. | | [`OnPlayerDisconnect`](/lua/server/callbacks/onplayerdisconnect/) | The player is gone. | | Function | What it does | |---|---| | [`GetPlayers`](/lua/server/functions/getplayers/) | Everyone who passed the handshake, in join order. | | [`GetPlayerCount`](/lua/server/functions/getplayercount/) | How many players are connected. | | [`GetPlayerName`](/lua/server/functions/getplayername/) | The player's name, as they joined. | | [`GetPlayerId`](/lua/server/functions/getplayerid/) | The player a command names - a pid, a name or a fragment of one - or `nil`. | | [`IsPlayerConnected`](/lua/server/functions/isplayerconnected/) | Whether a pid belongs to a connected player. | | [`IsPlayerInWorld`](/lua/server/functions/isplayerinworld/) | Whether the player is spawned and replicated. | | [`GetPlayerPing`](/lua/server/functions/getplayerping/) | The player's round trip to the server in milliseconds. | | [`GetPlayerIP`](/lua/server/functions/getplayerip/) | The player's address. | | [`GetPlayerPos`](/lua/server/functions/getplayerpos/) | The player's position of record. | | [`GetPlayerYaw`](/lua/server/functions/getplayeryaw/) | The direction the player faces, in degrees. | | [`GetPlayerVelocity`](/lua/server/functions/getplayervelocity/) | The player's velocity in metres per second. | | [`SetPlayerPos`](/lua/server/functions/setplayerpos/) | Moves the player's game to a point - a teleport. | | [`SetSpawnInfo`](/lua/server/functions/setspawninfo/) | Where and as what the player's next spawn happens. | | [`SpawnPlayer`](/lua/server/functions/spawnplayer/) | Spawns - or respawns - the player at their SetSpawnInfo point. | | [`GetDefaultSpawn`](/lua/server/functions/getdefaultspawn/) | The server's spawn point from server.toml. | | [`AddSpawnPoint`](/lua/server/functions/addspawnpoint/) | Remembers a spawn point under a tag. | | [`GetSpawnPoints`](/lua/server/functions/getspawnpoints/) | The spawn points of a tag. | | [`GetRandomSpawnPoint`](/lua/server/functions/getrandomspawnpoint/) | One spawn point of a tag, at random. | | [`ClearSpawnPoints`](/lua/server/functions/clearspawnpoints/) | Forgets the spawn points of a tag. | | [`TogglePlayerControllable`](/lua/server/functions/toggleplayercontrollable/) | Holds or releases the player's keyboard. | | [`IsPlayerControllable`](/lua/server/functions/isplayercontrollable/) | Whether the player's keyboard is theirs right now. | | [`Kick`](/lua/server/functions/kick/) | Disconnects the player with a reason. | | [`SetPlayerNameplate`](/lua/server/functions/setplayernameplate/) | The label over the player's body on every other screen. | | [`GetPlayerNameplate`](/lua/server/functions/getplayernameplate/) | The label as the mode set it. | | [`SetPlayerColour`](/lua/server/functions/setplayercolour/) | The colour of the player's label and of their name in the Tab roster. | | [`SetPlayerColor`](/lua/server/functions/setplayercolor/) | the same as `SetPlayerColour` | | [`GetPlayerColour`](/lua/server/functions/getplayercolour/) | The player's colour as set. | | [`GetPlayerColor`](/lua/server/functions/getplayercolor/) | the same as `GetPlayerColour` | | [`SetPlayerTeam`](/lua/server/functions/setplayerteam/) | Puts the player in a team - teammates cannot hurt each other. | | [`GetPlayerTeam`](/lua/server/functions/getplayerteam/) | The player's team. | | [`GetPlayerVirtualWorld`](/lua/server/functions/getplayervirtualworld/) | The virtual world the player is in. | | [`SetPlayerVirtualWorld`](/lua/server/functions/setplayervirtualworld/) | Moves the player into another virtual world. | ## Chat and commands Every chat line a player types passes through the mode before anyone sees it: a plain line through [`OnPlayerText`](/lua/server/callbacks/onplayertext/), a `/` line through [`OnPlayerCommandText`](/lua/server/callbacks/onplayercommandtext/). A `/` line the mode does not answer goes to the server's own [built-in commands](/reference/chat-commands/) (`/help`, `/pos`, `/give`, `/tp`, `/horse` ...), then to `Unknown command`; a mode overrides a built-in by handling its name. `/register`, `/login`, `/fight` and `/peace` are the server's and are answered before the mode sees them. The mode's own lines go out with [`SendClientMessage`](/lua/server/functions/sendclientmessage/) and [`SendClientMessageToAll`](/lua/server/functions/sendclientmessagetoall/). | Callback | When | |---|---| | [`OnPlayerText`](/lua/server/callbacks/onplayertext/) | A plain chat line - return `false` and nobody sees it. | | [`OnPlayerCommandText`](/lua/server/callbacks/onplayercommandtext/) | A `/` command - return `true` when the mode answered it. | | Function | What it does | |---|---| | [`sscanf`](/lua/server/functions/sscanf/) | The arguments of a command as typed values - a player, a number, a word, the rest of the line - in one call. | | [`SendClientMessage`](/lua/server/functions/sendclientmessage/) | A line in one player's chat. | | [`SendClientMessageToAll`](/lua/server/functions/sendclientmessagetoall/) | The same line in everyone's chat. | ## Vitals, stats and skills The server owns every player's **health, stamina, injuries and bleeding** (`[combat]` in `server.toml`; the [Combat guide](/lua/server/combat/) has how a hit becomes damage). Health and stamina are full at every spawn; `0` health is dead until the respawn. Stats and skills are the game's own character levels, raised by the server and kept on the record. | Function | What it does | |---|---| | [`GetPlayerHealth`](/lua/server/functions/getplayerhealth/) | The player's health. | | [`GetPlayerMaxHealth`](/lua/server/functions/getplayermaxhealth/) | The player's maximum health (100). | | [`SetPlayerHealth`](/lua/server/functions/setplayerhealth/) | Sets the player's health; 0 kills. | | [`IsPlayerDead`](/lua/server/functions/isplayerdead/) | Whether the player's health is 0 and they wait for the respawn. | | [`GetPlayerStamina`](/lua/server/functions/getplayerstamina/) | The player's stamina - the bar they see. | | [`GetPlayerMaxStamina`](/lua/server/functions/getplayermaxstamina/) | The player's maximum stamina (`[combat] max_stamina`). | | [`SetPlayerStamina`](/lua/server/functions/setplayerstamina/) | Sets the player's stamina. | | [`GetPlayerInjuries`](/lua/server/functions/getplayerinjuries/) | The player's injured body parts. | | [`IsPlayerInjured`](/lua/server/functions/isplayerinjured/) | Whether the player has an injury - anywhere, or on one part. | | [`GetBodyPartName`](/lua/server/functions/getbodypartname/) | The name of a body part id. | | [`GetPlayerBleeding`](/lua/server/functions/getplayerbleeding/) | How fast the player is bleeding, in health per second. | | [`IsPlayerBleeding`](/lua/server/functions/isplayerbleeding/) | Whether the player is bleeding. | | [`HealPlayer`](/lua/server/functions/healplayer/) | Makes the player whole - health, stamina, injuries, bleeding, buffs, drink. | | [`SetPlayerStat`](/lua/server/functions/setplayerstat/) | Raises a core stat of the player's character to a level. | | [`SetPlayerSkill`](/lua/server/functions/setplayerskill/) | Raises a skill of the player's character to a level. | | [`GetPlayerStat`](/lua/server/functions/getplayerstat/) | The level of record of a core stat. | | [`GetPlayerSkill`](/lua/server/functions/getplayerskill/) | The level of record of a skill. | ## Combat A player's game only reports what its swing or its arrow hit; the server decides what that did and tells the mode. The [Combat guide](/lua/server/combat/) walks through the model - the tables, stamina, injuries and bleeding, fights and the lock-on, teams and pvp. The callbacks let a mode change or cancel every hit; the functions manage fights. | Callback | When | |---|---| | [`OnPlayerDamage`](/lua/server/callbacks/onplayerdamage/) | The server accepted a hit on a player - change the damage, cancel it, or let it through. | | [`OnPlayerInjury`](/lua/server/callbacks/onplayerinjury/) | A hit injured one of the player's body parts. | | [`OnPlayerDeath`](/lua/server/callbacks/onplayerdeath/) | The player's health reached 0. | | [`OnFightStart`](/lua/server/callbacks/onfightstart/) | Two players are in a fight from now on. | | [`OnFightEnd`](/lua/server/callbacks/onfightend/) | A fight between two players is over. | | Function | What it does | |---|---| | [`StartFight`](/lua/server/functions/startfight/) | Puts two players in a fight so their games can lock on to each other. | | [`EndFight`](/lua/server/functions/endfight/) | Ends the fight between two players. | | [`AreFighting`](/lua/server/functions/arefighting/) | Whether two players are in a fight right now. | | [`GetPlayerOpponents`](/lua/server/functions/getplayeropponents/) | Everyone the player is fighting right now. | | [`GetPlayerWeapon`](/lua/server/functions/getplayerweapon/) | The weapon the damage model charges the player's hits to. | ## Buffs and the drink A **buff** is the game's own timed or permanent modifier on a character - a potion's effect, an injury, drunkenness, a perk's bonus. The server gives and takes them by **id, name or GUID** from [the buff list](/reference/buffs/); the player's client adds the game's buff once and removes it by GUID. The server also keeps a **blood-alcohol level** per player from the drinks their game consumed, and judges when they are drunk. A player's game consuming anything - a potion, food, an ointment - goes through the server ([`OnPlayerUseItem`](/lua/server/callbacks/onplayeruseitem/)), which applies the tables' effect ([Consumables](/reference/consumables/)). | Callback | When | |---|---| | [`OnPlayerUseItem`](/lua/server/callbacks/onplayeruseitem/) | The player's game consumed an item - the server is about to apply its effect; return `false` to cancel. | | [`OnPlayerDrunk`](/lua/server/callbacks/onplayerdrunk/) | The player got drunk, or sobered up. | | Function | What it does | |---|---| | [`GivePlayerBuff`](/lua/server/functions/giveplayerbuff/) | Gives the player a buff of the game's tables. | | [`RemovePlayerBuff`](/lua/server/functions/removeplayerbuff/) | Takes a buff off the player. | | [`HasPlayerBuff`](/lua/server/functions/hasplayerbuff/) | Whether the server gave the player this buff and has not taken it back. | | [`GetPlayerBuffs`](/lua/server/functions/getplayerbuffs/) | The buffs the server gave the player, as GUIDs. | | [`ClearPlayerBuffs`](/lua/server/functions/clearplayerbuffs/) | Takes every server-given buff off the player. | | [`GetClaimedBuffClasses`](/lua/server/functions/getclaimedbuffclasses/) | The buff classes the server has claimed. | | [`ClaimBuffClasses`](/lua/server/functions/claimbuffclasses/) | Names the buff classes the server takes over from the game. | | [`GetPlayerAlcohol`](/lua/server/functions/getplayeralcohol/) | The player's blood-alcohol level, 0 to 1. | | [`IsPlayerDrunk`](/lua/server/functions/isplayerdrunk/) | Whether the player is drunk. | | [`SetPlayerAlcohol`](/lua/server/functions/setplayeralcohol/) | Sets the player's blood-alcohol level; the drunk state is judged at once. | ## Items and inventory What a player carries, what the server gives them, and the pickups lying in the world. An item is named by any key of [the item catalogue](/reference/items/) - the id, the game's name, the English name or the class GUID; the client reports equipment and inventory as class GUIDs ([`GetItemName`](/lua/server/functions/getitemname/) turns one into a name). Items the server hands out - the spawn outfit, `GivePlayerItem`, a pickup taken, a take from a chest - are the ones the [inventory audit](/lua/server/callbacks/onplayerauditviolation/) can explain. | Callback | When | |---|---| | [`OnPlayerPickup`](/lua/server/callbacks/onplayerpickup/) | The player picked a pickup up - return `false` to take it back. | | [`OnPlayerDrop`](/lua/server/callbacks/onplayerdrop/) | The player dropped an item and the world made a pickup of it. | | Function | What it does | |---|---| | [`GetPlayerEquipment`](/lua/server/functions/getplayerequipment/) | What the player's client reports as equipped - clothing, armour, the weapons in the slots. | | [`GetPlayerInventory`](/lua/server/functions/getplayerinventory/) | The player's whole inventory as their client last reported it. | | [`GivePlayerItem`](/lua/server/functions/giveplayeritem/) | Puts items in the player's inventory - or takes them out. | | [`CreatePickup`](/lua/server/functions/createpickup/) | Puts an item on the ground for everyone to see and anyone to take. | ## GameText and HUD Two ways to put text on a player's screen besides the chat: a **GameText** - one big line for a moment ("Round 3", "You win", a subtitle) - and a **HUD text** - a line the mode places at a fraction of the screen and keeps there, changing it whenever (a clock, a score, a timer). Both draw under the game's own menus and vanish behind the loading screen. For anything richer a [client script](/lua/server/functions/sendclientevent/) draws it. | Function | What it does | |---|---| | [`GameText`](/lua/server/functions/gametext/) | One big line on the player's screen for a while. | | [`GameTextForAll`](/lua/server/functions/gametextforall/) | One big line on every screen. | | [`CreateHudText`](/lua/server/functions/createhudtext/) | A line of text at a screen position, shown to the players you choose. | | [`DestroyHudText`](/lua/server/functions/destroyhudtext/) | Removes a HUD text from every screen. | | [`SetHudText`](/lua/server/functions/sethudtext/) | Changes a HUD text's text. | | [`GetHudText`](/lua/server/functions/gethudtext/) | A HUD text's current text. | | [`SetHudTextPos`](/lua/server/functions/sethudtextpos/) | Moves a HUD text. | | [`SetHudTextColour`](/lua/server/functions/sethudtextcolour/) | Recolours a HUD text. | | [`SetHudTextScale`](/lua/server/functions/sethudtextscale/) | Resizes a HUD text. | | [`SetHudTextAlign`](/lua/server/functions/sethudtextalign/) | Changes which side of a HUD text sits at its x. | | [`ShowHudText`](/lua/server/functions/showhudtext/) | Shows a HUD text on one player's screen. | | [`HideHudText`](/lua/server/functions/hidehudtext/) | Takes a HUD text off one player's screen. | | [`ShowHudTextForAll`](/lua/server/functions/showhudtextforall/) | Shows a HUD text to everyone connected now. | | [`HideHudTextForAll`](/lua/server/functions/hidehudtextforall/) | Takes a HUD text off every screen (the element stays for later). | | [`IsHudTextShown`](/lua/server/functions/ishudtextshown/) | Whether a HUD text is on a player's screen. | | [`GetHudTexts`](/lua/server/functions/gethudtexts/) | Every HUD text the mode has made. | ## Effects and sounds One-shot things at a point in the world for everyone nearby: a **particle effect** of the game's own libraries (smoke, fire, sparks), a **decal** on the ground or a wall, a **sound** from the game's audio triggers. They reach the players within `[effects] range` metres (150; `0` = everyone in that virtual world) and are fire-and-forget - a player who arrives later sees and hears nothing. Each returns how many players got it. A name the game does not know is not an error on the server: it only warns in the clients' logs. | Function | What it does | |---|---| | [`SpawnEffect`](/lua/server/functions/spawneffect/) | Plays one of the game's particle effects at a point for everyone nearby. | | [`SpawnDecal`](/lua/server/functions/spawndecal/) | Puts a decal of a material on whatever is at a point. | | [`PlaySound`](/lua/server/functions/playsound/) | Plays one of the game's sounds at a point for everyone nearby. | ## Script events A mode that needs something on the client the server cannot draw - a marker in the world, a sound, a bit of UI, a value read from the game - keeps a [client script](/lua/client/) in the `client/` folder next to itself (the server sends it to every player who joins) and talks to it through **named events with a string payload**, both ways: `SendClientEvent` down, `KcdMp.send_event` up into [`OnClientEvent`](/lua/server/callbacks/onclientevent/). The payload is whatever string the two halves agree on - a number, a comma list, JSON. For values every client should simply *know* - a team, a round, a flag carrier - the [state bags](/lua/server/functions/setglobalstate/) are the better fit. The `marker` example mode in the server folder is the round trip whole. | Callback | When | |---|---| | [`OnClientEvent`](/lua/server/callbacks/onclientevent/) | A player's client script sent an event. | | Function | What it does | |---|---| | [`SendClientEvent`](/lua/server/functions/sendclientevent/) | A named event with a string payload to one player's client script. | | [`SendClientEventToAll`](/lua/server/functions/sendclienteventtoall/) | The same event to every connected client. | ## State bags String keys and values the mode sets on the **world**, a **player** or an **entity**, and **every client's script reads** - `KcdMp.state.global[key]`, `KcdMp.state.player[pid][key]`, `KcdMp.state.entity[id][key]`, with a change hook on each ([the client API](/lua/client/)). The way a mode's client half learns a team, a round, a marker, a flag carrier without a script event per client: the global and the players' bags reach every client from its join on, an entity's follows its spawn to whoever sees it. Numbers and booleans become strings; `nil` removes a key. Nothing is persisted - a player's bag goes with the session, an entity's with the entity, all of them with a reload. Limits: a key of 1-48 characters, a value of at most 1 KB, 64 keys a bag (a set beyond them returns `false` and logs). The mode's *private* storage is [`SetPlayerData`](/lua/server/functions/setplayerdata/) / [`SetEntityData`](/lua/server/functions/setentitydata/). | Function | What it does | |---|---| | [`SetGlobalState`](/lua/server/functions/setglobalstate/) | Sets a key of the world's bag, read by every client. | | [`GetGlobalState`](/lua/server/functions/getglobalstate/) | A key of the world's bag. | | [`GetGlobalStates`](/lua/server/functions/getglobalstates/) | The whole world bag. | | [`SetPlayerState`](/lua/server/functions/setplayerstate/) | Sets a key of a player's bag, read by every client. | | [`GetPlayerState`](/lua/server/functions/getplayerstate/) | A key of a player's bag. | | [`GetPlayerStates`](/lua/server/functions/getplayerstates/) | A player's whole bag. | | [`SetEntityState`](/lua/server/functions/setentitystate/) | Sets a key of an entity's bag, read by every client that sees the entity. | | [`GetEntityState`](/lua/server/functions/getentitystate/) | A key of an entity's bag. | | [`GetEntityStates`](/lua/server/functions/getentitystates/) | An entity's whole bag. | ## Storage and persistence Three places to keep a value, by how long it should live. **Data** (`SetPlayerData`, `SetEntityData`, [`SetZoneData`](/lua/server/functions/setzonedata/)) is the mode's private bag on a player, an entity or a zone - any Lua value, gone with the player's session, the entity or a reload; nothing leaves the server. **Saved data** is written to the player's **record** under their name (`[persistence] file`, `data/players.json`) and is there on their next visit, next to the visits, the play time and the last position the server keeps by itself. **Server data** is one key/value store for the mode, persisted in `data/server.json`. What every *client* should read is the [state bags](/lua/server/functions/setglobalstate/) instead. | Function | What it does | |---|---| | [`SetPlayerData`](/lua/server/functions/setplayerdata/) | Stores a value on the player, private to the server, for the session. | | [`GetPlayerData`](/lua/server/functions/getplayerdata/) | A value stored on the player with SetPlayerData. | | [`SetEntityData`](/lua/server/functions/setentitydata/) | Stores a value on a world entity, private to the server. | | [`GetEntityData`](/lua/server/functions/getentitydata/) | A value stored on an entity with SetEntityData. | | [`GetSavedPlayer`](/lua/server/functions/getsavedplayer/) | What the server remembers about the player's name between visits. | | [`GetSavedData`](/lua/server/functions/getsaveddata/) | A value the mode saved on the player's name. | | [`SetSavedData`](/lua/server/functions/setsaveddata/) | Saves a value on the player's name - it is there on their next visit. | | [`GetServerData`](/lua/server/functions/getserverdata/) | A value of the server-wide store. | | [`SetServerData`](/lua/server/functions/setserverdata/) | Saves a value in the server-wide store (data/server.json). | ## World entities A **world entity** is something the server owns and every client in range sees: a horse (`ENTITY_HORSE`), a pickup (`ENTITY_ITEM`), an NPC actor (`ENTITY_NPC`), a prop (`ENTITY_PROP`), a dog (`ENTITY_DOG`) - the [kinds](/lua/server/constants/#entity-kinds). Its `id` is unique while it lives and `nil` from every reader once it is gone. A horse is simulated by its **controller** - the client of the player who rides or minds it - and carries at most one **rider**; a loose horse is handed to the nearest player within 30 m once a second. Entities live within a [virtual world](/lua/server/functions/setplayervirtualworld/). These are the calls every kind shares; [horses](/lua/server/functions/createhorse/), [pickups](/lua/server/functions/createpickup/), [props](/lua/server/functions/createprop/), [dogs](/lua/server/functions/createdog/) and [actors](/lua/server/functions/createactor/) have their own. | Function | What it does | |---|---| | [`GetEntities`](/lua/server/functions/getentities/) | Every entity in the world, or every entity of one kind. | | [`GetEntityPos`](/lua/server/functions/getentitypos/) | An entity's position and heading. | | [`SetEntityPos`](/lua/server/functions/setentitypos/) | Moves an entity. | | [`GetEntityKind`](/lua/server/functions/getentitykind/) | What an entity is. | | [`GetEntityTemplate`](/lua/server/functions/getentitytemplate/) | What an entity is made of - the item class, the soul, the mesh path. | | [`GetEntityName`](/lua/server/functions/getentityname/) | An NPC actor's label; empty for everything else. | | [`DestroyEntity`](/lua/server/functions/destroyentity/) | Removes an entity from the world, for everyone. | | [`GetEntityController`](/lua/server/functions/getentitycontroller/) | The player whose client simulates the entity. | | [`SetEntityController`](/lua/server/functions/setentitycontroller/) | Hands the simulation of an entity to a player, or to nobody. | | [`GetEntityRider`](/lua/server/functions/getentityrider/) | The player in the saddle of a horse. | | [`GetEntityIdleTime`](/lua/server/functions/getentityidletime/) | Seconds since the entity's pose was last reported. | | [`GetEntityVirtualWorld`](/lua/server/functions/getentityvirtualworld/) | The virtual world the entity is replicated in. | | [`SetEntityVirtualWorld`](/lua/server/functions/setentityvirtualworld/) | Moves an entity into another virtual world. | | [`GetNearestEntity`](/lua/server/functions/getnearestentity/) | The entity nearest to a player, of a kind, within a radius. | ## Horses A horse is a world entity of `ENTITY_HORSE` simulated by its **controller** - the client of the player who rides or minds it; the others see a puppet following its pose. Its **soul** is the breed, a key of the Horse archetype of [the souls](/reference/souls/). Players get a horse with the `/horse` built-in (an admin command by default); a mode gives one with [`CreateHorse`](/lua/server/functions/createhorse/) and puts a player in the saddle with [`MountPlayer`](/lua/server/functions/mountplayer/). A mounted player's position and velocity are the horse's. | Callback | When | |---|---| | [`OnPlayerMount`](/lua/server/callbacks/onplayermount/) | The player is in the saddle of a horse. | | [`OnPlayerDismount`](/lua/server/callbacks/onplayerdismount/) | The player got off the horse - or left while riding, or the horse was destroyed. | | Function | What it does | |---|---| | [`CreateHorse`](/lua/server/functions/createhorse/) | Puts a horse in the world. | | [`MountPlayer`](/lua/server/functions/mountplayer/) | Puts a player in the saddle of a horse. | | [`GetPlayerMount`](/lua/server/functions/getplayermount/) | The horse the player rides right now. | | [`GetPlayerHorse`](/lua/server/functions/getplayerhorse/) | The horse the player rides, or else the newest one they control. | ## Props A **prop** is a static mesh of the game's object files placed in the world for everyone in range to see - a barrel, a fence, a table, a stone - like a pickup nobody can take. The mesh is a key of [the mesh list](/reference/meshes/): the id, the file's name (`barrel_a`, when only one file carries it) or the path. A static prop stands where it is placed and blocks the way; a **rigid** one is a physics body on each client - pushable, but its motion is not synchronised, so a barrel one player kicks stays put for the others. The `/prop` and `/props` built-ins place and search them. | Function | What it does | |---|---| | [`CreateProp`](/lua/server/functions/createprop/) | Places a static mesh in the world. | | [`GetMeshPath`](/lua/server/functions/getmeshpath/) | The path a mesh key stands for. | | [`FindMeshes`](/lua/server/functions/findmeshes/) | Meshes whose path holds every word of a pattern. | | [`GetEntityScale`](/lua/server/functions/getentityscale/) | A prop's scale. | | [`IsEntityRigid`](/lua/server/functions/isentityrigid/) | Whether a prop is a physics body. | ## Dogs A player's **dog**: a world entity of `ENTITY_DOG` whose controller is its master for life. On the master's screen it is the game's own companion - it follows, waits or roams on the game's dog AI, it can be praised - and everyone in range sees the same dog following them. One dog per player; it goes with the master's disconnect or [`DestroyEntity`](/lua/server/functions/destroyentity/). The `/dog` built-in gives the caller one (and sends it away on the second call); `/dog stay`, `/dog follow` and `/dog free` set its mode. The mode is the dog's state bag key `mode` ([`GetEntityState`](/lua/server/functions/getentitystate/)), a number of the game's own list: `DOG_STAY` 0, `DOG_FOLLOW` 1 (the default), `DOG_FREE` 2, `DOG_AGGRESSIVE` 3, `DOG_SEARCH` 4, `DOG_HUNT` 5, `DOG_GUARD` 6, `DOG_AMBUSH` 7. Stay, follow and free are the tested ones. | Function | What it does | |---|---| | [`CreateDog`](/lua/server/functions/createdog/) | Gives a player a dog that follows them. | | [`GetPlayerDog`](/lua/server/functions/getplayerdog/) | The player's dog. | | [`SetDogMode`](/lua/server/functions/setdogmode/) | Tells a dog to stay, follow or roam. | | [`GetDogMode`](/lua/server/functions/getdogmode/) | A dog's mode. | ## NPC actors An **NPC actor** is a dressed, named human body the server owns outright - a guard, a merchant, an arena opponent, a crowd - without the game's own AI. The mode creates it, walks it in straight lines, poses it and sets it on a player; it takes hits, dies and fights back. Its `id` is a world entity of `ENTITY_NPC`: [`GetEntityPos`](/lua/server/functions/getentitypos/), [`GetEntityName`](/lua/server/functions/getentityname/), [`SetEntityState`](/lua/server/functions/setentitystate/) and [`DestroyEntity`](/lua/server/functions/destroyentity/) work on it. Its look is a soul of [the souls](/reference/souls/), its clothes and arms are [clothing](/reference/clothing-presets/) and [weapon presets](/reference/weapon-presets/), its poses are clips of [the animation list](/reference/animations/). It fights like a player: an armed actor raises its guard against a swing part of the time (`[actors] block_chance`, `block_hold`), a heavy blow wounds the part it hits, a cut bleeds, a bleed-out kills it. `[actors]` in `server.toml` tunes how it fights. Not yet: paths around obstacles (a straight line through a wall stops at the wall), riding. | Callback | When | |---|---| | [`OnActorArrive`](/lua/server/callbacks/onactorarrive/) | An actor reached its MoveActor target. | | [`OnActorDamage`](/lua/server/callbacks/onactordamage/) | A player hit an actor - change the damage, cancel it, or let it through. | | [`OnActorInjury`](/lua/server/callbacks/onactorinjury/) | A hit wounded one of an actor's body parts. | | [`OnActorDeath`](/lua/server/callbacks/onactordeath/) | An actor's health reached 0. | | [`OnActorAttack`](/lua/server/callbacks/onactorattack/) | An actor's blow landed on its opponent - change the damage, cancel it, or let it through. | | Function | What it does | |---|---| | [`CreateActor`](/lua/server/functions/createactor/) | Creates an NPC actor - a dressed, named body the server owns. | | [`MoveActor`](/lua/server/functions/moveactor/) | Walks an actor to a point - around the walls when the server has the navigation mesh. | | [`StopActor`](/lua/server/functions/stopactor/) | Stops an actor where it is. | | [`TurnActor`](/lua/server/functions/turnactor/) | Turns a standing actor to face a direction. | | [`IsActorMoving`](/lua/server/functions/isactormoving/) | Whether an actor is on its way to a MoveActor target. | | [`SetActorAnim`](/lua/server/functions/setactoranim/) | Puts a pose on a standing actor - a clip of the game's animation set. | | [`GetActorHealth`](/lua/server/functions/getactorhealth/) | An actor's health. | | [`SetActorHealth`](/lua/server/functions/setactorhealth/) | Sets an actor's health; 0 kills it. | | [`IsActorDead`](/lua/server/functions/isactordead/) | Whether an actor is a corpse. | | [`HealActor`](/lua/server/functions/healactor/) | Makes an actor whole - full health, no wounds, no bleeding. | | [`GetActorInjuries`](/lua/server/functions/getactorinjuries/) | An actor's wounded body parts. | | [`IsActorInjured`](/lua/server/functions/isactorinjured/) | Whether an actor has a wound - anywhere, or on one part. | | [`GetActorBleeding`](/lua/server/functions/getactorbleeding/) | How fast an actor is bleeding, in health per second. | | [`IsActorBleeding`](/lua/server/functions/isactorbleeding/) | Whether an actor is bleeding. | | [`SetActorHostile`](/lua/server/functions/setactorhostile/) | Sets an actor on a player - or stands it down. | ## Zones A **zone** is a region the server watches for the mode: a box between two corners, or a circle around a point with any height unless a `zMin`/`zMax` band is given. Once per tick every player in the world is tested against every zone and the mode hears [`OnPlayerEnterZone`](/lua/server/callbacks/onplayerenterzone/) and [`OnPlayerLeaveZone`](/lua/server/callbacks/onplayerleavezone/) on the edges. Ids start at `1` and are reused after a destroy; there are 4096. A zone has a private data bag ([`SetZoneData`](/lua/server/functions/setzonedata/)). Zones go with a reload. | Callback | When | |---|---| | [`OnPlayerEnterZone`](/lua/server/callbacks/onplayerenterzone/) | A player's position of record entered a zone. | | [`OnPlayerLeaveZone`](/lua/server/callbacks/onplayerleavezone/) | A player left a zone - walked or was moved out, despawned, respawned elsewhere, disconnected. | | Function | What it does | |---|---| | [`CreateZone`](/lua/server/functions/createzone/) | A box zone between two corners. | | [`CreateCircleZone`](/lua/server/functions/createcirclezone/) | A circular zone around a point - a cylinder of any height, or of a band. | | [`DestroyZone`](/lua/server/functions/destroyzone/) | Removes a zone. | | [`IsPlayerInZone`](/lua/server/functions/isplayerinzone/) | Whether the player is inside a zone, as of the last tick's test. | | [`IsPointInZone`](/lua/server/functions/ispointinzone/) | Whether a point lies inside a zone. | | [`GetZonePlayers`](/lua/server/functions/getzoneplayers/) | The players inside a zone right now. | | [`GetPlayerZones`](/lua/server/functions/getplayerzones/) | The zones a player is inside right now. | | [`GetZones`](/lua/server/functions/getzones/) | Every zone the mode has made. | | [`GetZoneInfo`](/lua/server/functions/getzoneinfo/) | A zone's shape. | | [`SetZoneData`](/lua/server/functions/setzonedata/) | Stores a value on a zone, private to the server. | | [`GetZoneData`](/lua/server/functions/getzonedata/) | A value stored on a zone with SetZoneData. | ## The world - clock, weather, terrain, the navmesh, the geometry The server owns the **world clock** and the **weather**: every client follows them, so the whole server sees one time of day and one sky (`[world]` in `server.toml` sets the start). The clock is hours since midnight (`13.5` = 13:30) and runs at a ratio of game seconds per real second; the weather is a **preset** name or one of the level's own sky profiles ([Weather](/reference/weather/)); the rain is a lever on top. The **terrain height** comes from the level's heightmap when the server has one, and the **navigation mesh** - the game's own, when the operator exported it ([World data](/guides/#the-games-data)) - answers for walks, floors and reachability: the NPC actors walk around walls on it by themselves. The **collision geometry** - the level's walls, roofs, floors and trees, exported from the game's own physics world - answers rays: what is in the way, whether two points see each other, the true floor under a point. The doors the server knows are open let a ray through. | Function | What it does | |---|---| | [`GetWorldTime`](/lua/server/functions/getworldtime/) | The world clock, in hours since midnight. | | [`SetWorldTime`](/lua/server/functions/setworldtime/) | Sets the world clock for everyone. | | [`FormatWorldTime`](/lua/server/functions/formatworldtime/) | Hours as HH:MM. | | [`GetTimeRatio`](/lua/server/functions/gettimeratio/) | How fast the world clock runs - game seconds per real second. | | [`SetTimeRatio`](/lua/server/functions/settimeratio/) | Sets how fast the world clock runs. | | [`GetRain`](/lua/server/functions/getrain/) | The rain override. | | [`SetRain`](/lua/server/functions/setrain/) | Forces rain on every client, or hands the rain back to the weather. | | [`GetWeather`](/lua/server/functions/getweather/) | The sky profile every client follows. | | [`SetWeather`](/lua/server/functions/setweather/) | Changes the sky for everyone - by a preset name or a level profile. | | [`GetWeatherPresets`](/lua/server/functions/getweatherpresets/) | The preset names and the profiles they stand for. | | [`GetTerrainHeight`](/lua/server/functions/getterrainheight/) | The terrain height at a point, from the level's heightmap. | | [`HasNavmesh`](/lua/server/functions/hasnavmesh/) | Whether the server has the level's navigation mesh. | | [`FindPath`](/lua/server/functions/findpath/) | The corners of a walk between two points on the navigation mesh. | | [`IsReachable`](/lua/server/functions/isreachable/) | Whether a walk joins two points on the navigation mesh. | | [`GetNavmeshHeight`](/lua/server/functions/getnavmeshheight/) | The navigation mesh's floor at a point. | | [`NearestNavmeshPoint`](/lua/server/functions/nearestnavmeshpoint/) | The nearest point on the navigation mesh. | | [`HasCollision`](/lua/server/functions/hascollision/) | Whether the server holds the level's collision geometry. | | [`RayCast`](/lua/server/functions/raycast/) | The nearest surface along a line. | | [`IsLineOfSight`](/lua/server/functions/islineofsight/) | Whether nothing stands between two points. | | [`GetGroundZ`](/lua/server/functions/getgroundz/) | The surface under a point. | ## Doors and containers The level's own **doors** and **stashes** are in sync on every client whatever the mode does: a door one player opens swings on every screen; a chest one player loots is emptier for the next. A door's state of record is written by whoever uses it; a container's contents are the server's - the first opener's own loot seeds the record, one player holds a container at a time ("Someone is rummaging in it." for the next), and what they leave in it is what the next opener finds. The **key** of a door or a container is the entity's level name - `AnimDoor[Door/door_village_left32_77d417c2-...]`, `Stash7[Stash/stash_shelf_...]` - listed per level in [Levels](/reference/levels/). A mode needs nothing for the sync; it may veto ([`OnPlayerUseDoor`](/lua/server/callbacks/onplayerusedoor/), [`OnPlayerOpenContainer`](/lua/server/callbacks/onplayeropencontainer/)) or drive it ([`SetDoorState`](/lua/server/functions/setdoorstate/), [`SetContainerItems`](/lua/server/functions/setcontaineritems/)). | Callback | When | |---|---| | [`OnPlayerUseDoor`](/lua/server/callbacks/onplayerusedoor/) | A player's game opened, closed, locked or unlocked a door - return `false` to put it back. | | [`OnPlayerOpenContainer`](/lua/server/callbacks/onplayeropencontainer/) | A player wants to open a container - return `false` to refuse. | | [`OnPlayerCloseContainer`](/lua/server/callbacks/onplayerclosecontainer/) | A player closed a container; the record holds what they left in it. | | Function | What it does | |---|---| | [`GetDoors`](/lua/server/functions/getdoors/) | Every door anyone touched. | | [`GetDoorState`](/lua/server/functions/getdoorstate/) | A door's state of record. | | [`SetDoorState`](/lua/server/functions/setdoorstate/) | Opens, closes, locks or unlocks a door on every client. | | [`GetContainers`](/lua/server/functions/getcontainers/) | Every container anyone opened. | | [`GetContainerItems`](/lua/server/functions/getcontaineritems/) | A container's contents of record. | | [`SetContainerItems`](/lua/server/functions/setcontaineritems/) | Rewrites a container's contents; whoever has it open sees the new list. | | [`GetContainerUser`](/lua/server/functions/getcontaineruser/) | Who has a container open right now. | ## Accounts, admins, bans and the audit A name is open until a player claims it with `/register `; from then on whoever joins under it plays as a **guest** - held in a world of their own, no record, no admin flag - until `/login `, and is kicked after `[accounts] login_grace_seconds` without it. **Admins** are the logged-in owners of the names on `[accounts] admins`, or players the mode promotes for the session; the flag unlocks the server's admin-only [built-in commands](/reference/chat-commands/) and whatever the mode gates on it. **Bans** are kept in `data/bans.json` beside the player records - a plain list an admin may edit by hand. The **inventory audit** (`[audit]`) compares what a player holds with what the server can explain - the spawn outfit, `GivePlayerItem`, pickups, takes from containers - and calls the mode before it acts on a discrepancy. | Callback | When | |---|---| | [`OnPlayerLogin`](/lua/server/callbacks/onplayerlogin/) | The player proved a registered name, or just registered it. | | [`OnPlayerAuditViolation`](/lua/server/callbacks/onplayerauditviolation/) | The inventory audit found items the server cannot explain - return `false` to vouch for them. | | Function | What it does | |---|---| | [`IsPlayerRegistered`](/lua/server/functions/isplayerregistered/) | Whether the player's name has a password on record. | | [`IsPlayerLoggedIn`](/lua/server/functions/isplayerloggedin/) | Whether the player proved their registered name this session. | | [`IsPlayerAdmin`](/lua/server/functions/isplayeradmin/) | Whether the player is an admin. | | [`SetPlayerAdmin`](/lua/server/functions/setplayeradmin/) | Makes the player an admin for the session - or takes it back. | | [`GetAdminNames`](/lua/server/functions/getadminnames/) | The names on the server's admin list. | | [`Ban`](/lua/server/functions/ban/) | Kicks the player and bans their name and address. | | [`BanName`](/lua/server/functions/banname/) | Bans a name; whoever is on under it is kicked. | | [`BanAddress`](/lua/server/functions/banaddress/) | Bans an address; whoever is on from it is kicked. | | [`Unban`](/lua/server/functions/unban/) | Lifts every ban on a name or an address. | | [`IsBanned`](/lua/server/functions/isbanned/) | Whether a name or an address is banned right now, and why. | | [`GetPlayerAuditViolations`](/lua/server/functions/getplayerauditviolations/) | How many audit violations were acted on for the player this session. | ## Catalogues The server resolves the game's things by **id, name or GUID** through the tables export (`[combat] tables`): items ([the item catalogue](/reference/items/)), souls ([the souls](/reference/souls/)), buffs ([the buff list](/reference/buffs/)) and meshes ([the meshes](/reference/meshes/); [`GetMeshPath`](/lua/server/functions/getmeshpath/) and [`FindMeshes`](/lua/server/functions/findmeshes/) are with the props). Every function that takes an item, a soul or a buff accepts any of the keys; these look them up, search them and turn one key into another. The **id** is the row number of the name-sorted export - stable for one export of one game build, so keep the name or the GUID in anything durable. Without the export only GUIDs pass, unchecked. | Function | What it does | |---|---| | [`GetItemClass`](/lua/server/functions/getitemclass/) | The class GUID an item key stands for. | | [`GetItemName`](/lua/server/functions/getitemname/) | The game's name of an item key. | | [`GetItemInfo`](/lua/server/functions/getiteminfo/) | The catalogue's entry for an item key. | | [`FindItems`](/lua/server/functions/finditems/) | Items whose name, English name or category holds every word of a pattern. | | [`GetHorseSoul`](/lua/server/functions/gethorsesoul/) | The soul GUID a horse key stands for - the Horse archetype only. | | [`GetSoulInfo`](/lua/server/functions/getsoulinfo/) | The soul catalogue's entry for a key, of any archetype. | | [`FindSouls`](/lua/server/functions/findsouls/) | Souls whose name or archetype holds every word of a pattern. | | [`GetBuffGuid`](/lua/server/functions/getbuffguid/) | The GUID a buff key stands for. | | [`GetBuffInfo`](/lua/server/functions/getbuffinfo/) | The buff catalogue's entry for a key. | | [`FindBuffs`](/lua/server/functions/findbuffs/) | Buffs whose name, English name or class holds every word of a pattern. | ## Parties Players grouped with a leader (v38, [the guide](/lua/server/parties/)): the server keeps the group, the invitation with its timeout and the toast on the target's screen, the party frames every member sees (the others' name, health, stamina, wounds, at any distance and in any world) and the no-friendly-fire rule. **The server ships no party commands**: `/invite`, `/accept`, `/p` and every rule around them - who may invite, a level gate, leader-only invitations - are the mode's, written around these callbacks and functions (the shipped freeroam mode carries the plain ones). A party is a **number**; ids count up and are never reused while the server runs. A party exists with two or more members and ends when it falls to one - there is no party of one. One party and one pending invitation per player. `[party]` in the server's configuration holds the size (5), the invitation's timeout (30 s), the frames' default, what the leader's leaving does and the friendly fire. | Callback | When | |---|---| | [`OnPartyInvite`](/lua/server/callbacks/onpartyinvite/) | A player wants to invite another; return false to refuse. | | [`OnPartyInviteResponse`](/lua/server/callbacks/onpartyinviteresponse/) | An invitation was answered - or ran out, or fell through. | | [`OnPartyCreate`](/lua/server/callbacks/onpartycreate/) | A party came into being. | | [`OnPlayerJoinParty`](/lua/server/callbacks/onplayerjoinparty/) | A player joined a party - the leader too, at the party's birth. | | [`OnPlayerLeaveParty`](/lua/server/callbacks/onplayerleaveparty/) | A member is gone from the party. | | [`OnPartyLeaderChange`](/lua/server/callbacks/onpartyleaderchange/) | The lead changed hands. | | [`OnPartyDisband`](/lua/server/callbacks/onpartydisband/) | The party is over. | | Function | What it does | |---|---| | [`InviteToParty`](/lua/server/functions/invitetoparty/) | Sends a party invitation - the mode's /invite. | | [`AcceptPartyInvite`](/lua/server/functions/acceptpartyinvite/) | Accepts the player's pending invitation - the mode's /accept. | | [`DeclinePartyInvite`](/lua/server/functions/declinepartyinvite/) | Declines the player's pending invitation - the mode's /decline. | | [`GetPlayerPartyInvite`](/lua/server/functions/getplayerpartyinvite/) | The player's pending invitation. | | [`AddPlayerToParty`](/lua/server/functions/addplayertoparty/) | Puts a player into another's party without an invitation. | | [`RemovePlayerFromParty`](/lua/server/functions/removeplayerfromparty/) | Takes a player out of their party - the mode's /leave and /kick. | | [`SetPartyLeader`](/lua/server/functions/setpartyleader/) | Hands the lead to a member - the mode's /leader. | | [`DisbandParty`](/lua/server/functions/disbandparty/) | Ends a party. | | [`GetPlayerParty`](/lua/server/functions/getplayerparty/) | The party the player is in. | | [`GetPartyLeader`](/lua/server/functions/getpartyleader/) | The party's leader. | | [`GetPartyMembers`](/lua/server/functions/getpartymembers/) | The members, in join order. | | [`GetPartySize`](/lua/server/functions/getpartysize/) | How many members the party has. | | [`IsPartyFull`](/lua/server/functions/ispartyfull/) | Whether the party is at [party] max_size. | | [`ArePartyMembers`](/lua/server/functions/arepartymembers/) | Whether two players are in one party. | | [`GetParties`](/lua/server/functions/getparties/) | Every party on the server. | | [`SetPartyName`](/lua/server/functions/setpartyname/) | The party's title, shown over the members' frames. | | [`GetPartyName`](/lua/server/functions/getpartyname/) | The party's title. | | [`SetPartyMemberLabel`](/lua/server/functions/setpartymemberlabel/) | A line under the member's name in the frames - a role, a score. | | [`GetPartyMemberLabel`](/lua/server/functions/getpartymemberlabel/) | The member's label. | | [`ShowPartyFrames`](/lua/server/functions/showpartyframes/) | Whether this player sees the party frames. | | [`SendPartyMessage`](/lua/server/functions/sendpartymessage/) | One chat line to every member - the mode's /p. | | [`SetPartyData`](/lua/server/functions/setpartydata/) | The mode's private storage on a party. | | [`GetPartyData`](/lua/server/functions/getpartydata/) | A value of the mode's private storage on a party. | # Combat > How a swing or a shot becomes damage on the server, what stamina, injuries and bleeding do, fights and the lock-on, teams and pvp, and what a mode may decide about each hit. The server owns every player's **health, stamina and injuries**. A player's game only reports what its swing or its arrow hit - the game's own hit record - and the server decides what that did, tells the mode, and tells every client what to show. The numbers come from `[combat]` in `server.toml` ([Server configuration](/getting-started/server-config/#combat)); the game's own weapon and armour tables give the damage when the server has the tables export (`[combat] tables`). ## From a hit to damage 1. The attacker's client reports the hit: the target, the attack zone, the body part struck, and - for an arrow, a bolt or a ball - the shot it belongs to. 2. The server checks it is plausible: the two are within `max_reach`, the claim follows a swing the attacker announced within `claim_window_ms`, a shot was actually fired (`shot_interval_ms`, the ammunition in the shooter's inventory), the two are allowed to fight (`pvp`, not [teammates](#teams), the same [virtual world](/lua/server/functions/setplayervirtualworld/)). 3. The damage is computed. Melee: the attacker's equipped weapon's `Attack` × the type's modifier (stab, slash or smash) × `attack_scale`, reduced by the armour the target wears on the struck part against that type (`d / (d + armour_pivot)`, 85 % at most), × the part's coefficient (head 1.5, torso 1, limbs 0.7), less when the swing was thrown tired, × `damage_scale`. Ranged: the ammunition's attack × the launch speed (the draw - a snap shot at half speed does a quarter) × `ranged_scale`, then the same armour and part rules; every arrow is a stab. Bare hands do `fist_damage`. An attacker whose weapon is sheathed hits with fists whatever the claim says. Without the tables the server takes the attacker's own number, clamped to `max_claim_damage`. 4. The mode hears [`OnPlayerDamage(pid, attacker, damage, zone, part, weapon, dtype)`](/lua/server/callbacks/onplayerdamage/) and may change the number, zero it or cancel the hit. 5. The damage comes off the health; the victim's stamina takes `hit_stamina_damage`; a hit of at least `injury_threshold` injures the part (`OnPlayerInjury`); a stab or a slash opens a bleed of `bleed_per_damage × damage` health per second (`max_bleed` at most) for `bleed_seconds`; at `0` health the player dies (`OnPlayerDeath`) and every client shows it. The server log names every hit: `Henry#0 hit Hans#1 for 27.2 (shortswordBroad slash, raw 30.5, armour 6; zone 3, torso): health 72.8, torso injured, bleeding 0.41/s`. ## Stamina A swing costs `attack_stamina_cost` (× 1.2 for a slash or a smash, × 0.5 bare-handed, × 1.25 with an injured arm); a swing thrown with less than it costs lands at 35-100 % of its damage. A hit taken costs `hit_stamina_damage`, a swing blocked `block_stamina_cost`, a shot `shot_stamina`, a sprint `sprint_stamina_cost` per second, a jump `jump_stamina_cost`. It regenerates at `stamina_regen` per second after 1.5 s without any of those - halved with an injured head or torso. The bar the player sees is this number: [`GetPlayerStamina`](/lua/server/functions/getplayerstamina/) / [`SetPlayerStamina`](/lua/server/functions/setplayerstamina/). ## Fights and the lock-on Two players are **in a fight** - and only then may either one's game lock on to the other's body (the direction indicators, the combat stance) - once a swing of one reaches the other's body, after `/fight `, or when the mode says so. Without a fight two players walking up to each other stay at peace. A fight ends after `fight_timeout` seconds without a blow between the two (`0` = never by time), on a death, on `/peace` (ends every fight of the caller), on a disconnect, or when the mode ends it. Both players read a chat line at each change; the mode hears [`OnFightStart`](/lua/server/callbacks/onfightstart/) / [`OnFightEnd`](/lua/server/callbacks/onfightend/). The mode's side of it: [`StartFight`](/lua/server/functions/startfight/) (on a running fight it restarts the timeout clock - a duel mode calls it every second so two circling duelists never lose the lock), [`EndFight`](/lua/server/functions/endfight/), [`AreFighting`](/lua/server/functions/arefighting/), [`GetPlayerOpponents`](/lua/server/functions/getplayeropponents/), [`GetPlayerWeapon`](/lua/server/functions/getplayerweapon/). `[combat] pvp = false` keeps a co-op party from locking on to or hurting each other: no fight can start and every hit between players is refused. ## Teams [`SetPlayerTeam(pid, team)`](/lua/server/functions/setplayerteam/) puts players in teams; **a hit between two players of one team is refused** before `OnPlayerDamage` and starts no fight. `NO_TEAM` (`-1`) is no team. A mode that wants friendly fire on writes its rule in `OnPlayerDamage` instead of using teams. ## Ranged weapons A bow, a crossbow or a gun works through the server like a sword: the shooter's client reports the shot as it leaves the weapon (the ammunition, the speed - which is the draw), the server admits it (a bow among the equipment, the ammunition in the inventory, `shot_interval_ms` between shots, `shot_stamina`), every client in range flies a look-alike, and the hit is the shooter's claim within the flight time plus `shot_window_seconds`. `OnPlayerDamage` names the weapon as `"bow_c + arrow_normal"` and the type as `"stab"`. The archer's strength limits the draw as in the game ([`SetPlayerStat`](/lua/server/functions/setplayerstat/)). ## NPC actors A player's hit on an [NPC actor](/lua/server/#npc-actors) goes through the same model (no armour on the actor) and comes to the mode as [`OnActorDamage`](/lua/server/callbacks/onactordamage/); an actor's blow on a player is priced by the victim's own game (the actor's weapon through their armour) × `[actors] attack_scale` and comes as [`OnActorAttack`](/lua/server/callbacks/onactorattack/). An armed actor raises its guard against a swing part of the time (`[actors] block_chance`, `block_hold`) and swings where the opponent's guard is not; its wounds and bleeding follow the same `[combat]` keys as a player's ([`OnActorInjury`](/lua/server/callbacks/onactorinjury/), [`HealActor`](/lua/server/functions/healactor/)). ## Deciding a hit Everything the mode needs is in the callback: cancel, scale, redirect, log. ```lua -- no damage in the lobby zone, double damage to the head, a log line for every kill function OnPlayerDamage(pid, attacker, damage, zone, part, weapon, dtype) if IsPlayerInZone(pid, lobby) then return false end if part == BODY_PART_HEAD then return damage * 2 end end function OnPlayerDeath(pid, attacker) if attacker >= 0 then Log(GetPlayerName(attacker) .. " killed " .. GetPlayerName(pid) .. " with " .. GetPlayerWeapon(attacker)) end end ``` [`HealPlayer(pid)`](/lua/server/functions/healplayer/) makes a player whole; [`SetPlayerHealth(pid, 0)`](/lua/server/functions/setplayerhealth/) kills one; `[combat] respawn_seconds = 0` leaves the respawn to the mode's `SpawnPlayer`. # Constants > Every constant the server API defines - colours, body parts, GameText styles, HUD alignments, the no-team value, entity kinds, dog modes and the pose aliases. The globals the API defines next to its functions. They are plain Lua values: a mode may use the numbers directly, but the names read better and survive a renumbering. ## Colours `0xRRGGBBAA` - red, green, blue, alpha; `0xFF` alpha is opaque. Any number of that shape works wherever a colour is taken ([`SendClientMessage`](/lua/server/functions/sendclientmessage/), [`CreateHudText`](/lua/server/functions/createhudtext/), [`SetPlayerColour`](/lua/server/functions/setplayercolour/)). | Constant | Value | | |---|---|---| | `COLOUR_SERVER` | `0xFFD070FF` | amber - the server's own lines and the freeroam modes' | | `COLOUR_WHITE` | `0xFFFFFFFF` | | | `COLOUR_RED` | `0xFF4040FF` | | | `COLOUR_GREEN` | `0x40FF40FF` | | | `COLOUR_YELLOW` | `0xFFFF40FF` | | ## Body parts The game's own ids for the human body, as [`OnPlayerDamage`](/lua/server/callbacks/onplayerdamage/), [`OnPlayerInjury`](/lua/server/callbacks/onplayerinjury/), [`GetPlayerInjuries`](/lua/server/functions/getplayerinjuries/) and [`IsPlayerInjured`](/lua/server/functions/isplayerinjured/) use them; [`GetBodyPartName`](/lua/server/functions/getbodypartname/) names one. `0` is "unknown" - the record could not be resolved to a part. | Constant | Value | | |---|---|---| | `BODY_PART_HEAD` | `1` | `head` | | `BODY_PART_TORSO` | `2` | `torso` | | `BODY_PART_ARM_LEFT` | `3` | `arm_left` | | `BODY_PART_ARM_RIGHT` | `4` | `arm_right` | | `BODY_PART_LEG_LEFT` | `5` | `leg_left` | | `BODY_PART_LEG_RIGHT` | `6` | `leg_right` | ## GameText styles Where [`GameText`](/lua/server/functions/gametext/) lands on the screen. | Constant | Value | | |---|---|---| | `GAMETEXT_CENTRE` | `0` | big, in the middle of the screen | | `GAMETEXT_TOP` | `1` | under the top edge | | `GAMETEXT_LOWER` | `2` | the lower third, like a subtitle | ## HUD alignment Which side of a [HUD text](/lua/server/functions/createhudtext/) sits at its `x`. | Constant | Value | | |---|---|---| | `HUD_ALIGN_LEFT` | `0` | | | `HUD_ALIGN_CENTRE` | `1` | | | `HUD_ALIGN_RIGHT` | `2` | | ## Teams | Constant | Value | | |---|---|---| | `NO_TEAM` | `-1` | no team - what [`SetPlayerTeam`](/lua/server/functions/setplayerteam/) takes to remove a player from theirs and [`GetPlayerTeam`](/lua/server/functions/getplayerteam/) answers without one | ## Entity kinds What a world entity is: [`GetEntityKind`](/lua/server/functions/getentitykind/) answers one, [`GetEntities`](/lua/server/functions/getentities/) and [`GetNearestEntity`](/lua/server/functions/getnearestentity/) filter by one. | Constant | Value | | |---|---|---| | `ENTITY_PLAYER` | `0` | a player's body - never an entity id a mode holds; players are pids | | `ENTITY_HORSE` | `1` | a horse ([`CreateHorse`](/lua/server/functions/createhorse/)) | | `ENTITY_ITEM` | `2` | a pickup lying in the world ([`CreatePickup`](/lua/server/functions/createpickup/), a player's drop) | | `ENTITY_NPC` | `3` | an NPC actor ([`CreateActor`](/lua/server/functions/createactor/)) | | `ENTITY_PROP` | `4` | a static mesh ([`CreateProp`](/lua/server/functions/createprop/)) | | `ENTITY_DOG` | `5` | a player's dog ([`CreateDog`](/lua/server/functions/createdog/)) | ## Dog modes The game's own dog modes, for [`SetDogMode`](/lua/server/functions/setdogmode/) / [`GetDogMode`](/lua/server/functions/getdogmode/) (the dog's state bag key `mode` holds the number). Stay, follow and free are the tested ones; the rest are passed to the game as they are. | Constant | Value | | |---|---|---| | `DOG_STAY` | `0` | waits where it is | | `DOG_FOLLOW` | `1` | at its master's heel (what a new dog does) | | `DOG_FREE` | `2` | roams near its master | | `DOG_AGGRESSIVE` | `3` | the game's aggressive mode | | `DOG_SEARCH` | `4` | the game's search mode | | `DOG_HUNT` | `5` | the game's hunt mode | | `DOG_GUARD` | `6` | the game's guard mode | | `DOG_AMBUSH` | `7` | the game's ambush mode | ## Poses `ACTOR_ANIM` is a table of aliases [`SetActorAnim`](/lua/server/functions/setactoranim/) accepts in place of a clip name; the value is the clip of [the animation list](/reference/animations/) it stands for, `|once` marking the ones that play once. A mode may add its own: `ACTOR_ANIM.salute = "quest_stand_salute_v01|once"`, `ACTOR_ANIM.wave_small = "greetings_wave_small_over|once"`. `ACTOR_ANIM` - the pose aliases, alias -> clip: | Alias | Clip | | |---|---|---| | `sit` | `behavior_sitting_variation01_loop` | loops | | `wave` | `greetings_wave_big_over` | once | | `bow` | `greetings_bow` | once | | `nod` | `greetings_head_nod_over` | once | | `pray` | `pray_stand_long` | loops | | `chop` | `woodchopping_loop_01` | loops | | `sweep` | `sweeping_floor_idle_loop` | loops | | `smith` | `armorsmith_loop` | loops | ## `print` In a game mode `print` is [`Log`](/lua/server/functions/log/): it writes to the server log, never to a player's screen. # OnActorArrive > An actor reached its MoveActor target. An actor reached its MoveActor target. It stands there until the next [`MoveActor`](/lua/server/functions/moveactor/). Chain the legs of a route here. ## Syntax ```lua function OnActorArrive(id) -- ... end ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | ## Returns nothing ## Example ```lua -- a patrol between two points, for ever local route, leg = {{1280, 1100, -1}, {1300, 1100, -1}}, {} function OnActorArrive(id) leg[id] = (leg[id] or 1) % #route + 1 local p = route[leg[id]] MoveActor(id, p[1], p[2], p[3], 1.5) end ``` ## See also [MoveActor](/lua/server/functions/moveactor/) · [StopActor](/lua/server/functions/stopactor/) · [IsActorMoving](/lua/server/functions/isactormoving/) · the [NPC actors](/lua/server/#npc-actors) group of the index # OnActorAttack > An actor's blow landed on its opponent - change the damage, cancel it, or let it through. An actor's blow landed on its opponent - change the damage, cancel it, or let it through. The same shape and return rules as [`OnPlayerDamage`](/lua/server/callbacks/onplayerdamage/). The blow is priced by the victim's own game - the actor's weapon through their armour - times `[actors] attack_scale`, at most `[actors] max_damage`. A mode **without** this callback hears the blow as `OnPlayerDamage(pid, -1, ...)`. ## Syntax ```lua function OnActorAttack(id, pid, damage, zone, part, weapon, dtype) -- ... end ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | | `pid` | number | the player struck | | `damage` | number | what the player is about to lose | | `zone` | number | the attack zone | | `part` | number | the body part struck, `1` .. `6`; `0` unknown | | `weapon` | string | the actor's weapon by its table name; `""` bare-handed | | `dtype` | string | `"stab"`, `"slash"`, `"smash"` or `""` | ## Returns a number replaces the damage (`0` cancels); `false` cancels the blow; nothing keeps it ## Example ```lua -- the training dummy never really hurts function OnActorAttack(id, pid, damage, zone, part, weapon, dtype) if GetEntityData(id, "role") == "trainer" then return 1 end end ``` ## See also [OnActorDamage](/lua/server/callbacks/onactordamage/) · [SetActorHostile](/lua/server/functions/setactorhostile/) · [OnPlayerDamage](/lua/server/callbacks/onplayerdamage/) · the [NPC actors](/lua/server/#npc-actors) group of the index # OnActorDamage > A player hit an actor - change the damage, cancel it, or let it through. A player hit an actor - change the damage, cancel it, or let it through. The same shape and the same return rules as [`OnPlayerDamage`](/lua/server/callbacks/onplayerdamage/): a number replaces the damage (`0` cancels), `false` cancels, nothing keeps it. The hit went through the same model as a hit on a player, without armour on the actor. ## Syntax ```lua function OnActorDamage(id, attacker, damage, zone, part, weapon, dtype) -- ... end ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | | `attacker` | number | the player who struck | | `damage` | number | what the actor is about to lose | | `zone` | number | the attack zone the attacker's game recorded | | `part` | number | the body part struck, `1` .. `6`; `0` unknown | | `weapon` | string | the weapon's table name; `""` bare-handed | | `dtype` | string | `"stab"`, `"slash"`, `"smash"` or `""` | ## Returns a number replaces the damage (`0` cancels); `false` cancels the hit; nothing keeps it ## Example ```lua -- the shopkeeper cannot be hurt; the arena opponent takes half function OnActorDamage(id, attacker, damage, zone, part, weapon, dtype) if GetEntityData(id, "role") == "shopkeeper" then return false end return damage * 0.5 end ``` ## See also [OnActorDeath](/lua/server/callbacks/onactordeath/) · [OnActorAttack](/lua/server/callbacks/onactorattack/) · [OnPlayerDamage](/lua/server/callbacks/onplayerdamage/) · [GetActorHealth](/lua/server/functions/getactorhealth/) · the [NPC actors](/lua/server/#npc-actors) group of the index # OnActorDeath > An actor's health reached 0. An actor's health reached 0. `attacker` is the player who killed it - by a blow or by the bleed they opened - or `-1` for `SetActorHealth(id, 0)`. The corpse stays until [`DestroyEntity`](/lua/server/functions/destroyentity/) - an actor has no respawn of its own; a mode creates a new one. ## Syntax ```lua function OnActorDeath(id, attacker) -- ... end ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | | `attacker` | number | the killer; `-1` = nobody | ## Returns nothing ## Example ```lua function OnActorDeath(id, attacker) if attacker >= 0 then SendClientMessageToAll(COLOUR_YELLOW, GetPlayerName(attacker) .. " killed " .. GetEntityName(id)) end SetTimer(function() DestroyEntity(id) end, 20000) -- the corpse lies twenty seconds end ``` ## See also [OnActorDamage](/lua/server/callbacks/onactordamage/) · [SetActorHealth](/lua/server/functions/setactorhealth/) · [DestroyEntity](/lua/server/functions/destroyentity/) · the [NPC actors](/lua/server/#npc-actors) group of the index # OnActorInjury > A hit wounded one of an actor's body parts. A hit wounded one of an actor's body parts. The shape of [`OnPlayerInjury`](/lua/server/callbacks/onplayerinjury/): a blow of at least `[combat] injury_threshold` injures the part it struck; every client shows the limp. A cut bleeds for `[combat] bleed_seconds` ([`GetActorBleeding`](/lua/server/functions/getactorbleeding/)) and drains the health - a bleed-out is the last attacker's kill. [`HealActor`](/lua/server/functions/healactor/) makes the actor whole. ## Syntax ```lua function OnActorInjury(id, attacker, part) -- ... end ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | | `attacker` | number | the player who struck; `-1` = nobody | | `part` | number | the body part, `1` .. `6` | ## Returns nothing ## Example ```lua function OnActorInjury(id, attacker, part) SendClientMessageToAll(COLOUR_SERVER, GetEntityName(id) .. "'s " .. GetBodyPartName(part):gsub("_", " ") .. " is wounded") end ``` ## See also [OnActorDamage](/lua/server/callbacks/onactordamage/) · [GetActorInjuries](/lua/server/functions/getactorinjuries/) · [IsActorBleeding](/lua/server/functions/isactorbleeding/) · [HealActor](/lua/server/functions/healactor/) · the [NPC actors](/lua/server/#npc-actors) group of the index # OnClientEvent > A player's client script sent an event. A player's client script sent an event. The client's `KcdMp.send_event(name, payload)` lands here. `payload` is whatever string the client sent - trust it no further than any other input from a player (parse defensively, check the pid may do what it asks). At most 30 events a second and 4 KB each per client; more is dropped. ## Syntax ```lua function OnClientEvent(pid, name, payload) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | whose client sent it | | `name` | string | the event's name | | `payload` | string | the string the client sent; `""` when none | ## Returns nothing ## Example ```lua function OnClientEvent(pid, name, payload) if name == "echo" then SendClientEvent(pid, "echo", payload) -- a round-trip test elseif name == "marker_reached" then local n = tonumber(payload) if n and n == nextMarker[pid] then advance(pid) end end end ``` ## See also [SendClientEvent](/lua/server/functions/sendclientevent/) · [SendClientEventToAll](/lua/server/functions/sendclienteventtoall/) · [SetGlobalState](/lua/server/functions/setglobalstate/) · the [Script events](/lua/server/#script-events) group of the index # OnFightEnd > A fight between two players is over. A fight between two players is over. `reason` is `"timeout"` (`[combat] fight_timeout` seconds without a blow), `"death"`, `"left"` (a disconnect), `"peace"` (`/peace`) or `"mode"` ([`EndFight`](/lua/server/functions/endfight/)). Both clients drop the lock. ## Syntax ```lua function OnFightEnd(a, b, reason) -- ... end ``` | Parameter | Type | | |---|---|---| | `a` | number | one player | | `b` | number | the other | | `reason` | string | `"timeout"`, `"death"`, `"left"`, `"peace"` or `"mode"` | ## Returns nothing ## Example ```lua function OnFightEnd(a, b, reason) if reason == "timeout" then SendClientMessage(a, COLOUR_SERVER, "The fight is over - nobody landed a blow.") SendClientMessage(b, COLOUR_SERVER, "The fight is over - nobody landed a blow.") end end ``` ## See also [OnFightStart](/lua/server/callbacks/onfightstart/) · [EndFight](/lua/server/functions/endfight/) · the [Combat](/lua/server/#combat) group of the index # OnFightStart > Two players are in a fight from now on. Two players are in a fight from now on. Their clients let the game's lock-on pick each other's body from here. `reason` is `"hit"` (a swing of one reached the other's body), `"command"` (`/fight `) or `"mode"` ([`StartFight`](/lua/server/functions/startfight/)). Both players read a chat line about it. ## Syntax ```lua function OnFightStart(a, b, reason) -- ... end ``` | Parameter | Type | | |---|---|---| | `a` | number | one player | | `b` | number | the other | | `reason` | string | `"hit"`, `"command"` or `"mode"` | ## Returns nothing ## Example ```lua function OnFightStart(a, b, reason) Log(GetPlayerName(a) .. " and " .. GetPlayerName(b) .. " fight (" .. reason .. ")") end ``` ## See also [OnFightEnd](/lua/server/callbacks/onfightend/) · [StartFight](/lua/server/functions/startfight/) · [AreFighting](/lua/server/functions/arefighting/) · the [Combat](/lua/server/#combat) group of the index # OnGameModeExit > The server shuts down or the mode is about to be reloaded. The server shuts down or the mode is about to be reloaded. The last callback of a mode's life. Persist what you need with [`SetServerData`](/lua/server/functions/setserverdata/) or [`SetSavedData`](/lua/server/functions/setsaveddata/); the objects the mode made are torn down by the server right after this. ## Syntax ```lua function OnGameModeExit() -- ... end ``` ## Returns nothing ## Example ```lua function OnGameModeExit() SetServerData("rounds_played", tostring(roundsPlayed)) end ``` ## See also [OnGameModeInit](/lua/server/callbacks/ongamemodeinit/) · [ReloadGameMode](/lua/server/functions/reloadgamemode/) · the [Server and timers](/lua/server/#server-and-timers) group of the index # OnGameModeInit > The script is loaded and the API is ready - the place to create zones, HUD texts, timers and actors. The script is loaded and the API is ready - the place to create zones, HUD texts, timers and actors. Called once when the server starts and again after every [hot reload](/lua/server/functions/reloadgamemode/). Everything the mode creates - zones, HUD texts, props, actors, timers, state - is gone before it runs again, so this is where it is (re)made. The players are told to the mode afterwards: `OnPlayerConnect` for everyone on, then `OnPlayerLogin` for the logged-in and `OnPlayerSpawn` for those already in the world. ## Syntax ```lua function OnGameModeInit() -- ... end ``` ## Returns nothing ## Example ```lua local clock function OnGameModeInit() Log("hello on " .. GetLevel() .. ", " .. GetMaxPlayers() .. " slots") clock = CreateHudText(0.99, 0.02, FormatWorldTime(), COLOUR_YELLOW, 1.0, HUD_ALIGN_RIGHT) SetTimer(function() SetHudText(clock, FormatWorldTime()) end, 2000, true) end ``` ## See also [OnGameModeExit](/lua/server/callbacks/ongamemodeexit/) · [SetTimer](/lua/server/functions/settimer/) · [ReloadGameMode](/lua/server/functions/reloadgamemode/) · the [Server and timers](/lua/server/#server-and-timers) group of the index # OnPartyCreate > A party came into being. A party came into being. The first accepted invitation (or the mode's first [`AddPlayerToParty`](/lua/server/functions/addplayertoparty/)) makes the group with the inviter leading. Fires before the two joins ([`OnPlayerJoinParty`](/lua/server/callbacks/onplayerjoinparty/) with `"create"` for the leader, then the newcomer's reason). ## Syntax ```lua function OnPartyCreate(party, leader) -- ... end ``` | Parameter | Type | | |---|---|---| | `party` | number | the new party's id | | `leader` | number | the leader | ## Returns nothing ## Example ```lua function OnPartyCreate(party, leader) SetPartyName(party, GetPlayerName(leader) .. "'s party") end ``` ## See also [OnPlayerJoinParty](/lua/server/callbacks/onplayerjoinparty/) · [OnPartyDisband](/lua/server/callbacks/onpartydisband/) · the [Parties](/lua/server/#parties) group of the index # OnPartyDisband > The party is over. The party is over. Fires last, after every member's [`OnPlayerLeaveParty`](/lua/server/callbacks/onplayerleaveparty/). `reason` is `"empty"` (the party fell to one member), `"mode"` ([`DisbandParty`](/lua/server/functions/disbandparty/)) or `"leader"` (the leader left and `[party] leader_leaves` is `"disband"`). A reload of the mode drops every party without this callback. ## Syntax ```lua function OnPartyDisband(party, reason) -- ... end ``` | Parameter | Type | | |---|---|---| | `party` | number | the party that ended | | `reason` | string | `"empty"`, `"mode"` or `"leader"` | ## Returns nothing ## Example ```lua function OnPartyDisband(party, reason) Log("party " .. party .. " over: " .. reason) end ``` ## See also [DisbandParty](/lua/server/functions/disbandparty/) · [OnPlayerLeaveParty](/lua/server/callbacks/onplayerleaveparty/) · the [Parties](/lua/server/#parties) group of the index # OnPartyInvite > A player wants to invite another; return false to refuse. A player wants to invite another; return false to refuse. Fires from [`InviteToParty`](/lua/server/functions/invitetoparty/) before the toast goes out, after the server's own checks (the target free, the party not full, no invitation pending). The place for the mode's rule: leader-only invitations, a level gate, a cooldown. Without the callback every invitation the server admits goes through. ## Syntax ```lua function OnPartyInvite(from, target) -- ... end ``` | Parameter | Type | | |---|---|---| | `from` | number | the inviter | | `target` | number | the player invited | ## Returns `false` refuses the invitation (`InviteToParty` returns `false, "refused"`); anything else lets it through ## Example ```lua function OnPartyInvite(from, target) -- leader-only: a member who does not lead may not invite local party = GetPlayerParty(from) if party and GetPartyLeader(party) ~= from then return false end SendClientMessage(target, COLOUR_SERVER, GetPlayerName(from) .. " invites you to a party - /accept or /decline.") end ``` ## See also [InviteToParty](/lua/server/functions/invitetoparty/) · [OnPartyInviteResponse](/lua/server/callbacks/onpartyinviteresponse/) · the [Parties](/lua/server/#parties) group of the index # OnPartyInviteResponse > An invitation was answered - or ran out, or fell through. An invitation was answered - or ran out, or fell through. `answer` is `"accepted"` (the join follows at once), `"declined"`, `"timeout"` (`[party] invite_timeout` passed) or `"cancelled"` - the party filled or ended before the answer, a side disconnected, or the target joined another party. ## Syntax ```lua function OnPartyInviteResponse(from, target, answer) -- ... end ``` | Parameter | Type | | |---|---|---| | `from` | number | the inviter | | `target` | number | the player invited | | `answer` | string | `"accepted"`, `"declined"`, `"timeout"` or `"cancelled"` | ## Returns nothing ## Example ```lua function OnPartyInviteResponse(from, target, answer) if answer ~= "accepted" then SendClientMessage(from, COLOUR_SERVER, GetPlayerName(target) .. " " .. answer .. " the invitation.") end end ``` ## See also [OnPartyInvite](/lua/server/callbacks/onpartyinvite/) · [InviteToParty](/lua/server/functions/invitetoparty/) · the [Parties](/lua/server/#parties) group of the index # OnPartyLeaderChange > The lead changed hands. The lead changed hands. By the mode ([`SetPartyLeader`](/lua/server/functions/setpartyleader/)) or by the leader leaving, when the next member in join order takes over (`previous` is then the one who left). ## Syntax ```lua function OnPartyLeaderChange(party, pid, previous) -- ... end ``` | Parameter | Type | | |---|---|---| | `party` | number | the party | | `pid` | number | the new leader | | `previous` | number | the one before | ## Returns nothing ## Example ```lua function OnPartyLeaderChange(party, pid, previous) SendPartyMessage(party, COLOUR_SERVER, GetPlayerName(pid) .. " leads the party now.") end ``` ## See also [SetPartyLeader](/lua/server/functions/setpartyleader/) · [GetPartyLeader](/lua/server/functions/getpartyleader/) · the [Parties](/lua/server/#parties) group of the index # OnPlayerAuditViolation > The inventory audit found items the server cannot explain - return false to vouch for them. The inventory audit found items the server cannot explain - return `false` to vouch for them. The player holds `amount` of a guarded item class (`[audit] guarded_categories`: weapons, armour, ammunition) where the server's records explain `allowed`, in `[audit] strikes` reports in a row - or used a consumable they never held (`amount` `1`, `allowed` `0`). Return `false` to vouch: the records take the amount and nothing happens. Anything else and the `[audit] action` follows - `log` (the default; the excess is then accepted, so it is judged once), `kick` or `ban`. ## Syntax ```lua function OnPlayerAuditViolation(pid, class, amount, allowed) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `class` | string | the item class GUID ([`GetItemName`](/lua/server/functions/getitemname/) names it) | | `amount` | number | how many the player holds | | `allowed` | number | how many the server's records explain | ## Returns `false` vouches for the items; anything else lets the `[audit] action` happen ## Example ```lua function OnPlayerAuditViolation(pid, class, amount, allowed) Log(string.format("audit: %s holds %d x %s, %d explained", GetPlayerName(pid), amount, GetItemName(class), allowed)) if GetPlayerData(pid, "event_loot") then return false end -- the event handed things out itself end ``` ## See also [GetPlayerAuditViolations](/lua/server/functions/getplayerauditviolations/) · [GivePlayerItem](/lua/server/functions/giveplayeritem/) · [GetPlayerInventory](/lua/server/functions/getplayerinventory/) · the [Accounts, admins, bans and the audit](/lua/server/#accounts-admins-bans-and-the-audit) group of the index # OnPlayerCloseContainer > A player closed a container; the record holds what they left in it. A player closed a container; the record holds what they left in it. ## Syntax ```lua function OnPlayerCloseContainer(pid, key) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `key` | string | the container's level name | ## Returns nothing ## Example ```lua function OnPlayerCloseContainer(pid, key) local items = GetContainerItems(key) or {} Log(GetPlayerName(pid), "closed", key, "with", #items, "stacks left") end ``` ## See also [OnPlayerOpenContainer](/lua/server/callbacks/onplayeropencontainer/) · [GetContainerItems](/lua/server/functions/getcontaineritems/) · [SetContainerItems](/lua/server/functions/setcontaineritems/) · the [Doors and containers](/lua/server/#doors-and-containers) group of the index # OnPlayerCommandText > A / command - return true when the mode answered it. A `/` command - return `true` when the mode answered it. `/tp 1 2 3` arrives as `cmd = "tp"`, `args = "1 2 3"`: the word after the slash as typed (compare it lower-cased if you want to be lenient) and the rest of the line, trimmed. Return `true` to say the mode answered - even when the answer was "you may not". Return `false` (or nothing) and the server's [built-in commands](/reference/chat-commands/) get the line, then `Unknown command: /x`. A mode takes a built-in over by answering its name; a `/help` that prints a line and returns `false` is followed by the server's own list. Commands are never echoed to the chat. ## Syntax ```lua function OnPlayerCommandText(pid, cmd, args) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | who typed it | | `cmd` | string | the command without the slash, as typed | | `args` | string | everything after the command, trimmed; `""` when nothing | ## Returns `true` = handled; `false` or nothing = the server's built-ins, then "Unknown command" ## Example ```lua function OnPlayerCommandText(pid, cmd, args) if cmd == "help" then SendClientMessage(pid, COLOUR_SERVER, "arena: /duel, /leave, /score") return false -- the server appends its own list elseif cmd == "duel" then queue[#queue + 1] = pid SendClientMessage(pid, COLOUR_SERVER, "queued (" .. #queue .. " waiting)") return true elseif cmd == "give" then SendClientMessage(pid, COLOUR_RED, "No /give in the arena.") return true -- the built-in /give never runs here elseif cmd == "pay" then local target, amount = sscanf(args, "ud") -- a player and a whole number, typed and checked in one line if target == false then SendClientMessage(pid, COLOUR_RED, "usage: /pay (" .. amount .. ")") return true end pay(pid, target, amount) return true end return false end ``` ## See also [OnPlayerText](/lua/server/callbacks/onplayertext/) · [SendClientMessage](/lua/server/functions/sendclientmessage/) · [sscanf](/lua/server/functions/sscanf/) · [GetPlayerId](/lua/server/functions/getplayerid/) · [IsPlayerAdmin](/lua/server/functions/isplayeradmin/) · the [Chat and commands](/lua/server/#chat-and-commands) group of the index # OnPlayerConnect > The handshake is done and the client is loading the level. The handshake is done and the client is loading the level. The player has a name and an address and no position yet; they are not in the world until [`OnPlayerSpawn`](/lua/server/callbacks/onplayerspawn/). A returning player's record is already readable ([`GetSavedPlayer`](/lua/server/functions/getsavedplayer/)). Also called for everyone on the server after a [reload](/lua/server/functions/reloadgamemode/). ## Syntax ```lua function OnPlayerConnect(pid) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns nothing ## Example ```lua function OnPlayerConnect(pid) local saved = GetSavedPlayer(pid) if saved and saved.visits > 1 then SendClientMessage(pid, COLOUR_SERVER, string.format("Welcome back, %s (visit %d)", GetPlayerName(pid), saved.visits)) else SendClientMessage(pid, COLOUR_SERVER, "Welcome, " .. GetPlayerName(pid) .. ". /help for the commands.") end SendClientMessageToAll(COLOUR_SERVER, GetPlayerName(pid) .. " joined") end ``` ## See also [OnPlayerRequestSpawn](/lua/server/callbacks/onplayerrequestspawn/) · [OnPlayerDisconnect](/lua/server/callbacks/onplayerdisconnect/) · [GetSavedPlayer](/lua/server/functions/getsavedplayer/) · the [Players](/lua/server/#players) group of the index # OnPlayerDamage > The server accepted a hit on a player - change the damage, cancel it, or let it through. The server accepted a hit on a player - change the damage, cancel it, or let it through. Called before the damage comes off the health. `attacker` is the pid who struck, or `-1` for damage without one (an NPC actor's blow when the mode has no [`OnActorAttack`](/lua/server/callbacks/onactorattack/), [`SetPlayerHealth`](/lua/server/functions/setplayerhealth/)). `zone` is the attack zone the attacker's game recorded; `part` the body part struck, `1` .. `6` (`0` unknown; [`GetBodyPartName`](/lua/server/functions/getbodypartname/)); `weapon` the attacker's weapon by its table name (`shortswordBroad`, `bow_c + arrow_normal`; `""` bare-handed or without the tables); `dtype` `"stab"`, `"slash"`, `"smash"` or `""`. **Return a number** to change the damage (`0` cancels the hit, so do a stamina cost, an injury and a bleed), **`false`** to cancel it, nothing to keep it. Hits between teammates never get here. ## Syntax ```lua function OnPlayerDamage(pid, attacker, damage, zone, part, weapon, dtype) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the victim | | `attacker` | number | who struck; `-1` = nobody | | `damage` | number | what the victim is about to lose | | `zone` | number | the attack zone the attacker's game recorded | | `part` | number | the body part struck, `1` .. `6`; `0` unknown | | `weapon` | string | the weapon's table name; `""` bare-handed | | `dtype` | string | `"stab"`, `"slash"`, `"smash"` or `""` | ## Returns a number replaces the damage (`0` cancels); `false` cancels the hit; nothing keeps it ## Example ```lua -- no damage in the lobby, double to the head, a log line for a big one function OnPlayerDamage(pid, attacker, damage, zone, part, weapon, dtype) if IsPlayerInZone(pid, lobby) then return false end if part == BODY_PART_HEAD then damage = damage * 2 end if damage > 40 and attacker >= 0 then Log(string.format("%s hit %s for %.0f with %s (%s)", GetPlayerName(attacker), GetPlayerName(pid), damage, weapon, dtype)) end return damage end ``` ## See also [OnPlayerInjury](/lua/server/callbacks/onplayerinjury/) · [OnPlayerDeath](/lua/server/callbacks/onplayerdeath/) · [OnActorDamage](/lua/server/callbacks/onactordamage/) · [GetBodyPartName](/lua/server/functions/getbodypartname/) · [SetPlayerTeam](/lua/server/functions/setplayerteam/) · the [Combat](/lua/server/#combat) group of the index # OnPlayerDeath > The player's health reached 0. The player's health reached 0. A hit, a bleed-out (the last attacker is named) or `SetPlayerHealth(pid, 0)` (attacker `-1`). Every client shows the death; the respawn follows after `[combat] respawn_seconds` at the player's spawn point - with `0` there the mode calls [`SpawnPlayer`](/lua/server/functions/spawnplayer/) itself. Every fight of the player ends (`OnFightEnd` with `"death"`). ## Syntax ```lua function OnPlayerDeath(pid, attacker) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | who died | | `attacker` | number | who killed them; `-1` = nobody | ## Returns nothing ## Example ```lua function OnPlayerDeath(pid, attacker) if attacker >= 0 then kills[attacker] = (kills[attacker] or 0) + 1 SendClientMessageToAll(COLOUR_YELLOW, GetPlayerName(attacker) .. " killed " .. GetPlayerName(pid)) end SetTimer(function() if IsPlayerConnected(pid) then SpawnPlayer(pid) end end, 5000) -- with respawn_seconds = 0 end ``` ## See also [OnPlayerDamage](/lua/server/callbacks/onplayerdamage/) · [SpawnPlayer](/lua/server/functions/spawnplayer/) · [SetPlayerHealth](/lua/server/functions/setplayerhealth/) · [OnFightEnd](/lua/server/callbacks/onfightend/) · the [Combat](/lua/server/#combat) group of the index # OnPlayerDisconnect > The player is gone. The player is gone. `reason` is `"disconnected"` (they left), `"timed out"` (nothing heard for a while) or `"kicked: "` with the text given to [`Kick`](/lua/server/functions/kick/) or [`Ban`](/lua/server/functions/ban/). Their pid may be given to the next player who joins; their `SetPlayerData` is cleared, their saved record has been written. A horse they controlled stays in the world (a nearby player takes it over); their dog leaves with them; every fight of theirs ends. ## Syntax ```lua function OnPlayerDisconnect(pid, reason) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `reason` | string | why, as above | ## Returns nothing ## Example ```lua function OnPlayerDisconnect(pid, reason) SendClientMessageToAll(COLOUR_SERVER, string.format("%s left (%s)", GetPlayerName(pid), reason)) removeFromQueue(pid) end ``` ## See also [OnPlayerConnect](/lua/server/callbacks/onplayerconnect/) · [Kick](/lua/server/functions/kick/) · the [Players](/lua/server/#players) group of the index # OnPlayerDismount > The player got off the horse - or left while riding, or the horse was destroyed. The player got off the horse - or left while riding, or the horse was destroyed. ## Syntax ```lua function OnPlayerDismount(pid, id) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `id` | number | the horse | ## Returns nothing ## Example ```lua function OnPlayerDismount(pid, id) Log(GetPlayerName(pid), "dismounted horse", id) end ``` ## See also [OnPlayerMount](/lua/server/callbacks/onplayermount/) · the [Horses](/lua/server/#horses) group of the index # OnPlayerDrop > The player dropped an item and the world made a pickup of it. The player dropped an item and the world made a pickup of it. The player's own game dropped the item; the server made pickup `id` of it so everyone sees it lying there and anyone may take it. Nothing to veto - the dropper's screen already shows it; a mode that wants it gone calls [`DestroyEntity`](/lua/server/functions/destroyentity/). ## Syntax ```lua function OnPlayerDrop(pid, id) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `id` | number | the new pickup entity | ## Returns nothing ## Example ```lua -- dropped items vanish after two minutes function OnPlayerDrop(pid, id) SetTimer(function() DestroyEntity(id) end, 120000) end ``` ## See also [OnPlayerPickup](/lua/server/callbacks/onplayerpickup/) · [DestroyEntity](/lua/server/functions/destroyentity/) · [GetEntityTemplate](/lua/server/functions/getentitytemplate/) · the [Items and inventory](/lua/server/#items-and-inventory) group of the index # OnPlayerDrunk > The player got drunk, or sobered up. The player got drunk, or sobered up. `true` when the blood-alcohol level crossed `[combat] drunk_threshold` upwards (the game's drunkenness is on, the others see the body sway); `false` when it fell back under half of it (the hangover follows for `[combat] hangover_seconds`). ## Syntax ```lua function OnPlayerDrunk(pid, drunk) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `drunk` | boolean | `true` = drunk now, `false` = sober again | ## Returns nothing ## Example ```lua function OnPlayerDrunk(pid, drunk) SendClientMessageToAll(COLOUR_SERVER, GetPlayerName(pid) .. (drunk and " has had one too many" or " is sober again")) end ``` ## See also [GetPlayerAlcohol](/lua/server/functions/getplayeralcohol/) · [IsPlayerDrunk](/lua/server/functions/isplayerdrunk/) · [SetPlayerAlcohol](/lua/server/functions/setplayeralcohol/) · the [Buffs and the drink](/lua/server/#buffs-and-the-drink) group of the index # OnPlayerEnterZone > A player's position of record entered a zone. A player's position of record entered a zone. ## Syntax ```lua function OnPlayerEnterZone(pid, zone) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `zone` | number | the zone | ## Returns nothing ## Example ```lua function OnPlayerEnterZone(pid, zone) if zone == spawnZone then GameText(pid, "The spawn", 1500, GAMETEXT_LOWER) end if GetZoneData(zone, "safe") then SendClientMessage(pid, COLOUR_GREEN, "You are safe here.") end end ``` ## See also [OnPlayerLeaveZone](/lua/server/callbacks/onplayerleavezone/) · [CreateZone](/lua/server/functions/createzone/) · [IsPlayerInZone](/lua/server/functions/isplayerinzone/) · the [Zones](/lua/server/#zones) group of the index # OnPlayerInjury > A hit injured one of the player's body parts. A hit injured one of the player's body parts. A hit of at least `[combat] injury_threshold` injures the part it struck. An injured arm makes the player's swings weaker and costlier; an injured head or torso halves the stamina regeneration. [`HealPlayer`](/lua/server/functions/healplayer/) and the respawn heal it. ## Syntax ```lua function OnPlayerInjury(pid, attacker, part) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the victim | | `attacker` | number | who struck; `-1` = nobody | | `part` | number | the body part, `1` .. `6` | ## Returns nothing ## Example ```lua function OnPlayerInjury(pid, attacker, part) SendClientMessage(pid, COLOUR_RED, "your " .. GetBodyPartName(part):gsub("_", " ") .. " is injured") end ``` ## See also [OnPlayerDamage](/lua/server/callbacks/onplayerdamage/) · [GetPlayerInjuries](/lua/server/functions/getplayerinjuries/) · [GetBodyPartName](/lua/server/functions/getbodypartname/) · the [Combat](/lua/server/#combat) group of the index # OnPlayerJoinParty > A player joined a party - the leader too, at the party's birth. A player joined a party - the leader too, at the party's birth. Every member arrives through here: `reason` is `"create"` (the leader, as the party is made), `"invite"` (an accepted invitation) or `"mode"` ([`AddPlayerToParty`](/lua/server/functions/addplayertoparty/)). ## Syntax ```lua function OnPlayerJoinParty(party, pid, reason) -- ... end ``` | Parameter | Type | | |---|---|---| | `party` | number | the party | | `pid` | number | the member | | `reason` | string | `"create"`, `"invite"` or `"mode"` | ## Returns nothing ## Example ```lua function OnPlayerJoinParty(party, pid, reason) SendPartyMessage(party, COLOUR_SERVER, GetPlayerName(pid) .. " joined the party.") end ``` ## See also [OnPlayerLeaveParty](/lua/server/callbacks/onplayerleaveparty/) · [AddPlayerToParty](/lua/server/functions/addplayertoparty/) · the [Parties](/lua/server/#parties) group of the index # OnPlayerLeaveParty > A member is gone from the party. A member is gone from the party. `reason` is `"left"` ([`RemovePlayerFromParty`](/lua/server/functions/removeplayerfromparty/)), `"kicked"` (the same with `"kicked"`), `"disconnect"`, or `"disband"` - the mode's [`DisbandParty`](/lua/server/functions/disbandparty/), the leader's leaving under `leader_leaves = "disband"`, or the last member standing when the party fell to one. The member's label is gone with the membership. ## Syntax ```lua function OnPlayerLeaveParty(party, pid, reason) -- ... end ``` | Parameter | Type | | |---|---|---| | `party` | number | the party | | `pid` | number | the member who left | | `reason` | string | `"left"`, `"kicked"`, `"disconnect"` or `"disband"` | ## Returns nothing ## Example ```lua function OnPlayerLeaveParty(party, pid, reason) if reason ~= "disband" then SendPartyMessage(party, COLOUR_SERVER, GetPlayerName(pid) .. " left the party (" .. reason .. ").") end end ``` ## See also [OnPlayerJoinParty](/lua/server/callbacks/onplayerjoinparty/) · [RemovePlayerFromParty](/lua/server/functions/removeplayerfromparty/) · [OnPartyDisband](/lua/server/callbacks/onpartydisband/) · the [Parties](/lua/server/#parties) group of the index # OnPlayerLeaveZone > A player left a zone - walked or was moved out, despawned, respawned elsewhere, disconnected. A player left a zone - walked or was moved out, despawned, respawned elsewhere, disconnected. ## Syntax ```lua function OnPlayerLeaveZone(pid, zone) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `zone` | number | the zone | ## Returns nothing ## Example ```lua function OnPlayerLeaveZone(pid, zone) if zone == arena and inDuel[pid] then SendClientMessage(pid, COLOUR_RED, "Back in the ring!") SetPlayerPos(pid, ringX, ringY, ringZ) end end ``` ## See also [OnPlayerEnterZone](/lua/server/callbacks/onplayerenterzone/) · the [Zones](/lua/server/#zones) group of the index # OnPlayerLogin > The player proved a registered name, or just registered it. The player proved a registered name, or just registered it. After `/login ` or `/register `. A registered name held in its own world is released into the shared one now; its record ([`GetSavedPlayer`](/lua/server/functions/getsavedplayer/)) is theirs; if the name is on `[accounts] admins`, [`IsPlayerAdmin`](/lua/server/functions/isplayeradmin/) is `true` from here. ## Syntax ```lua function OnPlayerLogin(pid) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns nothing ## Example ```lua function OnPlayerLogin(pid) SendClientMessage(pid, COLOUR_GREEN, "Logged in as " .. GetPlayerName(pid) .. (IsPlayerAdmin(pid) and " (admin)" or "")) end ``` ## See also [IsPlayerRegistered](/lua/server/functions/isplayerregistered/) · [IsPlayerLoggedIn](/lua/server/functions/isplayerloggedin/) · [IsPlayerAdmin](/lua/server/functions/isplayeradmin/) · the [Accounts, admins, bans and the audit](/lua/server/#accounts-admins-bans-and-the-audit) group of the index # OnPlayerMount > The player is in the saddle of a horse. The player is in the saddle of a horse. ## Syntax ```lua function OnPlayerMount(pid, id) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `id` | number | the horse | ## Returns nothing ## Example ```lua function OnPlayerMount(pid, id) SetEntityData(id, "last_rider", pid) end ``` ## See also [OnPlayerDismount](/lua/server/callbacks/onplayerdismount/) · [MountPlayer](/lua/server/functions/mountplayer/) · [GetPlayerMount](/lua/server/functions/getplayermount/) · the [Horses](/lua/server/#horses) group of the index # OnPlayerOpenContainer > A player wants to open a container - return false to refuse. A player wants to open a container - return `false` to refuse. Nothing has opened yet. Return `false` and the container stays shut for them. Otherwise their client's loot window opens on the record's contents ([`GetContainerItems`](/lua/server/functions/getcontaineritems/)) and they hold the container until they close it. ## Syntax ```lua function OnPlayerOpenContainer(pid, key) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `key` | string | the container's level name | ## Returns `false` refuses; anything else lets them open it ## Example ```lua function OnPlayerOpenContainer(pid, key) if IsPlayerInZone(pid, arena) then return false end -- no rummaging mid-duel end ``` ## See also [OnPlayerCloseContainer](/lua/server/callbacks/onplayerclosecontainer/) · [GetContainerItems](/lua/server/functions/getcontaineritems/) · [GetContainerUser](/lua/server/functions/getcontaineruser/) · the [Doors and containers](/lua/server/#doors-and-containers) group of the index # OnPlayerPickup > The player picked a pickup up - return false to take it back. The player picked a pickup up - return `false` to take it back. The player's client already holds the item when this runs. Return `false` and the item is taken from them and the pickup stays in the world for everyone. Otherwise the pickup is gone for everyone and the item is the player's - the audit counts it as explained. ## Syntax ```lua function OnPlayerPickup(pid, id) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `id` | number | the pickup entity ([`GetEntityTemplate`](/lua/server/functions/getentitytemplate/) is its class GUID) | ## Returns `false` refuses the pickup; anything else lets them keep it ## Example ```lua function OnPlayerPickup(pid, id) if GetEntityData(id, "owner") and GetEntityData(id, "owner") ~= pid then SendClientMessage(pid, COLOUR_RED, "That is not yours.") return false end return true end ``` ## See also [OnPlayerDrop](/lua/server/callbacks/onplayerdrop/) · [CreatePickup](/lua/server/functions/createpickup/) · [GetEntityTemplate](/lua/server/functions/getentitytemplate/) · the [Items and inventory](/lua/server/#items-and-inventory) group of the index # OnPlayerRequestSpawn > The client's level is ready - decide where the player spawns, or hold them. The client's level is ready - decide where the player spawns, or hold them. Set the spawn point with [`SetSpawnInfo`](/lua/server/functions/setspawninfo/) and return `true` (or nothing): the player is spawned there - or at the server's default point without one - and [`OnPlayerSpawn`](/lua/server/callbacks/onplayerspawn/) follows. Return `false` to **hold** the player: their screen says "waiting for the spawn" until the mode calls [`SpawnPlayer`](/lua/server/functions/spawnplayer/) - a lobby, a team pick, a class menu. Called once per level load, not on respawns. ## Syntax ```lua function OnPlayerRequestSpawn(pid) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `true` or nothing spawns the player now; `false` holds them until `SpawnPlayer` ## Example ```lua function OnPlayerRequestSpawn(pid) local saved = GetSavedPlayer(pid) if saved and saved.x then SetSpawnInfo(pid, saved.x, saved.y, saved.z, saved.yaw) -- back where they left else SetSpawnInfo(pid, spawnX + 1.5 * (pid % 16), spawnY, spawnZ, spawnYaw) end return true end ``` ## See also [SetSpawnInfo](/lua/server/functions/setspawninfo/) · [SpawnPlayer](/lua/server/functions/spawnplayer/) · [OnPlayerSpawn](/lua/server/callbacks/onplayerspawn/) · the [Players](/lua/server/#players) group of the index # OnPlayerSpawn > The player stands in the world and the others see them. The player stands in the world and the others see them. After the first spawn, every respawn after a death, and every [`SpawnPlayer`](/lua/server/functions/spawnplayer/). Vitals are full, the position is the spawn point, [`IsPlayerInWorld`](/lua/server/functions/isplayerinworld/) is `true`. Show the player their HUD texts here - a late joiner gets nothing shown before. ## Syntax ```lua function OnPlayerSpawn(pid) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns nothing ## Example ```lua function OnPlayerSpawn(pid) ShowHudText(clock, pid) GameText(pid, GetLevel(), 3000, GAMETEXT_CENTRE) end ``` ## See also [OnPlayerRequestSpawn](/lua/server/callbacks/onplayerrequestspawn/) · [SpawnPlayer](/lua/server/functions/spawnplayer/) · [ShowHudText](/lua/server/functions/showhudtext/) · the [Players](/lua/server/#players) group of the index # OnPlayerText > A plain chat line - return false and nobody sees it. A plain chat line - return `false` and nobody sees it. Never a `/` command (those are [`OnPlayerCommandText`](/lua/server/callbacks/onplayercommandtext/)). Anything but `false` lets the line through to everyone connected, in the player's own colour. Filters, team channels, a muted player, a whisper: return `false` and send the line on yourself with [`SendClientMessage`](/lua/server/functions/sendclientmessage/). ## Syntax ```lua function OnPlayerText(pid, text) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | who typed it | | `text` | string | the line, as typed | ## Returns `false` suppresses the line; anything else (or nothing) lets it through ## Example ```lua -- team chat: a line starting with "!" goes to the team alone function OnPlayerText(pid, text) local team = GetPlayerTeam(pid) if text:sub(1, 1) == "!" and team ~= NO_TEAM then for _, other in ipairs(GetPlayers()) do if GetPlayerTeam(other) == team then SendClientMessage(other, GetPlayerColour(pid), "[team] " .. GetPlayerName(pid) .. ": " .. text:sub(2)) end end return false end return true end ``` ## See also [OnPlayerCommandText](/lua/server/callbacks/onplayercommandtext/) · [SendClientMessage](/lua/server/functions/sendclientmessage/) · [SendClientMessageToAll](/lua/server/functions/sendclientmessagetoall/) · the [Chat and commands](/lua/server/#chat-and-commands) group of the index # OnPlayerUseDoor > A player's game opened, closed, locked or unlocked a door - return false to put it back. A player's game opened, closed, locked or unlocked a door - return `false` to put it back. `open` and `locked` are the door's state **as it is now** on the player's client. Return `false` to refuse: the record stands, the player's door is put back, nobody else hears of it. Otherwise the state becomes the record and every client shows it. ## Syntax ```lua function OnPlayerUseDoor(pid, key, open, locked) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `key` | string | the door's level name | | `open` | boolean | open now | | `locked` | boolean | locked now | ## Returns `false` refuses the change; anything else accepts it ## Example ```lua -- the vault stays shut for everyone but the guards function OnPlayerUseDoor(pid, key, open, locked) if key == VAULT_DOOR and GetPlayerData(pid, "role") ~= "guard" then SendClientMessage(pid, COLOUR_RED, "Locked. The guards have the key.") return false end end ``` ## See also [GetDoorState](/lua/server/functions/getdoorstate/) · [SetDoorState](/lua/server/functions/setdoorstate/) · [GetDoors](/lua/server/functions/getdoors/) · the [Doors and containers](/lua/server/#doors-and-containers) group of the index # OnPlayerUseItem > The player's game consumed an item - the server is about to apply its effect; return false to cancel. The player's game consumed an item - the server is about to apply its effect; return `false` to cancel. A potion drunk, food eaten, an ointment applied. The server looked the class up in the game's tables ([Consumables](/reference/consumables/)) and is about to add `health` to its own vitals (a potion's heal-over-time runs at `[combat] potion_speed` times the game's pace) and give the buff `buff` ([`GivePlayerBuff`](/lua/server/functions/giveplayerbuff/)). Return `false` to cancel both - the item is gone from the player's inventory either way, their game consumed it. Item classes the tables do not know never get here; a use of an item the player never held is refused by the [inventory audit](/lua/server/callbacks/onplayerauditviolation/) first. A drink raises the alcohol level on the side ([`OnPlayerDrunk`](/lua/server/callbacks/onplayerdrunk/)). ## Syntax ```lua function OnPlayerUseItem(pid, class, health, buff) -- ... end ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `class` | string | the item's class GUID ([`GetItemName`](/lua/server/functions/getitemname/) turns it into a name) | | `health` | number | the health the server is about to add (a negative number hurts) | | `buff` | string | the buff GUID the server is about to give; `""` = none | ## Returns `false` cancels the health and the buff; anything else lets them through ## Example ```lua -- nothing heals in the arena; bandages (an Ointment) still stop the bleeding function OnPlayerUseItem(pid, class, health, buff) local info = GetItemInfo(class) if inArena[pid] and info and info.category ~= "Ointment" and health > 0 then SendClientMessage(pid, COLOUR_RED, "That does nothing in the arena.") return false end end ``` ## See also [GivePlayerBuff](/lua/server/functions/giveplayerbuff/) · [OnPlayerDrunk](/lua/server/callbacks/onplayerdrunk/) · [GetItemInfo](/lua/server/functions/getiteminfo/) · [OnPlayerAuditViolation](/lua/server/callbacks/onplayerauditviolation/) · the [Buffs and the drink](/lua/server/#buffs-and-the-drink) group of the index # OnTick > Every simulation tick, with the time since the last one. Every simulation tick, with the time since the last one. Thirty times a second (`[rates] tick_hz`), after the tick's network events were applied. Whatever runs here runs for every tick of every player's game, so keep it to a few lines; do the heavy things on a [timer](/lua/server/functions/settimer/) every second instead. The server log reports the slowest tick while the budget is missed. ## Syntax ```lua function OnTick(dt) -- ... end ``` | Parameter | Type | | |---|---|---| | `dt` | number | seconds since the previous tick (`0.033` at 30 Hz) | ## Returns nothing ## Example ```lua local elapsed = 0 function OnTick(dt) elapsed = elapsed + dt if elapsed >= 1 then -- once a second is enough for most bookkeeping elapsed = 0 checkRound() end end ``` ## See also [SetTimer](/lua/server/functions/settimer/) · [GetServerTick](/lua/server/functions/getservertick/) · the [Server and timers](/lua/server/#server-and-timers) group of the index # AcceptPartyInvite > Accepts the player's pending invitation - the mode's /accept. Accepts the player's pending invitation - the mode's /accept. The same road as the toast's accept key: the player joins the inviter's party (making it when there is none). `false` without a pending invitation. When the party filled or ended meanwhile the invitation is cancelled instead ([`OnPartyInviteResponse`](/lua/server/callbacks/onpartyinviteresponse/) `"cancelled"`). ## Syntax ```lua AcceptPartyInvite(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the invited player | ## Returns `boolean` - `false` when nothing was pending ## Example ```lua elseif cmd == "accept" then if not AcceptPartyInvite(pid) then SendClientMessage(pid, COLOUR_RED, "Nobody invited you.") end return true ``` ## See also [DeclinePartyInvite](/lua/server/functions/declinepartyinvite/) · [InviteToParty](/lua/server/functions/invitetoparty/) · the [Parties](/lua/server/#parties) group of the index # AddPlayerToParty > Puts a player into another's party without an invitation. Puts a player into another's party without an invitation. A queue, a raid maker, a mode that groups its players itself: `pid` joins `host`'s party, which is made first (with `host` leading) when there is none. The join's reason is `"mode"`. `false` when either is not connected, `pid` is in a party already, or the party is full. ## Syntax ```lua AddPlayerToParty(host, pid) ``` | Parameter | Type | | |---|---|---| | `host` | number | a member of the party (or the leader of the new one) | | `pid` | number | the player to add | ## Returns `boolean` ## Example ```lua -- the duel queue: the two next in line become a party for the round AddPlayerToParty(queue[1], queue[2]) ``` ## See also [RemovePlayerFromParty](/lua/server/functions/removeplayerfromparty/) · [OnPlayerJoinParty](/lua/server/callbacks/onplayerjoinparty/) · the [Parties](/lua/server/#parties) group of the index # AddSpawnPoint > Remembers a spawn point under a tag. Remembers a spawn point under a tag. A plain list the prelude keeps for the mode - nothing on the server side. Points are grouped by `tag` (`""` without one): one list per team, per arena, per role. ## Syntax ```lua AddSpawnPoint(x, y, z, yaw [, tag]) ``` | Parameter | Type | | |---|---|---| | `x` | number | metres | | `y` | number | metres | | `z` | number \| nil | metres; `nil` = `-1`, on the terrain | | `yaw` | number | degrees (`0` without) | | `tag` | string | the list to add to *(optional)* | ## Returns `number` - how many points the list holds now ## Example ```lua AddSpawnPoint(1280, 1088, -1, 0, "red") AddSpawnPoint(1284, 1088, -1, 0, "red") AddSpawnPoint(1310, 1088, -1, 180, "blue") ``` ## See also [GetRandomSpawnPoint](/lua/server/functions/getrandomspawnpoint/) · [GetSpawnPoints](/lua/server/functions/getspawnpoints/) · [ClearSpawnPoints](/lua/server/functions/clearspawnpoints/) · [SetSpawnInfo](/lua/server/functions/setspawninfo/) · the [Players](/lua/server/#players) group of the index # AreFighting > Whether two players are in a fight right now. Whether two players are in a fight right now. ## Syntax ```lua AreFighting(a, b) ``` | Parameter | Type | | |---|---|---| | `a` | number | one player | | `b` | number | the other | ## Returns `boolean` ## Example ```lua if not AreFighting(pid, target) then SendClientMessage(pid, COLOUR_RED, "You are not fighting them.") end ``` ## See also [StartFight](/lua/server/functions/startfight/) · [GetPlayerOpponents](/lua/server/functions/getplayeropponents/) · the [Combat](/lua/server/#combat) group of the index # ArePartyMembers > Whether two players are in one party. Whether two players are in one party. For the mode's own rules - loot shared with the party, a duel refused between friends, a party chat. ## Syntax ```lua ArePartyMembers(a, b) ``` | Parameter | Type | | |---|---|---| | `a` | number | one player | | `b` | number | the other | ## Returns `boolean` ## Example ```lua function OnPlayerDamage(pid, attacker, damage, zone, part, weapon, dtype) -- friendly fire is refused by the server already; this is for a mode that turned it on and wants half damage if attacker >= 0 and ArePartyMembers(pid, attacker) then return damage * 0.5 end end ``` ## See also [GetPlayerParty](/lua/server/functions/getplayerparty/) · the [Parties](/lua/server/#parties) group of the index # Ban > Kicks the player and bans their name and address. Kicks the player and bans their name and address. A `Hello` under the name or from the address is refused with the reason until the ban runs out; `seconds` `0` or none = for good. Written to `data/bans.json`. ## Syntax ```lua Ban(pid, reason [, seconds]) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `reason` | string | shown to the player now and at every refused join | | `seconds` | number | how long; `0` or none = for good *(optional)* | ## Returns `boolean` - `false` when not connected ## Example ```lua Ban(pid, "speed hacking", 7 * 24 * 3600) -- a week ``` ## See also [BanName](/lua/server/functions/banname/) · [BanAddress](/lua/server/functions/banaddress/) · [Unban](/lua/server/functions/unban/) · [IsBanned](/lua/server/functions/isbanned/) · [Kick](/lua/server/functions/kick/) · the [Accounts, admins, bans and the audit](/lua/server/#accounts-admins-bans-and-the-audit) group of the index # BanAddress > Bans an address; whoever is on from it is kicked. Bans an address; whoever is on from it is kicked. ## Syntax ```lua BanAddress(address, reason [, seconds]) ``` | Parameter | Type | | |---|---|---| | `address` | string | `"a.b.c.d"` | | `reason` | string | the reason | | `seconds` | number | how long; `0` or none = for good *(optional)* | ## Returns nothing ## Example ```lua BanAddress(GetPlayerIP(pid), "ban evasion", 3600) ``` ## See also [Ban](/lua/server/functions/ban/) · [BanName](/lua/server/functions/banname/) · [Unban](/lua/server/functions/unban/) · [GetPlayerIP](/lua/server/functions/getplayerip/) · the [Accounts, admins, bans and the audit](/lua/server/#accounts-admins-bans-and-the-audit) group of the index # BanName > Bans a name; whoever is on under it is kicked. Bans a name; whoever is on under it is kicked. ## Syntax ```lua BanName(name, reason [, seconds]) ``` | Parameter | Type | | |---|---|---| | `name` | string | the player name (case-insensitive) | | `reason` | string | the reason | | `seconds` | number | how long; `0` or none = for good *(optional)* | ## Returns nothing ## Example ```lua BanName("Griefer", "you know why") ``` ## See also [Ban](/lua/server/functions/ban/) · [BanAddress](/lua/server/functions/banaddress/) · [Unban](/lua/server/functions/unban/) · the [Accounts, admins, bans and the audit](/lua/server/#accounts-admins-bans-and-the-audit) group of the index # ClaimBuffClasses > Names the buff classes the server takes over from the game. Names the buff classes the server takes over from the game. With a class claimed, a buff of that class a player's game applies by itself - a potion drunk, a poison, the game's own drunkenness - is undone on their client within a second unless the server gave it ([`GivePlayerBuff`](/lua/server/functions/giveplayerbuff/)). The way a mode keeps the game's own potions from opening a hole in the server-owned health: with `Potion` claimed, a potion only works through the server's [consumption path](/lua/server/callbacks/onplayeruseitem/). The class names are the pages of [the buff list](/reference/buffs/) - `Potion`, `Poison`, `Alcohol`, `Hangover`, `Unconsciousness`, `Plague` ...; an unknown one is logged and ignored. The whole list replaces the previous one and goes to every client; `{}` claims nothing. Nothing is claimed by default. ## Syntax ```lua ClaimBuffClasses(classes) ``` | Parameter | Type | | |---|---|---| | `classes` | table | a list of class names | ## Returns nothing ## Example ```lua function OnGameModeInit() ClaimBuffClasses({"Potion", "Poison", "Alcohol", "Hangover"}) end ``` ## See also [GetClaimedBuffClasses](/lua/server/functions/getclaimedbuffclasses/) · [GivePlayerBuff](/lua/server/functions/giveplayerbuff/) · [OnPlayerUseItem](/lua/server/callbacks/onplayeruseitem/) · the [Buffs and the drink](/lua/server/#buffs-and-the-drink) group of the index # ClearPlayerBuffs > Takes every server-given buff off the player. Takes every server-given buff off the player. ## Syntax ```lua ClearPlayerBuffs(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns nothing ## Example ```lua ClearPlayerBuffs(pid) ``` ## See also [GetPlayerBuffs](/lua/server/functions/getplayerbuffs/) · [HealPlayer](/lua/server/functions/healplayer/) · the [Buffs and the drink](/lua/server/#buffs-and-the-drink) group of the index # ClearSpawnPoints > Forgets the spawn points of a tag. Forgets the spawn points of a tag. ## Syntax ```lua ClearSpawnPoints([tag]) ``` | Parameter | Type | | |---|---|---| | `tag` | string | the list (`""` without) *(optional)* | ## Returns nothing ## Example ```lua ClearSpawnPoints("red") ``` ## See also [AddSpawnPoint](/lua/server/functions/addspawnpoint/) · the [Players](/lua/server/#players) group of the index # CreateActor > Creates an NPC actor - a dressed, named body the server owns. Creates an NPC actor - a dressed, named body the server owns. `soul` is the face and build: a soul of any archetype from [the souls](/reference/souls/) by name, id or GUID (`nil` = the server's appearance pool for the name, like a player without a `SetSpawnInfo` face). `name` is the label over its head (`nil` = none). `clothing` and `weapons` are preset GUIDs ([clothing](/reference/clothing-presets/), [weapons](/reference/weapon-presets/); `nil` = the server's `[spawn]` presets, like a player; `weapons = "none"` makes an unarmed one that fights with its fists). `world` is the virtual world (`nil` = the shared one). The actor stands where it is put until [`MoveActor`](/lua/server/functions/moveactor/); its health is 100. `nil` when the soul is unknown or the world is full. ## Syntax ```lua CreateActor(soul, x, y, z, yaw [, name, clothing, weapons, world]) ``` | Parameter | Type | | |---|---|---| | `soul` | string \| number \| nil | a soul's name, id or GUID; `nil` = the server's pool | | `x` | number | metres | | `y` | number | metres | | `z` | number | metres | | `yaw` | number | degrees (`0` without) | | `name` | string | the label over its head; `nil` = none *(optional)* | | `clothing` | string | a clothing preset GUID; `nil` = the server default *(optional)* | | `weapons` | string | a weapon preset GUID; `nil` = the server default; `"none"` = unarmed *(optional)* | | `world` | number | the virtual world; `nil` = the shared one *(optional)* | ## Returns `number` - the actor's entity id; `nil` when it could not be made ## Example ```lua -- a guard at the gate, dressed by the server, facing south local guard = CreateActor("test_cuman_ai", 1290, 1095, -1, 180, "Gate guard") SetEntityData(guard, "role", "guard") -- an unarmed brawler set on the caller local brawler = CreateActor(nil, x + 3, y, z, 180, "Brawler", nil, "none") SetActorHostile(pid, brawler, true) ``` ## See also [MoveActor](/lua/server/functions/moveactor/) · [SetActorAnim](/lua/server/functions/setactoranim/) · [SetActorHostile](/lua/server/functions/setactorhostile/) · [GetEntityName](/lua/server/functions/getentityname/) · [DestroyEntity](/lua/server/functions/destroyentity/) · [FindSouls](/lua/server/functions/findsouls/) · the [NPC actors](/lua/server/#npc-actors) group of the index # CreateCircleZone > A circular zone around a point - a cylinder of any height, or of a band. A circular zone around a point - a cylinder of any height, or of a band. Without `zMin` and `zMax` the height does not matter; with `zMin < zMax` only that band counts. ## Syntax ```lua CreateCircleZone(x, y, radius [, zMin, zMax]) ``` | Parameter | Type | | |---|---|---| | `x` | number | the centre, metres | | `y` | number | metres | | `radius` | number | metres | | `zMin` | number | the bottom of the band *(optional)* | | `zMax` | number | the top of the band; without a band any height counts *(optional)* | ## Returns `number` - the zone's id; `nil` when none is free ## Example ```lua local spawnX, spawnY = GetDefaultSpawn() local spawnZone = CreateCircleZone(spawnX, spawnY, 12) ``` ## See also [CreateZone](/lua/server/functions/createzone/) · [IsPlayerInZone](/lua/server/functions/isplayerinzone/) · the [Zones](/lua/server/#zones) group of the index # CreateDog > Gives a player a dog that follows them. Gives a player a dog that follows them. `soul` names the look - a soul of the Dog archetype from [the dog souls](/reference/souls/dog/) by name, id or GUID; `nil` = the plain dog. `x, y, z, yaw` is where it appears; without them, two metres in front of the master. A player who already has a dog gets the one they have. `nil` when the player is not in the world or the world is full. ## Syntax ```lua CreateDog(pid [, soul, x, y, z, yaw]) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the master | | `soul` | string \| number | a dog soul's name, id or GUID; `nil` = the plain dog *(optional)* | | `x` | number | metres; without a point the dog appears in front of the master *(optional)* | | `y` | number | metres *(optional)* | | `z` | number | metres *(optional)* | | `yaw` | number | degrees *(optional)* | ## Returns `number` - the dog's entity id; `nil` when it could not be made ## Example ```lua function OnPlayerSpawn(pid) if GetPlayerData(pid, "houndmaster") then CreateDog(pid) end end ``` ## See also [GetPlayerDog](/lua/server/functions/getplayerdog/) · [DestroyEntity](/lua/server/functions/destroyentity/) · [FindSouls](/lua/server/functions/findsouls/) · the [Dogs](/lua/server/#dogs) group of the index # CreateHorse > Puts a horse in the world. Puts a horse in the world. `controllerPid` is the player whose client simulates it (usually the one it is for); with `nil` nobody does and it stands still until the server hands it to the nearest player within 30 m. `world` is the virtual world (`nil` = the controller's; `0` without one). `soul` is the breed - a Horse-archetype soul by name (`Horse2`, `Pebbles`), id or GUID from [the horse souls](/reference/souls/horse/); `nil` = the server's `[spawn] horse_soul`; a key that is not a horse makes no horse. `nil` when the world is full (`[world] max_entities`). ## Syntax ```lua CreateHorse(x, y, z, yaw [, controllerPid, world, soul]) ``` | Parameter | Type | | |---|---|---| | `x` | number | metres | | `y` | number | metres | | `z` | number | metres | | `yaw` | number | degrees (`0` without) | | `controllerPid` | number | the player whose client simulates it; `nil` = nobody yet *(optional)* | | `world` | number | the virtual world; `nil` = the controller's *(optional)* | | `soul` | string \| number | the breed - a horse soul's name, id or GUID; `nil` = the server default *(optional)* | ## Returns `number` - the horse's entity id; `nil` when it could not be made ## Example ```lua -- /steed: a horse in front of the player, mounted at once local x, y, z = GetPlayerPos(pid) local r = math.rad(GetPlayerYaw(pid)) local horse = CreateHorse(x - math.sin(r) * 3, y + math.cos(r) * 3, z, GetPlayerYaw(pid), pid, nil, "Pebbles") if horse then MountPlayer(pid, horse) end ``` ## See also [MountPlayer](/lua/server/functions/mountplayer/) · [GetPlayerHorse](/lua/server/functions/getplayerhorse/) · [GetHorseSoul](/lua/server/functions/gethorsesoul/) · [DestroyEntity](/lua/server/functions/destroyentity/) · the [Horses](/lua/server/#horses) group of the index # CreateHudText > A line of text at a screen position, shown to the players you choose. A line of text at a screen position, shown to the players you choose. `x` and `y` are fractions of the screen from the top left - `0.5, 0.02` is the top centre, `0.99, 0.02` the top right with `HUD_ALIGN_RIGHT`, `0.02, 0.5` the left edge halfway down - so the line lands in the same place at every resolution. The element is shown to **nobody** until [`ShowHudText`](/lua/server/functions/showhudtext/) or [`ShowHudTextForAll`](/lua/server/functions/showhudtextforall/); a change to its text or look is re-sent to everyone it is shown to. A shown element survives its player's respawns and goes with their disconnect; the mode's elements go with a reload. Ids start at `1`; there are 4096. ## Syntax ```lua CreateHudText(x, y, text [, colour, scale, align]) ``` | Parameter | Type | | |---|---|---| | `x` | number | `0` .. `1` of the screen width from the left | | `y` | number | `0` .. `1` of the screen height from the top | | `text` | string | the line | | `colour` | number | `0xRRGGBBAA` (white) *(optional)* | | `scale` | number | `1` = the HUD's own text size; `0.5` .. `5` *(optional)* | | `align` | number | `HUD_ALIGN_LEFT` (the default), `HUD_ALIGN_CENTRE` or `HUD_ALIGN_RIGHT` - which side of the line sits at `x` *(optional)* | ## Returns `number` - the element's id; `nil` when the ids are used up ## Example ```lua local clock function OnGameModeInit() clock = CreateHudText(0.99, 0.02, FormatWorldTime(), COLOUR_YELLOW, 1.0, HUD_ALIGN_RIGHT) SetTimer(function() SetHudText(clock, FormatWorldTime()) end, 2000, true) end function OnPlayerSpawn(pid) ShowHudText(clock, pid) end ``` ## See also [ShowHudText](/lua/server/functions/showhudtext/) · [SetHudText](/lua/server/functions/sethudtext/) · [DestroyHudText](/lua/server/functions/destroyhudtext/) · [GetHudTexts](/lua/server/functions/gethudtexts/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # CreatePickup > Puts an item on the ground for everyone to see and anyone to take. Puts an item on the ground for everyone to see and anyone to take. A pickup entity of `ENTITY_ITEM`: every client in range shows the item lying at the point; whoever takes it gets the item ([`OnPlayerPickup`](/lua/server/callbacks/onplayerpickup/)) and the pickup is gone for everyone. `item` is any key of [the item catalogue](/reference/items/). `world` is the virtual world (`nil` = the shared one). `nil` when the key is unknown or the world is full (`[world] max_entities`). The `/item` built-in places one in front of an admin. ## Syntax ```lua CreatePickup(item, x, y, z [, yaw, world]) ``` | Parameter | Type | | |---|---|---| | `item` | string \| number | the item's name, id, English name or GUID | | `x` | number | metres | | `y` | number | metres | | `z` | number | metres | | `yaw` | number | degrees (`0` without) *(optional)* | | `world` | number | the virtual world; `nil` = the shared one *(optional)* | ## Returns `number` - the pickup's entity id; `nil` when it could not be made ## Example ```lua -- a reward on the arena floor local x, y, z = GetPlayerPos(loser) local id = CreatePickup("longSwordDuel", x, y, z) if id then SetEntityData(id, "owner", winner) end ``` ## See also [OnPlayerPickup](/lua/server/callbacks/onplayerpickup/) · [GivePlayerItem](/lua/server/functions/giveplayeritem/) · [DestroyEntity](/lua/server/functions/destroyentity/) · [GetEntityTemplate](/lua/server/functions/getentitytemplate/) · the [Items and inventory](/lua/server/#items-and-inventory) group of the index # CreateProp > Places a static mesh in the world. Places a static mesh in the world. An entity of `ENTITY_PROP` every client in range shows. `mesh` is a key of [the mesh list](/reference/meshes/); without the tables export only a path passes. `scale` is uniform (`1` = the mesh's own size); `rigid` makes it a physics body on each client (false = static); `world` is the virtual world (`nil` = the shared one). Nobody controls a prop, nobody mounts or takes it; [`DestroyEntity`](/lua/server/functions/destroyentity/) removes it, a reload removes them all. `nil` when the mesh resolves to nothing or the world is full. ## Syntax ```lua CreateProp(mesh, x, y, z [, yaw, scale, rigid, world]) ``` | Parameter | Type | | |---|---|---| | `mesh` | string \| number | the mesh's id, file name or path | | `x` | number | metres | | `y` | number | metres | | `z` | number | metres | | `yaw` | number | degrees (`0` without) *(optional)* | | `scale` | number | uniform scale (`1`) *(optional)* | | `rigid` | boolean | `true` = a pushable physics body on each client; `false` = static *(optional)* | | `world` | number | the virtual world; `nil` = the shared one *(optional)* | ## Returns `number` - the prop's entity id; `nil` when it could not be made ## Example ```lua -- an arena ring of barrels for i = 0, 11 do local a = math.rad(i * 30) CreateProp("barrel_a", cx + math.cos(a) * 6, cy + math.sin(a) * 6, cz, i * 30) end ``` ## See also [GetMeshPath](/lua/server/functions/getmeshpath/) · [FindMeshes](/lua/server/functions/findmeshes/) · [GetEntityScale](/lua/server/functions/getentityscale/) · [IsEntityRigid](/lua/server/functions/isentityrigid/) · [DestroyEntity](/lua/server/functions/destroyentity/) · the [Props](/lua/server/#props) group of the index # CreateZone > A box zone between two corners. A box zone between two corners. The corners may be given in any order. `nil` when the 4096 ids are used up. ## Syntax ```lua CreateZone(x1, y1, z1, x2, y2, z2) ``` | Parameter | Type | | |---|---|---| | `x1` | number | one corner, metres | | `y1` | number | metres | | `z1` | number | metres | | `x2` | number | the opposite corner | | `y2` | number | metres | | `z2` | number | metres | ## Returns `number` - the zone's id; `nil` when none is free ## Example ```lua local courtyard = CreateZone(1260, 1070, 20, 1300, 1110, 40) ``` ## See also [CreateCircleZone](/lua/server/functions/createcirclezone/) · [DestroyZone](/lua/server/functions/destroyzone/) · [OnPlayerEnterZone](/lua/server/callbacks/onplayerenterzone/) · [GetZoneInfo](/lua/server/functions/getzoneinfo/) · the [Zones](/lua/server/#zones) group of the index # DeclinePartyInvite > Declines the player's pending invitation - the mode's /decline. Declines the player's pending invitation - the mode's /decline. ## Syntax ```lua DeclinePartyInvite(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the invited player | ## Returns `boolean` - `false` when nothing was pending ## Example ```lua elseif cmd == "decline" then DeclinePartyInvite(pid) return true ``` ## See also [AcceptPartyInvite](/lua/server/functions/acceptpartyinvite/) · [InviteToParty](/lua/server/functions/invitetoparty/) · the [Parties](/lua/server/#parties) group of the index # DestroyEntity > Removes an entity from the world, for everyone. Removes an entity from the world, for everyone. A horse under a rider dismounts them; a pickup vanishes; an actor's corpse is gone; a dog leaves. Anything a mode created is also removed by a reload. ## Syntax ```lua DestroyEntity(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | ## Returns `boolean` - `false` when there is no such entity ## Example ```lua SetTimer(function() DestroyEntity(corpse) end, 20000) ``` ## See also [GetEntities](/lua/server/functions/getentities/) · [CreatePickup](/lua/server/functions/createpickup/) · [CreateHorse](/lua/server/functions/createhorse/) · the [World entities](/lua/server/#world-entities) group of the index # DestroyHudText > Removes a HUD text from every screen. Removes a HUD text from every screen. ## Syntax ```lua DestroyHudText(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the element | ## Returns `boolean` - `false` when there is no such element ## Example ```lua DestroyHudText(roundTimer) ``` ## See also [CreateHudText](/lua/server/functions/createhudtext/) · [HideHudTextForAll](/lua/server/functions/hidehudtextforall/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # DestroyZone > Removes a zone. Removes a zone. Nobody hears a leave for it. Its id may be reused by the next zone. ## Syntax ```lua DestroyZone(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the zone | ## Returns `boolean` - `false` when there is no such zone ## Example ```lua DestroyZone(capturePoint) ``` ## See also [CreateZone](/lua/server/functions/createzone/) · [GetZones](/lua/server/functions/getzones/) · the [Zones](/lua/server/#zones) group of the index # DisbandParty > Ends a party. Ends a party. Every member leaves with `"disband"`, then [`OnPartyDisband`](/lua/server/callbacks/onpartydisband/) fires with `"mode"`. ## Syntax ```lua DisbandParty(party) ``` | Parameter | Type | | |---|---|---| | `party` | number | the party | ## Returns `boolean` - `false` for an unknown party ## Example ```lua elseif cmd == "disband" then local party = GetPlayerParty(pid) if party and GetPartyLeader(party) == pid then DisbandParty(party) end return true ``` ## See also [RemovePlayerFromParty](/lua/server/functions/removeplayerfromparty/) · [OnPartyDisband](/lua/server/callbacks/onpartydisband/) · the [Parties](/lua/server/#parties) group of the index # EndFight > Ends the fight between two players. Ends the fight between two players. Both clients drop the lock; `OnFightEnd` fires with `"mode"`. Nothing happens when the two were not fighting. `/peace` ends every fight of the caller the same way. ## Syntax ```lua EndFight(a, b) ``` | Parameter | Type | | |---|---|---| | `a` | number | one player | | `b` | number | the other | ## Returns `boolean` - `false` when one of them is not connected ## Example ```lua local function endDuel(a, b) EndFight(a, b) HealPlayer(a) HealPlayer(b) end ``` ## See also [StartFight](/lua/server/functions/startfight/) · [OnFightEnd](/lua/server/callbacks/onfightend/) · the [Combat](/lua/server/#combat) group of the index # FindBuffs > Buffs whose name, English name or class holds every word of a pattern. Buffs whose name, English name or class holds every word of a pattern. ## Syntax ```lua FindBuffs(pattern [, max]) ``` | Parameter | Type | | |---|---|---| | `pattern` | string | words to look for, case-insensitive | | `max` | number | at most this many (`10`) *(optional)* | ## Returns `table` - a list of `{id=, name=, guid=, class=, display=}` ## Example ```lua for _, b in ipairs(FindBuffs("potion strength", 5)) do Log(b.id, b.name, b.display) end ``` ## See also [GetBuffInfo](/lua/server/functions/getbuffinfo/) · [GivePlayerBuff](/lua/server/functions/giveplayerbuff/) · the [Catalogues](/lua/server/#catalogues) group of the index # FindItems > Items whose name, English name or category holds every word of a pattern. Items whose name, English name or category holds every word of a pattern. ## Syntax ```lua FindItems(pattern [, max]) ``` | Parameter | Type | | |---|---|---| | `pattern` | string | words to look for, case-insensitive | | `max` | number | at most this many (`10`) *(optional)* | ## Returns `table` - a list of `{id=, name=, class=, category=, display=}` ## Example ```lua -- /items local found = FindItems(args, 8) local names = {} for _, it in ipairs(found) do names[#names + 1] = it.id .. " " .. it.name end SendClientMessage(pid, COLOUR_SERVER, #names > 0 and table.concat(names, ", ") or "nothing matches") ``` ## See also [GetItemInfo](/lua/server/functions/getiteminfo/) · [GetItemClass](/lua/server/functions/getitemclass/) · the [Catalogues](/lua/server/#catalogues) group of the index # FindMeshes > Meshes whose path holds every word of a pattern. Meshes whose path holds every word of a pattern. ## Syntax ```lua FindMeshes(pattern [, max]) ``` | Parameter | Type | | |---|---|---| | `pattern` | string | words to look for in the path, case-insensitive | | `max` | number | at most this many (`10`) *(optional)* | ## Returns `table` - a list of `{id=, path=, name=}` ## Example ```lua for _, m in ipairs(FindMeshes("barrel", 5)) do Log(m.id, m.name, m.path) end ``` ## See also [GetMeshPath](/lua/server/functions/getmeshpath/) · [CreateProp](/lua/server/functions/createprop/) · the [Props](/lua/server/#props) group of the index # FindPath > The corners of a walk between two points on the navigation mesh. The corners of a walk between two points on the navigation mesh. The route an NPC actor would take, string-pulled to its corners: the first is the start snapped to the mesh, the last the end. `nil` when either point is off the mesh (more than 2 m from it sideways or 4 m up or down - a wall, a roof, the air), when no way joins them, or without a navmesh. Positions in metres, the level's world space. A path takes well under a millisecond across a village; a mode that asks every tick for every actor should not. ## Syntax ```lua FindPath(x1, y1, z1, x2, y2, z2) ``` | Parameter | Type | | |---|---|---| | `x1` | number | the start | | `y1` | number | | | `z1` | number | | | `x2` | number | the end | | `y2` | number | | | `z2` | number | | ## Returns `table` of `{x=, y=, z=}` corners, the start first; `nil` for no way ## Example ```lua local path = FindPath(px, py, pz, gx, gy, gz) if path then SendClientMessage(pid, COLOUR_SERVER, #path .. " corners to the goal") end ``` ## See also [IsReachable](/lua/server/functions/isreachable/) · [MoveActor](/lua/server/functions/moveactor/) · [GetNavmeshHeight](/lua/server/functions/getnavmeshheight/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # FindSouls > Souls whose name or archetype holds every word of a pattern. Souls whose name or archetype holds every word of a pattern. `"Horse"` alone lists the breeds; `"Dog"` the dogs; a word of a name narrows it. ## Syntax ```lua FindSouls(pattern [, max]) ``` | Parameter | Type | | |---|---|---| | `pattern` | string | words to look for, case-insensitive | | `max` | number | at most this many (`10`) *(optional)* | ## Returns `table` - a list of `{id=, name=, guid=, archetype=}` ## Example ```lua for _, s in ipairs(FindSouls("horse black", 5)) do Log(s.id, s.name) end ``` ## See also [GetSoulInfo](/lua/server/functions/getsoulinfo/) · [GetHorseSoul](/lua/server/functions/gethorsesoul/) · [CreateActor](/lua/server/functions/createactor/) · the [Catalogues](/lua/server/#catalogues) group of the index # FormatWorldTime > Hours as HH:MM. Hours as HH:MM. ## Syntax ```lua FormatWorldTime([hours]) ``` | Parameter | Type | | |---|---|---| | `hours` | number | hours since midnight; without it, the world clock now *(optional)* | ## Returns `string` - `"13:30"` ## Example ```lua SetHudText(clock, FormatWorldTime()) ``` ## See also [GetWorldTime](/lua/server/functions/getworldtime/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # GameText > One big line on the player's screen for a while. One big line on the player's screen for a while. A line in a large serif, fading out over its last half second; a new one replaces the old. `style` is `GAMETEXT_CENTRE` (`0`, big in the middle), `GAMETEXT_TOP` (`1`, under the top edge) or `GAMETEXT_LOWER` (`2`, the lower third, like a subtitle). ## Syntax ```lua GameText(pid, text [, ms, style]) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `text` | string | the line | | `ms` | number | how long it stays, milliseconds (`3000`; `100` .. `60000`) *(optional)* | | `style` | number | `GAMETEXT_CENTRE` (the default), `GAMETEXT_TOP` or `GAMETEXT_LOWER` *(optional)* | ## Returns `boolean` - `false` when not connected ## Example ```lua GameText(pid, "You win!", 4000) GameText(pid, "The spawn", 1500, GAMETEXT_LOWER) ``` ## See also [GameTextForAll](/lua/server/functions/gametextforall/) · [SendClientMessage](/lua/server/functions/sendclientmessage/) · [CreateHudText](/lua/server/functions/createhudtext/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # GameTextForAll > One big line on every screen. One big line on every screen. ## Syntax ```lua GameTextForAll(text [, ms, style]) ``` | Parameter | Type | | |---|---|---| | `text` | string | the line | | `ms` | number | milliseconds (`3000`; `100` .. `60000`) *(optional)* | | `style` | number | `GAMETEXT_CENTRE`, `GAMETEXT_TOP` or `GAMETEXT_LOWER` *(optional)* | ## Returns nothing ## Example ```lua GameTextForAll("Round 3", 2500, GAMETEXT_TOP) ``` ## See also [GameText](/lua/server/functions/gametext/) · [SendClientMessageToAll](/lua/server/functions/sendclientmessagetoall/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # GetActorBleeding > How fast an actor is bleeding, in health per second. How fast an actor is bleeding, in health per second. A cut opens a bleed for `[combat] bleed_seconds`; `0` = not bleeding. A bleed-out is the last attacker's kill ([`OnActorDeath`](/lua/server/callbacks/onactordeath/)); [`HealActor`](/lua/server/functions/healactor/) stops it. ## Syntax ```lua GetActorBleeding(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | ## Returns `number` - health lost per second; `0` = not bleeding ## Example ```lua if GetActorBleeding(id) > 0.5 then HealActor(id) end -- the demo character never bleeds out ``` ## See also [IsActorBleeding](/lua/server/functions/isactorbleeding/) · [HealActor](/lua/server/functions/healactor/) · [GetActorHealth](/lua/server/functions/getactorhealth/) · the [NPC actors](/lua/server/#npc-actors) group of the index # GetActorHealth > An actor's health. An actor's health. ## Syntax ```lua GetActorHealth(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | ## Returns `number` - `0` .. `100`; `0` for anything but an actor ## Example ```lua SendClientMessage(pid, COLOUR_SERVER, GetEntityName(id) .. ": " .. GetActorHealth(id) .. " health") ``` ## See also [SetActorHealth](/lua/server/functions/setactorhealth/) · [IsActorDead](/lua/server/functions/isactordead/) · [OnActorDamage](/lua/server/callbacks/onactordamage/) · the [NPC actors](/lua/server/#npc-actors) group of the index # GetActorInjuries > An actor's wounded body parts. An actor's wounded body parts. A list of body parts, `BODY_PART_HEAD` .. `BODY_PART_LEG_RIGHT` (`1` .. `6`); `{}` when whole. A blow of at least `[combat] injury_threshold` wounds the part it struck ([`OnActorInjury`](/lua/server/callbacks/onactorinjury/)). ## Syntax ```lua GetActorInjuries(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | ## Returns `table` - a list of body part ids ## Example ```lua for _, part in ipairs(GetActorInjuries(id)) do Log(GetEntityName(id), "wounded:", GetBodyPartName(part)) end ``` ## See also [IsActorInjured](/lua/server/functions/isactorinjured/) · [GetBodyPartName](/lua/server/functions/getbodypartname/) · [OnActorInjury](/lua/server/callbacks/onactorinjury/) · [HealActor](/lua/server/functions/healactor/) · the [NPC actors](/lua/server/#npc-actors) group of the index # GetAdminNames > The names on the server's admin list. The names on the server's admin list. ## Syntax ```lua GetAdminNames() ``` ## Returns `table` - a list of names (`[accounts] admins`) ## Example ```lua SendClientMessage(pid, COLOUR_SERVER, "admins: " .. table.concat(GetAdminNames(), ", ")) ``` ## See also [IsPlayerAdmin](/lua/server/functions/isplayeradmin/) · the [Accounts, admins, bans and the audit](/lua/server/#accounts-admins-bans-and-the-audit) group of the index # GetBodyPartName > The name of a body part id. The name of a body part id. ## Syntax ```lua GetBodyPartName(part) ``` | Parameter | Type | | |---|---|---| | `part` | number | `1` head, `2` torso, `3` left arm, `4` right arm, `5` left leg, `6` right leg | ## Returns `string` - `"head"`, `"torso"`, `"arm_left"`, `"arm_right"`, `"leg_left"`, `"leg_right"`; `""` for anything else ## Example ```lua function OnPlayerInjury(pid, attacker, part) SendClientMessage(pid, COLOUR_RED, "your " .. GetBodyPartName(part):gsub("_", " ") .. " is injured") end ``` ## See also [GetPlayerInjuries](/lua/server/functions/getplayerinjuries/) · [OnPlayerDamage](/lua/server/callbacks/onplayerdamage/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # GetBuffGuid > The GUID a buff key stands for. The GUID a buff key stands for. ## Syntax ```lua GetBuffGuid(key) ``` | Parameter | Type | | |---|---|---| | `key` | string \| number | a buff's name (`well_rested`), id or GUID | ## Returns `string` - the buff GUID; `nil` when unknown ## Example ```lua local guid = GetBuffGuid("well_rested") ``` ## See also [GetBuffInfo](/lua/server/functions/getbuffinfo/) · [FindBuffs](/lua/server/functions/findbuffs/) · [GivePlayerBuff](/lua/server/functions/giveplayerbuff/) · the [Catalogues](/lua/server/#catalogues) group of the index # GetBuffInfo > The buff catalogue's entry for a key. The buff catalogue's entry for a key. ## Syntax ```lua GetBuffInfo(key) ``` | Parameter | Type | | |---|---|---| | `key` | string \| number | a buff's name, id or GUID | ## Returns `table` - `{id=, name=, guid=, class=, display=, duration=}`: the class is what `claimed_buffs` names, the duration the game's own in game minutes (`-1` = until removed); `nil` when unknown ## Example ```lua for _, guid in ipairs(GetPlayerBuffs(pid)) do local b = GetBuffInfo(guid) Log(b and b.name or guid, b and b.class or "") end ``` ## See also [GetBuffGuid](/lua/server/functions/getbuffguid/) · [FindBuffs](/lua/server/functions/findbuffs/) · [GetPlayerBuffs](/lua/server/functions/getplayerbuffs/) · the [Catalogues](/lua/server/#catalogues) group of the index # GetClaimedBuffClasses > The buff classes the server has claimed. The buff classes the server has claimed. A claimed class is one the server takes over: every client undoes the game's own application of any buff of that class unless the server gave it. `[combat] claimed_buffs` sets the list at startup; [`ClaimBuffClasses`](/lua/server/functions/claimbuffclasses/) changes it. ## Syntax ```lua GetClaimedBuffClasses() ``` ## Returns `table` - a list of class names (`"Potion"`, `"Poison"` ...); `{}` when nothing is claimed ## Example ```lua Log("claimed:", table.concat(GetClaimedBuffClasses(), ", ")) ``` ## See also [ClaimBuffClasses](/lua/server/functions/claimbuffclasses/) · the [Buffs and the drink](/lua/server/#buffs-and-the-drink) group of the index # GetContainerItems > A container's contents of record. A container's contents of record. One entry per stack: the item class GUID ([`GetItemName`](/lua/server/functions/getitemname/) names it), how many, the item's condition in percent. `nil` when nobody has opened the container yet - its contents are still the level's own, unknown to the server. ## Syntax ```lua GetContainerItems(key) ``` | Parameter | Type | | |---|---|---| | `key` | string | the container's level name | ## Returns `table` - a list of `{class=, amount=, health=}`; `nil` when never opened ## Example ```lua local items = GetContainerItems(key) if items then for _, stack in ipairs(items) do Log(GetItemName(stack.class), "x", stack.amount) end end ``` ## See also [SetContainerItems](/lua/server/functions/setcontaineritems/) · [GetContainers](/lua/server/functions/getcontainers/) · [OnPlayerCloseContainer](/lua/server/callbacks/onplayerclosecontainer/) · the [Doors and containers](/lua/server/#doors-and-containers) group of the index # GetContainers > Every container anyone opened. Every container anyone opened. ## Syntax ```lua GetContainers() ``` ## Returns `table` - a list of container keys ## Example ```lua Log(#GetContainers(), "containers have been opened") ``` ## See also [GetContainerItems](/lua/server/functions/getcontaineritems/) · [GetContainerUser](/lua/server/functions/getcontaineruser/) · the [Doors and containers](/lua/server/#doors-and-containers) group of the index # GetContainerUser > Who has a container open right now. Who has a container open right now. ## Syntax ```lua GetContainerUser(key) ``` | Parameter | Type | | |---|---|---| | `key` | string | the container's level name | ## Returns `number` - a pid; `nil` when nobody ## Example ```lua local who = GetContainerUser(key) if who then SendClientMessage(pid, COLOUR_RED, GetPlayerName(who) .. " is looking through it.") end ``` ## See also [OnPlayerOpenContainer](/lua/server/callbacks/onplayeropencontainer/) · [GetContainers](/lua/server/functions/getcontainers/) · the [Doors and containers](/lua/server/#doors-and-containers) group of the index # GetDefaultSpawn > The server's spawn point from server.toml. The server's spawn point from server.toml. ## Syntax ```lua GetDefaultSpawn() ``` ## Returns `number, number, number, number` - the `[spawn]` section's point as `x, y, z, yaw` ## Example ```lua local spawnX, spawnY, spawnZ, spawnYaw = GetDefaultSpawn() local lobby = CreateCircleZone(spawnX, spawnY, 12) ``` ## See also [SetSpawnInfo](/lua/server/functions/setspawninfo/) · [GetLevel](/lua/server/functions/getlevel/) · the [Players](/lua/server/#players) group of the index # GetDogMode > A dog's mode. A dog's mode. ## Syntax ```lua GetDogMode(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the dog's entity id | ## Returns `number` - the mode (`DOG_FOLLOW` for a dog nobody told otherwise); `false` when the id is not a dog ## Example ```lua if GetDogMode(dog) == DOG_STAY then SendClientMessage(pid, COLOUR_WHITE, "your dog is waiting for you") end ``` ## See also [SetDogMode](/lua/server/functions/setdogmode/) · the [Dogs](/lua/server/#dogs) group of the index # GetDoors > Every door anyone touched. Every door anyone touched. A door nobody used is at the level's default and not listed; the [level lists](/reference/levels/) have every door's key. ## Syntax ```lua GetDoors() ``` ## Returns `table` - a list of door keys ## Example ```lua for _, key in ipairs(GetDoors()) do local open, locked = GetDoorState(key) if open then SetDoorState(key, false, false) end -- curfew: every door shut end ``` ## See also [GetDoorState](/lua/server/functions/getdoorstate/) · [SetDoorState](/lua/server/functions/setdoorstate/) · the [Doors and containers](/lua/server/#doors-and-containers) group of the index # GetDoorState > A door's state of record. A door's state of record. ## Syntax ```lua GetDoorState(key) ``` | Parameter | Type | | |---|---|---| | `key` | string | the door's level name | ## Returns `boolean, boolean` - two booleans `open, locked`; `nil` when nobody ever touched the door (the level's default) ## Example ```lua local open, locked = GetDoorState(GATE) if open == nil then Log("the gate is as the level left it") end ``` ## See also [SetDoorState](/lua/server/functions/setdoorstate/) · [GetDoors](/lua/server/functions/getdoors/) · [OnPlayerUseDoor](/lua/server/callbacks/onplayerusedoor/) · the [Doors and containers](/lua/server/#doors-and-containers) group of the index # GetEntities > Every entity in the world, or every entity of one kind. Every entity in the world, or every entity of one kind. ## Syntax ```lua GetEntities([kind]) ``` | Parameter | Type | | |---|---|---| | `kind` | number | `ENTITY_HORSE`, `ENTITY_ITEM`, `ENTITY_NPC`, `ENTITY_PROP` or `ENTITY_DOG`; without it, every kind *(optional)* | ## Returns `table` - a list of entity ids ## Example ```lua -- horses nobody controls for ten minutes are removed for _, id in ipairs(GetEntities(ENTITY_HORSE)) do if GetEntityController(id) == nil and GetEntityIdleTime(id) > 600 then DestroyEntity(id) end end ``` ## See also [GetEntityKind](/lua/server/functions/getentitykind/) · [GetNearestEntity](/lua/server/functions/getnearestentity/) · [DestroyEntity](/lua/server/functions/destroyentity/) · the [World entities](/lua/server/#world-entities) group of the index # GetEntityController > The player whose client simulates the entity. The player whose client simulates the entity. A horse's controller is the player who rides or minds it; a dog's is its master for life; a pickup, a prop and an actor have none (the server itself moves an actor). ## Syntax ```lua GetEntityController(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | ## Returns `number` - a pid; `nil` when nobody controls it ## Example ```lua if GetEntityController(horse) == nil then Log("horse", horse, "stands alone") end ``` ## See also [SetEntityController](/lua/server/functions/setentitycontroller/) · [GetEntityRider](/lua/server/functions/getentityrider/) · the [World entities](/lua/server/#world-entities) group of the index # GetEntityData > A value stored on an entity with SetEntityData. A value stored on an entity with SetEntityData. ## Syntax ```lua GetEntityData(id, key) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | | `key` | string | the key | ## Returns `any` - the value; `nil` when unset or no such entity ## Example ```lua function OnPlayerPickup(pid, id) local owner = GetEntityData(id, "owner") return owner == nil or owner == pid end ``` ## See also [SetEntityData](/lua/server/functions/setentitydata/) · the [Storage and persistence](/lua/server/#storage-and-persistence) group of the index # GetEntityIdleTime > Seconds since the entity's pose was last reported. Seconds since the entity's pose was last reported. A controlled horse reports its pose all the time, so its idle time stays near zero; a loose one counts up from the moment it was left. Since the creation for anything that never reported. ## Syntax ```lua GetEntityIdleTime(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | ## Returns `number` - seconds ## Example ```lua if GetEntityIdleTime(horse) > 600 then DestroyEntity(horse) end ``` ## See also [GetEntityController](/lua/server/functions/getentitycontroller/) · [GetEntities](/lua/server/functions/getentities/) · the [World entities](/lua/server/#world-entities) group of the index # GetEntityKind > What an entity is. What an entity is. ## Syntax ```lua GetEntityKind(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | ## Returns `number` - `ENTITY_HORSE`, `ENTITY_ITEM`, `ENTITY_NPC`, `ENTITY_PROP` or `ENTITY_DOG`; `nil` when there is no such entity ## Example ```lua if GetEntityKind(id) == ENTITY_HORSE then MountPlayer(pid, id) end ``` ## See also [GetEntities](/lua/server/functions/getentities/) · [GetEntityTemplate](/lua/server/functions/getentitytemplate/) · the [World entities](/lua/server/#world-entities) group of the index # GetEntityName > An NPC actor's label; empty for everything else. An NPC actor's label; empty for everything else. ## Syntax ```lua GetEntityName(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | ## Returns `string` - the name over the actor's head; `""` for other kinds or no such entity ## Example ```lua function OnActorDeath(id, attacker) SendClientMessageToAll(COLOUR_SERVER, GetEntityName(id) .. " is dead") end ``` ## See also [CreateActor](/lua/server/functions/createactor/) · the [World entities](/lua/server/#world-entities) group of the index # GetEntityPos > An entity's position and heading. An entity's position and heading. ## Syntax ```lua GetEntityPos(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | ## Returns `number, number, number, number` - `x, y, z, yaw` in metres and degrees; `nil` when there is no such entity ## Example ```lua local x, y, z, yaw = GetEntityPos(horse) if x then SetPlayerPos(pid, x + 1.5, y, z, yaw) end ``` ## See also [SetEntityPos](/lua/server/functions/setentitypos/) · [GetPlayerPos](/lua/server/functions/getplayerpos/) · the [World entities](/lua/server/#world-entities) group of the index # GetEntityRider > The player in the saddle of a horse. The player in the saddle of a horse. ## Syntax ```lua GetEntityRider(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | ## Returns `number` - a pid; `nil` when nobody rides it (or it is not a horse) ## Example ```lua local rider = GetEntityRider(horse) if rider then SendClientMessage(rider, COLOUR_SERVER, "Nice horse.") end ``` ## See also [GetPlayerMount](/lua/server/functions/getplayermount/) · [MountPlayer](/lua/server/functions/mountplayer/) · [GetEntityController](/lua/server/functions/getentitycontroller/) · the [World entities](/lua/server/#world-entities) group of the index # GetEntityScale > A prop's scale. A prop's scale. ## Syntax ```lua GetEntityScale(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | ## Returns `number` - the uniform scale; `1` for anything but a prop ## Example ```lua Log("scale", GetEntityScale(prop)) ``` ## See also [CreateProp](/lua/server/functions/createprop/) · [IsEntityRigid](/lua/server/functions/isentityrigid/) · the [Props](/lua/server/#props) group of the index # GetEntityState > A key of an entity's bag. A key of an entity's bag. ## Syntax ```lua GetEntityState(id, key) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | | `key` | string | the key | ## Returns `string | nil` ## Example ```lua local owner = GetEntityState(horse, "owner") ``` ## See also [SetEntityState](/lua/server/functions/setentitystate/) · [GetEntityStates](/lua/server/functions/getentitystates/) · the [State bags](/lua/server/#state-bags) group of the index # GetEntityStates > An entity's whole bag. An entity's whole bag. ## Syntax ```lua GetEntityStates(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | ## Returns `table` - `{key = value, ...}` ## Example ```lua for k, v in pairs(GetEntityStates(id)) do Log(id, k, "=", v) end ``` ## See also [GetEntityState](/lua/server/functions/getentitystate/) · the [State bags](/lua/server/#state-bags) group of the index # GetEntityTemplate > What an entity is made of - the item class, the soul, the mesh path. What an entity is made of - the item class, the soul, the mesh path. A pickup: its item class GUID ([`GetItemName`](/lua/server/functions/getitemname/) names it). A horse or a dog: the soul GUID ([`GetSoulInfo`](/lua/server/functions/getsoulinfo/)). A prop: the mesh path. An actor: its soul GUID. ## Syntax ```lua GetEntityTemplate(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | ## Returns `string`; `""` when there is no such entity ## Example ```lua function OnPlayerDrop(pid, id) Log(GetPlayerName(pid), "dropped", GetItemName(GetEntityTemplate(id))) end ``` ## See also [GetEntityKind](/lua/server/functions/getentitykind/) · [GetItemName](/lua/server/functions/getitemname/) · [GetSoulInfo](/lua/server/functions/getsoulinfo/) · [GetMeshPath](/lua/server/functions/getmeshpath/) · the [World entities](/lua/server/#world-entities) group of the index # GetEntityVirtualWorld > The virtual world the entity is replicated in. The virtual world the entity is replicated in. ## Syntax ```lua GetEntityVirtualWorld(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | ## Returns `number` - the world, `0` = the shared one; `nil` when there is no such entity ## Example ```lua if GetEntityVirtualWorld(id) ~= GetPlayerVirtualWorld(pid) then return end -- not where the player is ``` ## See also [SetEntityVirtualWorld](/lua/server/functions/setentityvirtualworld/) · [GetPlayerVirtualWorld](/lua/server/functions/getplayervirtualworld/) · the [World entities](/lua/server/#world-entities) group of the index # GetGlobalState > A key of the world's bag. A key of the world's bag. ## Syntax ```lua GetGlobalState(key) ``` | Parameter | Type | | |---|---|---| | `key` | string | the key | ## Returns `string | nil` ## Example ```lua local round = tonumber(GetGlobalState("round")) or 0 ``` ## See also [SetGlobalState](/lua/server/functions/setglobalstate/) · [GetGlobalStates](/lua/server/functions/getglobalstates/) · the [State bags](/lua/server/#state-bags) group of the index # GetGlobalStates > The whole world bag. The whole world bag. ## Syntax ```lua GetGlobalStates() ``` ## Returns `table` - `{key = value, ...}` ## Example ```lua for k, v in pairs(GetGlobalStates()) do Log(k, "=", v) end ``` ## See also [GetGlobalState](/lua/server/functions/getglobalstate/) · the [State bags](/lua/server/#state-bags) group of the index # GetGroundZ > The surface under a point. The surface under a point. The height of the first surface under the point - a ray from half a metre over it, 100 m down: the paving, a bridge, a roof, an upper storey, wherever the level's geometry is. Where the geometry has nothing (open terrain), `nil`: ask `GetTerrainHeight` then. Where a spawn, a prop or a teleport should land. ## Syntax ```lua GetGroundZ(x, y, z) ``` | Parameter | Type | | |---|---|---| | `x` | number | metres | | `y` | number | metres | | `z` | number | metres, the height to look down from | ## Returns the height in metres, or `nil` when nothing is under the point (or without the geometry) ## Example ```lua local floor = GetGroundZ(x, y, z) or GetTerrainHeight(x, y) or z SetPlayerPos(pid, x, y, floor) ``` ## See also [GetTerrainHeight](/lua/server/functions/getterrainheight/) · [GetNavmeshHeight](/lua/server/functions/getnavmeshheight/) · [RayCast](/lua/server/functions/raycast/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # GetHorseSoul > The soul GUID a horse key stands for - the Horse archetype only. The soul GUID a horse key stands for - the Horse archetype only. ## Syntax ```lua GetHorseSoul(key) ``` | Parameter | Type | | |---|---|---| | `key` | string \| number | a soul's name (`Horse2`, `Pebbles`), id or GUID | ## Returns `string` - the soul GUID; `nil` when the key is not a horse soul ## Example ```lua local soul = GetHorseSoul(args) if not soul then SendClientMessage(pid, COLOUR_RED, "no such breed; try /horses ") return true end CreateHorse(x, y, z, yaw, pid, nil, soul) ``` ## See also [GetSoulInfo](/lua/server/functions/getsoulinfo/) · [FindSouls](/lua/server/functions/findsouls/) · [CreateHorse](/lua/server/functions/createhorse/) · the [Catalogues](/lua/server/#catalogues) group of the index # GetHudText > A HUD text's current text. A HUD text's current text. ## Syntax ```lua GetHudText(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the element | ## Returns `string`; `""` when there is no such element ## Example ```lua Log("the clock reads", GetHudText(clock)) ``` ## See also [SetHudText](/lua/server/functions/sethudtext/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # GetHudTexts > Every HUD text the mode has made. Every HUD text the mode has made. ## Syntax ```lua GetHudTexts() ``` ## Returns `table` - a list of element ids ## Example ```lua for _, id in ipairs(GetHudTexts()) do DestroyHudText(id) end ``` ## See also [CreateHudText](/lua/server/functions/createhudtext/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # GetItemClass > The class GUID an item key stands for. The class GUID an item key stands for. `key` is an item's id, the game's name (`shortswordBroad`, case-insensitive), its English name (`Duelling longsword`; when several classes share one, the plainest answers) or a GUID (passed through). `nil` when the catalogue knows no such item. ## Syntax ```lua GetItemClass(key) ``` | Parameter | Type | | |---|---|---| | `key` | string \| number | an item's id, name, English name or GUID | ## Returns `string` - the class GUID; `nil` when unknown ## Example ```lua local class = GetItemClass("Duelling longsword") if class then SetContainerItems(chest, {{class = class, amount = 1}}) end ``` ## See also [GetItemName](/lua/server/functions/getitemname/) · [GetItemInfo](/lua/server/functions/getiteminfo/) · [FindItems](/lua/server/functions/finditems/) · [GivePlayerItem](/lua/server/functions/giveplayeritem/) · the [Catalogues](/lua/server/#catalogues) group of the index # GetItemInfo > The catalogue's entry for an item key. The catalogue's entry for an item key. ## Syntax ```lua GetItemInfo(key) ``` | Parameter | Type | | |---|---|---| | `key` | string \| number | an item's id, name, English name or GUID | ## Returns `table` - `{id=, name=, class=, category=, display=, weight=, price=}`: the id, the game's name, the class GUID, the category (`MeleeWeapon`, `Armor`, `Food` ...), the English name (`""` when the export had none), the weight and the price; `nil` when unknown ## Example ```lua local info = GetItemInfo(stack.class) if info and info.category == "MeleeWeapon" then SendClientMessage(pid, COLOUR_SERVER, "a " .. (info.display ~= "" and info.display or info.name)) end ``` ## See also [GetItemClass](/lua/server/functions/getitemclass/) · [FindItems](/lua/server/functions/finditems/) · the [Catalogues](/lua/server/#catalogues) group of the index # GetItemName > The game's name of an item key. The game's name of an item key. Turns a class GUID - what the client reports, what the callbacks carry - into the name the catalogue lists. ## Syntax ```lua GetItemName(key) ``` | Parameter | Type | | |---|---|---| | `key` | string \| number | an item's id, name, English name or GUID | ## Returns `string` - the name (`shortswordBroad`); `""` when unknown ## Example ```lua function OnPlayerDrop(pid, id) Log(GetPlayerName(pid), "dropped", GetItemName(GetEntityTemplate(id))) end ``` ## See also [GetItemClass](/lua/server/functions/getitemclass/) · [GetItemInfo](/lua/server/functions/getiteminfo/) · the [Catalogues](/lua/server/#catalogues) group of the index # GetLevel > The name of the level the server runs. The name of the level the server runs. `[server] level` in `server.toml`: `klaster`, `trosecko` or `kutnohorsko` ([Levels](/reference/levels/)). Every client boots the same level; the launcher asks the server which. ## Syntax ```lua GetLevel() ``` ## Returns `string` - the level name ## Example ```lua if GetLevel() == "klaster" then AddSpawnPoint(1280, 1088, -1, 0) end ``` ## See also [GetLevelName](/lua/server/functions/getlevelname/) · [GetDefaultSpawn](/lua/server/functions/getdefaultspawn/) · the [Server and timers](/lua/server/#server-and-timers) group of the index # GetLevelName > The level as a player reads it. The level as a player reads it. The game's own name of the level [`GetLevel`](/lua/server/functions/getlevel/) names: `Trosky` for `trosecko`, `Kuttenberg` for `kutnohorsko`, `Sedletz Monastery` for `klaster`. For what a player sees - a welcome line, a HUD text; keep [`GetLevel`](/lua/server/functions/getlevel/) for comparisons and file names. ## Syntax ```lua GetLevelName() ``` ## Returns `string` - the name ## Example ```lua function OnPlayerConnect(pid) SendClientMessage(pid, COLOUR_SERVER, "Welcome to " .. GetLevelName() .. ", " .. GetPlayerName(pid)) end ``` ## See also [GetLevel](/lua/server/functions/getlevel/) · the [Server and timers](/lua/server/#server-and-timers) group of the index # GetMaxPlayers > How many players the server holds ([server] max_players). How many players the server holds (`[server] max_players`). Player ids run from `0` to `GetMaxPlayers() - 1`. ## Syntax ```lua GetMaxPlayers() ``` ## Returns `number` - the slot count ## Example ```lua for pid = 0, GetMaxPlayers() - 1 do if IsPlayerConnected(pid) then SendClientMessage(pid, COLOUR_SERVER, "Round over") end end ``` ## See also [GetPlayers](/lua/server/functions/getplayers/) · [GetPlayerCount](/lua/server/functions/getplayercount/) · the [Server and timers](/lua/server/#server-and-timers) group of the index # GetMeshPath > The path a mesh key stands for. The path a mesh key stands for. ## Syntax ```lua GetMeshPath(key) ``` | Parameter | Type | | |---|---|---| | `key` | string \| number | the mesh's id, file name or path | ## Returns `string` - the path (`objects/manmade/.../barrel_a.cgf`); `nil` when the key resolves to nothing or to several files ## Example ```lua local path = GetMeshPath("barrel_a") ``` ## See also [FindMeshes](/lua/server/functions/findmeshes/) · [CreateProp](/lua/server/functions/createprop/) · the [Props](/lua/server/#props) group of the index # GetNavmeshHeight > The navigation mesh's floor at a point. The navigation mesh's floor at a point. The height of the walkable surface under (or near) the point - a floor, a bridge, a stair - where [`GetTerrainHeight`](/lua/server/functions/getterrainheight/) only knows the terrain. `nil` more than 2 m from the mesh sideways or 4 m up or down, or without a navmesh. ## Syntax ```lua GetNavmeshHeight(x, y, z) ``` | Parameter | Type | | |---|---|---| | `x` | number | metres | | `y` | number | metres | | `z` | number | a height near the floor asked for (the floor above or below within 4 m) | ## Returns `number` - metres; `nil` off the mesh ## Example ```lua local floor = GetNavmeshHeight(x, y, z) or GetTerrainHeight(x, y) or z CreateActor("guard_a", x, y, floor, 0, "Guard") ``` ## See also [GetTerrainHeight](/lua/server/functions/getterrainheight/) · [NearestNavmeshPoint](/lua/server/functions/nearestnavmeshpoint/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # GetNearestEntity > The entity nearest to a player, of a kind, within a radius. The entity nearest to a player, of a kind, within a radius. Horizontal distance, in the player's own virtual world only. ## Syntax ```lua GetNearestEntity(pid, kind [, radius]) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `kind` | number \| nil | an entity kind; `nil` = any | | `radius` | number | metres; without it, any distance *(optional)* | ## Returns `number, number` - the entity `id` and its `distance` in metres; `nil` when none ## Example ```lua -- /mount: the nearest horse within ten metres local horse = GetNearestEntity(pid, ENTITY_HORSE, 10) if horse then MountPlayer(pid, horse) else SendClientMessage(pid, COLOUR_RED, "No horse near you.") end ``` ## See also [GetEntities](/lua/server/functions/getentities/) · [GetEntityPos](/lua/server/functions/getentitypos/) · the [World entities](/lua/server/#world-entities) group of the index # GetParties > Every party on the server. Every party on the server. ## Syntax ```lua GetParties() ``` ## Returns `table` of party ids ## Example ```lua for _, party in ipairs(GetParties()) do Log(GetPartyName(party) .. ": " .. GetPartySize(party)) end ``` ## See also [GetPartyMembers](/lua/server/functions/getpartymembers/) · the [Parties](/lua/server/#parties) group of the index # GetPartyData > A value of the mode's private storage on a party. A value of the mode's private storage on a party. ## Syntax ```lua GetPartyData(party, key) ``` | Parameter | Type | | |---|---|---| | `party` | number | the party | | `key` | string | the key | ## Returns the value, or `nil` ## Example ```lua local round = GetPartyData(party, "round") or 1 ``` ## See also [SetPartyData](/lua/server/functions/setpartydata/) · the [Parties](/lua/server/#parties) group of the index # GetPartyLeader > The party's leader. The party's leader. ## Syntax ```lua GetPartyLeader(party) ``` | Parameter | Type | | |---|---|---| | `party` | number | the party | ## Returns `number` - the leader's pid; `nil` for an unknown party ## Example ```lua if GetPartyLeader(party) ~= pid then SendClientMessage(pid, COLOUR_RED, "You lead no party.") return true end ``` ## See also [SetPartyLeader](/lua/server/functions/setpartyleader/) · [GetPlayerParty](/lua/server/functions/getplayerparty/) · the [Parties](/lua/server/#parties) group of the index # GetPartyMemberLabel > The member's label. The member's label. ## Syntax ```lua GetPartyMemberLabel(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the member | ## Returns `string` - `""` when none ## Example ```lua local role = GetPartyMemberLabel(pid) ``` ## See also [SetPartyMemberLabel](/lua/server/functions/setpartymemberlabel/) · the [Parties](/lua/server/#parties) group of the index # GetPartyMembers > The members, in join order. The members, in join order. ## Syntax ```lua GetPartyMembers(party) ``` | Parameter | Type | | |---|---|---| | `party` | number | the party | ## Returns `table` of pids in join order; `{}` for an unknown party ## Example ```lua for _, member in ipairs(GetPartyMembers(party)) do GameText(member, "Round " .. round, 2000) end ``` ## See also [GetPartySize](/lua/server/functions/getpartysize/) · [IsPartyFull](/lua/server/functions/ispartyfull/) · [GetPlayerParty](/lua/server/functions/getplayerparty/) · the [Parties](/lua/server/#parties) group of the index # GetPartyName > The party's title. The party's title. ## Syntax ```lua GetPartyName(party) ``` | Parameter | Type | | |---|---|---| | `party` | number | the party | ## Returns `string` - `""` when none or unknown ## Example ```lua local title = GetPartyName(party) ``` ## See also [SetPartyName](/lua/server/functions/setpartyname/) · the [Parties](/lua/server/#parties) group of the index # GetPartySize > How many members the party has. How many members the party has. ## Syntax ```lua GetPartySize(party) ``` | Parameter | Type | | |---|---|---| | `party` | number | the party | ## Returns `number` - 0 for an unknown party ## Example ```lua SendClientMessage(pid, COLOUR_SERVER, GetPartySize(party) .. " in the party") ``` ## See also [GetPartyMembers](/lua/server/functions/getpartymembers/) · [IsPartyFull](/lua/server/functions/ispartyfull/) · the [Parties](/lua/server/#parties) group of the index # GetPlayerAlcohol > The player's blood-alcohol level, 0 to 1. The player's blood-alcohol level, 0 to 1. Each drink adds its alcohol content × `[combat] alcohol_per_content`; time takes `[combat] alcohol_decay` off per second. Drunk from `[combat] drunk_threshold` up, sober again from half of it down ([`OnPlayerDrunk`](/lua/server/callbacks/onplayerdrunk/)). ## Syntax ```lua GetPlayerAlcohol(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number` - `0` .. `1` ## Example ```lua if GetPlayerAlcohol(pid) > 0.2 then SendClientMessage(pid, COLOUR_SERVER, "Steady on.") end ``` ## See also [IsPlayerDrunk](/lua/server/functions/isplayerdrunk/) · [SetPlayerAlcohol](/lua/server/functions/setplayeralcohol/) · [OnPlayerDrunk](/lua/server/callbacks/onplayerdrunk/) · the [Buffs and the drink](/lua/server/#buffs-and-the-drink) group of the index # GetPlayerAuditViolations > How many audit violations were acted on for the player this session. How many audit violations were acted on for the player this session. ## Syntax ```lua GetPlayerAuditViolations(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number` ## Example ```lua if GetPlayerAuditViolations(pid) >= 3 then Ban(pid, "repeated inventory violations") end ``` ## See also [OnPlayerAuditViolation](/lua/server/callbacks/onplayerauditviolation/) · the [Accounts, admins, bans and the audit](/lua/server/#accounts-admins-bans-and-the-audit) group of the index # GetPlayerBleeding > How fast the player is bleeding, in health per second. How fast the player is bleeding, in health per second. A stab or a slash opens a bleed for `[combat] bleed_seconds`; `0` means not bleeding. A bleed-out is a death by the last attacker. A bandage stops it, so do [`HealPlayer`](/lua/server/functions/healplayer/) and the respawn. ## Syntax ```lua GetPlayerBleeding(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number` - health lost per second; `0` = not bleeding ## Example ```lua if GetPlayerBleeding(pid) > 0.5 then GameText(pid, "You are bleeding heavily", 2000, GAMETEXT_LOWER) end ``` ## See also [IsPlayerBleeding](/lua/server/functions/isplayerbleeding/) · [HealPlayer](/lua/server/functions/healplayer/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # GetPlayerBuffs > The buffs the server gave the player, as GUIDs. The buffs the server gave the player, as GUIDs. ## Syntax ```lua GetPlayerBuffs(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `table` - a list of buff GUIDs; `{}` when none ## Example ```lua for _, guid in ipairs(GetPlayerBuffs(pid)) do local info = GetBuffInfo(guid) Log(GetPlayerName(pid), "has", info and info.name or guid) end ``` ## See also [GivePlayerBuff](/lua/server/functions/giveplayerbuff/) · [GetBuffInfo](/lua/server/functions/getbuffinfo/) · [ClearPlayerBuffs](/lua/server/functions/clearplayerbuffs/) · the [Buffs and the drink](/lua/server/#buffs-and-the-drink) group of the index # GetPlayerColor > The same function as GetPlayerColour. `GetPlayerColor` is another name for [GetPlayerColour](/lua/server/functions/getplayercolour/); the two are the same function. # GetPlayerColour > The player's colour as set. The player's colour as set. ## Syntax ```lua GetPlayerColour(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number` - `0xRRGGBBAA`; `0` = the default ## Example ```lua local c = GetPlayerColour(pid) ``` ## See also [SetPlayerColour](/lua/server/functions/setplayercolour/) · the [Players](/lua/server/#players) group of the index # GetPlayerCount > How many players are connected. How many players are connected. ## Syntax ```lua GetPlayerCount() ``` ## Returns `number` ## Example ```lua Log(GetPlayerCount() .. " player(s) online") ``` ## See also [GetPlayers](/lua/server/functions/getplayers/) · the [Players](/lua/server/#players) group of the index # GetPlayerData > A value stored on the player with SetPlayerData. A value stored on the player with SetPlayerData. ## Syntax ```lua GetPlayerData(pid, key) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `key` | string | the key | ## Returns `any` - the value; `nil` when unset or not connected ## Example ```lua local team = GetPlayerData(pid, "team") or "red" ``` ## See also [SetPlayerData](/lua/server/functions/setplayerdata/) · the [Storage and persistence](/lua/server/#storage-and-persistence) group of the index # GetPlayerDog > The player's dog. The player's dog. ## Syntax ```lua GetPlayerDog(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number` - the dog's entity id; `nil` when they have none ## Example ```lua -- /dog away local dog = GetPlayerDog(pid) if dog then DestroyEntity(dog) end ``` ## See also [CreateDog](/lua/server/functions/createdog/) · [SetDogMode](/lua/server/functions/setdogmode/) · the [Dogs](/lua/server/#dogs) group of the index # GetPlayerEquipment > What the player's client reports as equipped - clothing, armour, the weapons in the slots. What the player's client reports as equipped - clothing, armour, the weapons in the slots. Class GUIDs, as the client last reported them. The damage model reads the armour from here; [`GetPlayerWeapon`](/lua/server/functions/getplayerweapon/) names the weapon it charges the hits to. ## Syntax ```lua GetPlayerEquipment(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `table` - a list of item class GUIDs; `{}` before the first report ## Example ```lua for _, class in ipairs(GetPlayerEquipment(pid)) do local info = GetItemInfo(class) if info and info.category == "Helmet" then hasHelmet = true end end ``` ## See also [GetPlayerInventory](/lua/server/functions/getplayerinventory/) · [GetPlayerWeapon](/lua/server/functions/getplayerweapon/) · [GetItemInfo](/lua/server/functions/getiteminfo/) · the [Items and inventory](/lua/server/#items-and-inventory) group of the index # GetPlayerHealth > The player's health. The player's health. ## Syntax ```lua GetPlayerHealth(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number` - `0` .. `GetPlayerMaxHealth`; `-1` when not connected ## Example ```lua if GetPlayerHealth(pid) < 25 then SendClientMessage(pid, COLOUR_RED, "You are badly hurt.") end ``` ## See also [GetPlayerMaxHealth](/lua/server/functions/getplayermaxhealth/) · [SetPlayerHealth](/lua/server/functions/setplayerhealth/) · [IsPlayerDead](/lua/server/functions/isplayerdead/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # GetPlayerHorse > The horse the player rides, or else the newest one they control. The horse the player rides, or else the newest one they control. ## Syntax ```lua GetPlayerHorse(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number` - a horse's entity id; `nil` when they have none ## Example ```lua -- /horse home: the player's horse comes to them local horse = GetPlayerHorse(pid) if horse then local x, y, z = GetPlayerPos(pid) SetEntityPos(horse, x + 2, y, z) end ``` ## See also [GetPlayerMount](/lua/server/functions/getplayermount/) · [GetEntityController](/lua/server/functions/getentitycontroller/) · [CreateHorse](/lua/server/functions/createhorse/) · the [Horses](/lua/server/#horses) group of the index # GetPlayerId > The player a command names - a pid, a name or a fragment of one - or nil. The player a command names - a pid, a name or a fragment of one - or `nil`. The reverse of [`GetPlayerName`](/lua/server/functions/getplayername/), for commands that take a player: `"2"` or `2` is the pid 2 (returned when that player is connected); a name is matched case-insensitively - the exact name wins, else a fragment (`"hen"` for Henry) when exactly one connected name contains it. `nil` when nobody matches or two do, so a command can answer "no player called ..." and never guess between two. [`sscanf`](/lua/server/functions/sscanf/)'s `u` letter is this function. ## Syntax ```lua GetPlayerId(name) ``` | Parameter | Type | | |---|---|---| | `name` | string \| number | a pid, a name, or a fragment of a name | ## Returns `number | nil` - the pid ## Example ```lua elseif cmd == "goto" then local target = GetPlayerId(args) if not target then SendClientMessage(pid, COLOUR_RED, "no player called " .. args) else local x, y, z = GetPlayerPos(target) SetPlayerPos(pid, x + 1, y, z) end return true ``` ## See also [GetPlayerName](/lua/server/functions/getplayername/) · [sscanf](/lua/server/functions/sscanf/) · [GetPlayers](/lua/server/functions/getplayers/) · [IsPlayerConnected](/lua/server/functions/isplayerconnected/) · the [Players](/lua/server/#players) group of the index # GetPlayerInjuries > The player's injured body parts. The player's injured body parts. A list of body parts, `BODY_PART_HEAD` .. `BODY_PART_LEG_RIGHT` (`1` .. `6`); `{}` when whole. An injured arm makes the swings weaker and costlier, an injured head or torso halves the stamina regeneration. A hit of at least `[combat] injury_threshold` injures the part it struck; [`OnPlayerInjury`](/lua/server/callbacks/onplayerinjury/) says so. ## Syntax ```lua GetPlayerInjuries(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `table` - a list of body part ids ## Example ```lua local names = {} for _, part in ipairs(GetPlayerInjuries(pid)) do names[#names + 1] = GetBodyPartName(part) end if #names > 0 then SendClientMessage(pid, COLOUR_RED, "injured: " .. table.concat(names, ", ")) end ``` ## See also [IsPlayerInjured](/lua/server/functions/isplayerinjured/) · [GetBodyPartName](/lua/server/functions/getbodypartname/) · [OnPlayerInjury](/lua/server/callbacks/onplayerinjury/) · [HealPlayer](/lua/server/functions/healplayer/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # GetPlayerInventory > The player's whole inventory as their client last reported it. The player's whole inventory as their client last reported it. One entry per stack: the class GUID, how many, the item's condition in percent. Reported 1.5 s after a spawn, then every 10 s or within a second of a change; `{}` before the first report. Money is not reported. ## Syntax ```lua GetPlayerInventory(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `table` - a list of `{class=, amount=, health=}` ## Example ```lua local arrows = 0 for _, stack in ipairs(GetPlayerInventory(pid)) do local info = GetItemInfo(stack.class) if info and info.category == "Ammo" then arrows = arrows + stack.amount end end ``` ## See also [GetPlayerEquipment](/lua/server/functions/getplayerequipment/) · [GivePlayerItem](/lua/server/functions/giveplayeritem/) · [GetItemInfo](/lua/server/functions/getiteminfo/) · the [Items and inventory](/lua/server/#items-and-inventory) group of the index # GetPlayerIP > The player's address. The player's address. ## Syntax ```lua GetPlayerIP(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `string` - `"a.b.c.d"`; `""` when not connected ## Example ```lua Log(GetPlayerName(pid) .. " joined from " .. GetPlayerIP(pid)) ``` ## See also [BanAddress](/lua/server/functions/banaddress/) · [GetPlayerPing](/lua/server/functions/getplayerping/) · the [Players](/lua/server/#players) group of the index # GetPlayerMaxHealth > The player's maximum health (100). The player's maximum health (100). ## Syntax ```lua GetPlayerMaxHealth(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number`; `-1` when not connected ## Example ```lua local fraction = GetPlayerHealth(pid) / GetPlayerMaxHealth(pid) ``` ## See also [GetPlayerHealth](/lua/server/functions/getplayerhealth/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # GetPlayerMaxStamina > The player's maximum stamina ([combat] max_stamina). The player's maximum stamina (`[combat] max_stamina`). ## Syntax ```lua GetPlayerMaxStamina(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number`; `-1` when not connected ## Example ```lua SetPlayerStamina(pid, GetPlayerMaxStamina(pid)) ``` ## See also [GetPlayerStamina](/lua/server/functions/getplayerstamina/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # GetPlayerMount > The horse the player rides right now. The horse the player rides right now. ## Syntax ```lua GetPlayerMount(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number` - the horse's entity id; `nil` on foot ## Example ```lua if GetPlayerMount(pid) then SendClientMessage(pid, COLOUR_RED, "Not from the saddle.") return true end ``` ## See also [GetPlayerHorse](/lua/server/functions/getplayerhorse/) · [MountPlayer](/lua/server/functions/mountplayer/) · [GetEntityRider](/lua/server/functions/getentityrider/) · the [Horses](/lua/server/#horses) group of the index # GetPlayerName > The player's name, as they joined. The player's name, as they joined. Names are unique on a server and compared case-insensitively; a registered name ([`IsPlayerRegistered`](/lua/server/functions/isplayerregistered/)) belongs to whoever logs in with its password. `nil` when no player has the pid. ## Syntax ```lua GetPlayerName(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `string | nil` ## Example ```lua SendClientMessageToAll(COLOUR_SERVER, GetPlayerName(pid) .. " has arrived") -- the other way round, a name (or a fragment of one) to a pid: GetPlayerId ``` ## See also [GetPlayerId](/lua/server/functions/getplayerid/) · [GetPlayers](/lua/server/functions/getplayers/) · [IsPlayerConnected](/lua/server/functions/isplayerconnected/) · [SetPlayerNameplate](/lua/server/functions/setplayernameplate/) · the [Players](/lua/server/#players) group of the index # GetPlayerNameplate > The label as the mode set it. The label as the mode set it. ## Syntax ```lua GetPlayerNameplate(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `string` - the text; `""` when it is the name ## Example ```lua if GetPlayerNameplate(pid) == "" then SetPlayerNameplate(pid, "Rookie " .. GetPlayerName(pid)) end ``` ## See also [SetPlayerNameplate](/lua/server/functions/setplayernameplate/) · the [Players](/lua/server/#players) group of the index # GetPlayerOpponents > Everyone the player is fighting right now. Everyone the player is fighting right now. ## Syntax ```lua GetPlayerOpponents(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `table` - a list of pids, `{}` at peace ## Example ```lua for _, other in ipairs(GetPlayerOpponents(pid)) do EndFight(pid, other) end -- what /peace does ``` ## See also [AreFighting](/lua/server/functions/arefighting/) · [EndFight](/lua/server/functions/endfight/) · the [Combat](/lua/server/#combat) group of the index # GetPlayerParty > The party the player is in. The party the player is in. ## Syntax ```lua GetPlayerParty(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number` - the party's id; `nil` in none ## Example ```lua local party = GetPlayerParty(pid) if not party then SendClientMessage(pid, COLOUR_RED, "You are in no party.") return true end ``` ## See also [GetPartyMembers](/lua/server/functions/getpartymembers/) · [GetPartyLeader](/lua/server/functions/getpartyleader/) · the [Parties](/lua/server/#parties) group of the index # GetPlayerPartyInvite > The player's pending invitation. The player's pending invitation. ## Syntax ```lua GetPlayerPartyInvite(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `from, seconds` - the inviter and the seconds left; `nil` without a pending invitation ## Example ```lua local from, seconds = GetPlayerPartyInvite(pid) if from then SendClientMessage(pid, COLOUR_SERVER, GetPlayerName(from) .. "'s invitation runs out in " .. math.floor(seconds) .. " s.") end ``` ## See also [InviteToParty](/lua/server/functions/invitetoparty/) · the [Parties](/lua/server/#parties) group of the index # GetPlayerPing > The player's round trip to the server in milliseconds. The player's round trip to the server in milliseconds. ## Syntax ```lua GetPlayerPing(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number` - milliseconds; `-1` when not connected ## Example ```lua SendClientMessage(pid, COLOUR_SERVER, "your ping is " .. GetPlayerPing(pid) .. " ms") ``` ## See also [GetPlayerIP](/lua/server/functions/getplayerip/) · the [Players](/lua/server/#players) group of the index # GetPlayerPos > The player's position of record. The player's position of record. Metres in the level's world space, from the client's reports (thirty a second); a mounted player's position is the horse's. A report that would move a player faster than `[validation] max_speed` allows is refused and the client pulled back, so the record is the server's own opinion of where they are. ## Syntax ```lua GetPlayerPos(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number, number, number` - three numbers `x, y, z`; `nil` when not connected ## Example ```lua local x, y, z = GetPlayerPos(pid) if x then CreatePickup("torch_weapon", x + 1, y, z) end ``` ## See also [GetPlayerYaw](/lua/server/functions/getplayeryaw/) · [GetPlayerVelocity](/lua/server/functions/getplayervelocity/) · [SetPlayerPos](/lua/server/functions/setplayerpos/) · [GetTerrainHeight](/lua/server/functions/getterrainheight/) · the [Players](/lua/server/#players) group of the index # GetPlayers > Everyone who passed the handshake, in join order. Everyone who passed the handshake, in join order. ## Syntax ```lua GetPlayers() ``` ## Returns `table` - a list of pids, `{}` on an empty server ## Example ```lua for _, pid in ipairs(GetPlayers()) do SendClientMessage(pid, COLOUR_YELLOW, "The round starts in ten seconds.") end ``` ## See also [GetPlayerCount](/lua/server/functions/getplayercount/) · [IsPlayerInWorld](/lua/server/functions/isplayerinworld/) · [GetMaxPlayers](/lua/server/functions/getmaxplayers/) · the [Players](/lua/server/#players) group of the index # GetPlayerSkill > The level of record of a skill. The level of record of a skill. ## Syntax ```lua GetPlayerSkill(pid, skill) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `skill` | string | the skill's name | ## Returns `number` - the level the server set; `0` = never set ## Example ```lua Log(GetPlayerName(pid), "marksmanship", GetPlayerSkill(pid, "marksmanship")) ``` ## See also [SetPlayerSkill](/lua/server/functions/setplayerskill/) · [GetPlayerStat](/lua/server/functions/getplayerstat/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # GetPlayerStamina > The player's stamina - the bar they see. The player's stamina - the bar they see. Swings, hits taken, blocks, shots, sprints and jumps cost it; it regenerates after a pause ([Combat](/lua/server/combat/#stamina)). What the player sees on their stamina bar **is** this number. ## Syntax ```lua GetPlayerStamina(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number` - `0` .. `GetPlayerMaxStamina`; `-1` when not connected ## Example ```lua if GetPlayerStamina(pid) < 20 then GameText(pid, "Catch your breath", 1000, GAMETEXT_LOWER) end ``` ## See also [GetPlayerMaxStamina](/lua/server/functions/getplayermaxstamina/) · [SetPlayerStamina](/lua/server/functions/setplayerstamina/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # GetPlayerStat > The level of record of a core stat. The level of record of a core stat. ## Syntax ```lua GetPlayerStat(pid, stat) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `stat` | string | the stat's name | ## Returns `number` - the level the server set; `0` = never set (the character's own level is not read back) ## Example ```lua if GetPlayerStat(pid, "strength") < 13 then SetPlayerStat(pid, "strength", 13) end ``` ## See also [SetPlayerStat](/lua/server/functions/setplayerstat/) · [GetPlayerSkill](/lua/server/functions/getplayerskill/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # GetPlayerState > A key of a player's bag. A key of a player's bag. ## Syntax ```lua GetPlayerState(pid, key) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `key` | string | the key | ## Returns `string | nil` ## Example ```lua local team = GetPlayerState(pid, "team") ``` ## See also [SetPlayerState](/lua/server/functions/setplayerstate/) · [GetPlayerStates](/lua/server/functions/getplayerstates/) · the [State bags](/lua/server/#state-bags) group of the index # GetPlayerStates > A player's whole bag. A player's whole bag. ## Syntax ```lua GetPlayerStates(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `table` - `{key = value, ...}` ## Example ```lua for k, v in pairs(GetPlayerStates(pid)) do Log(GetPlayerName(pid), k, "=", v) end ``` ## See also [GetPlayerState](/lua/server/functions/getplayerstate/) · the [State bags](/lua/server/#state-bags) group of the index # GetPlayerTeam > The player's team. The player's team. ## Syntax ```lua GetPlayerTeam(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number` - the team; `NO_TEAM` (`-1`) when none ## Example ```lua if GetPlayerTeam(a) == GetPlayerTeam(b) then SendClientMessage(a, COLOUR_RED, "That is your teammate.") end ``` ## See also [SetPlayerTeam](/lua/server/functions/setplayerteam/) · the [Players](/lua/server/#players) group of the index # GetPlayerVelocity > The player's velocity in metres per second. The player's velocity in metres per second. ## Syntax ```lua GetPlayerVelocity(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number, number, number` - three numbers `vx, vy, vz`; `nil` when not connected ## Example ```lua local vx, vy = GetPlayerVelocity(pid) local speed = math.sqrt(vx * vx + vy * vy) -- ~1.5 walking, ~4 running, ~6.5 sprinting ``` ## See also [GetPlayerPos](/lua/server/functions/getplayerpos/) · the [Players](/lua/server/#players) group of the index # GetPlayerVirtualWorld > The virtual world the player is in. The virtual world the player is in. Players and entities are replicated to each other **within one world only**; `0` is the shared world. A registered name waiting for its `/login` sits in a world of its own. See [Getting started](/lua/server/getting-started/) and [`SetPlayerVirtualWorld`](/lua/server/functions/setplayervirtualworld/). ## Syntax ```lua GetPlayerVirtualWorld(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number` - the world; `nil` when not connected ## Example ```lua if GetPlayerVirtualWorld(pid) ~= 0 then SendClientMessage(pid, COLOUR_SERVER, "You are in a private instance.") end ``` ## See also [SetPlayerVirtualWorld](/lua/server/functions/setplayervirtualworld/) · [GetEntityVirtualWorld](/lua/server/functions/getentityvirtualworld/) · the [Players](/lua/server/#players) group of the index # GetPlayerWeapon > The weapon the damage model charges the player's hits to. The weapon the damage model charges the player's hits to. The table name of the melee weapon the player has equipped and drawn (`shortswordBroad`, `longSwordDuel` ...), as the `weapon` argument of [`OnPlayerDamage`](/lua/server/callbacks/onplayerdamage/) names it; `""` bare-handed, with the weapon sheathed, or without the tables export. [`GetItemInfo`](/lua/server/functions/getiteminfo/) turns the name into its catalogue entry. ## Syntax ```lua GetPlayerWeapon(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `string` - the weapon's name; `""` when none ## Example ```lua local weapon = GetPlayerWeapon(pid) if weapon ~= "" then local info = GetItemInfo(weapon) SendClientMessage(pid, COLOUR_SERVER, "you fight with " .. (info and info.display ~= "" and info.display or weapon)) end ``` ## See also [GetPlayerEquipment](/lua/server/functions/getplayerequipment/) · [GetItemInfo](/lua/server/functions/getiteminfo/) · [OnPlayerDamage](/lua/server/callbacks/onplayerdamage/) · the [Combat](/lua/server/#combat) group of the index # GetPlayerYaw > The direction the player faces, in degrees. The direction the player faces, in degrees. The game's convention: `0` faces +Y, `90` faces -X, `180` faces -Y, `270` faces +X - counter-clockwise seen from above. ## Syntax ```lua GetPlayerYaw(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `number` - degrees `0`..`360`; `0` when not connected ## Example ```lua -- two metres in front of the player local x, y, z = GetPlayerPos(pid) local r = math.rad(GetPlayerYaw(pid)) local fx, fy = x - math.sin(r) * 2, y + math.cos(r) * 2 ``` ## See also [GetPlayerPos](/lua/server/functions/getplayerpos/) · [SetPlayerPos](/lua/server/functions/setplayerpos/) · the [Players](/lua/server/#players) group of the index # GetPlayerZones > The zones a player is inside right now. The zones a player is inside right now. ## Syntax ```lua GetPlayerZones(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `table` - a list of zone ids ## Example ```lua for _, zone in ipairs(GetPlayerZones(pid)) do Log(GetPlayerName(pid), "is in zone", zone) end ``` ## See also [IsPlayerInZone](/lua/server/functions/isplayerinzone/) · [GetZonePlayers](/lua/server/functions/getzoneplayers/) · the [Zones](/lua/server/#zones) group of the index # GetRain > The rain override. The rain override. ## Syntax ```lua GetRain() ``` ## Returns `number` - `0` .. `1` when forced; `-1` = the level's own weather ## Example ```lua if GetRain() > 0.5 then SendClientMessage(pid, COLOUR_SERVER, "Mind the mud.") end ``` ## See also [SetRain](/lua/server/functions/setrain/) · [GetWeather](/lua/server/functions/getweather/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # GetRandomSpawnPoint > One spawn point of a tag, at random. One spawn point of a tag, at random. ## Syntax ```lua GetRandomSpawnPoint([tag]) ``` | Parameter | Type | | |---|---|---| | `tag` | string | the list (`""` without) *(optional)* | ## Returns `number, number, number, number` - a point as `x, y, z, yaw`; `nil` when the list is empty ## Example ```lua function OnPlayerRequestSpawn(pid) local x, y, z, yaw = GetRandomSpawnPoint(GetPlayerData(pid, "team") or "red") if x then SetSpawnInfo(pid, x, y, z, yaw) end return true end ``` ## See also [AddSpawnPoint](/lua/server/functions/addspawnpoint/) · [SetSpawnInfo](/lua/server/functions/setspawninfo/) · the [Players](/lua/server/#players) group of the index # GetSavedData > A value the mode saved on the player's name. A value the mode saved on the player's name. ## Syntax ```lua GetSavedData(pid, key) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `key` | string | the key | ## Returns `string | nil` ## Example ```lua local wins = tonumber(GetSavedData(pid, "wins")) or 0 ``` ## See also [SetSavedData](/lua/server/functions/setsaveddata/) · [GetSavedPlayer](/lua/server/functions/getsavedplayer/) · the [Storage and persistence](/lua/server/#storage-and-persistence) group of the index # GetSavedPlayer > What the server remembers about the player's name between visits. What the server remembers about the player's name between visits. The record the server keeps by itself: how many visits, the seconds played, and the last position - refreshed on the disconnect and every minute (`x`, `y`, `z`, `yaw` are absent until the first visit ended). `nil` when the name has no record yet. A **registered** name's record is written for its owner only: a guest who typed the name reads nothing and leaves no trace. Persistence is `[persistence] file` in `server.toml`; names are case-insensitive. ## Syntax ```lua GetSavedPlayer(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `table` - `{visits=, playTime=, x=, y=, z=, yaw=}` (the position absent on a first visit); `nil` without a record ## Example ```lua function OnPlayerRequestSpawn(pid) local saved = GetSavedPlayer(pid) if saved and saved.x then SetSpawnInfo(pid, saved.x, saved.y, saved.z, saved.yaw) end -- back where they left return true end ``` ## See also [GetSavedData](/lua/server/functions/getsaveddata/) · [SetSavedData](/lua/server/functions/setsaveddata/) · [OnPlayerConnect](/lua/server/callbacks/onplayerconnect/) · the [Storage and persistence](/lua/server/#storage-and-persistence) group of the index # GetServerData > A value of the server-wide store. A value of the server-wide store. ## Syntax ```lua GetServerData(key) ``` | Parameter | Type | | |---|---|---| | `key` | string | the key | ## Returns `string | nil` ## Example ```lua local rounds = tonumber(GetServerData("rounds_played")) or 0 ``` ## See also [SetServerData](/lua/server/functions/setserverdata/) · the [Storage and persistence](/lua/server/#storage-and-persistence) group of the index # GetServerTick > The number of the simulation tick being processed. The number of the simulation tick being processed. Counts up from the server's start, one per tick (30 a second). Handy as a cheap clock for "every n ticks" logic; for time in milliseconds use [`GetServerTime`](/lua/server/functions/getservertime/). ## Syntax ```lua GetServerTick() ``` ## Returns `number` - the tick ## Example ```lua function OnTick(dt) if GetServerTick() % 300 == 0 then Log(GetPlayerCount() .. " players online") end -- every 10 s end ``` ## See also [GetServerTime](/lua/server/functions/getservertime/) · [OnTick](/lua/server/callbacks/ontick/) · the [Server and timers](/lua/server/#server-and-timers) group of the index # GetServerTime > The server's clock in milliseconds. The server's clock in milliseconds. Milliseconds since the server started - the clock the protocol carries. It wraps after about 49 days; compare differences, not absolute values, for anything long-lived. ## Syntax ```lua GetServerTime() ``` ## Returns `number` - milliseconds ## Example ```lua local startedAt = GetServerTime() -- ... later local seconds = (GetServerTime() - startedAt) / 1000 ``` ## See also [GetServerTick](/lua/server/functions/getservertick/) · [SetTimer](/lua/server/functions/settimer/) · [FormatWorldTime](/lua/server/functions/formatworldtime/) · the [Server and timers](/lua/server/#server-and-timers) group of the index # GetSoulInfo > The soul catalogue's entry for a key, of any archetype. The soul catalogue's entry for a key, of any archetype. ## Syntax ```lua GetSoulInfo(key) ``` | Parameter | Type | | |---|---|---| | `key` | string \| number | a soul's name, id or GUID | ## Returns `table` - `{id=, name=, guid=, archetype=}`; `nil` when unknown ## Example ```lua local info = GetSoulInfo(GetEntityTemplate(horse)) Log("the horse is a", info and info.name or "?") ``` ## See also [GetHorseSoul](/lua/server/functions/gethorsesoul/) · [FindSouls](/lua/server/functions/findsouls/) · the [Catalogues](/lua/server/#catalogues) group of the index # GetSpawnPoints > The spawn points of a tag. The spawn points of a tag. ## Syntax ```lua GetSpawnPoints([tag]) ``` | Parameter | Type | | |---|---|---| | `tag` | string | the list (`""` without) *(optional)* | ## Returns `table` - a list of `{x=, y=, z=, yaw=}`; `{}` when empty ## Example ```lua for i, p in ipairs(GetSpawnPoints("red")) do Log(string.format("red %d: %.1f %.1f", i, p.x, p.y)) end ``` ## See also [AddSpawnPoint](/lua/server/functions/addspawnpoint/) · [GetRandomSpawnPoint](/lua/server/functions/getrandomspawnpoint/) · the [Players](/lua/server/#players) group of the index # GetTerrainHeight > The terrain height at a point, from the level's heightmap. The terrain height at a point, from the level's heightmap. The server has a heightmap when `[validation] heightmap` names one the operator exported from the game; without one, or outside the sampled area, `nil`. Use it to place things on the ground where a `z` below `0` is not accepted. ## Syntax ```lua GetTerrainHeight(x, y) ``` | Parameter | Type | | |---|---|---| | `x` | number | metres | | `y` | number | metres | ## Returns `number` - metres; `nil` without a heightmap or outside it ## Example ```lua local z = GetTerrainHeight(x, y) or -1 CreateProp("barrel_a", x, y, z) ``` ## See also [GetPlayerPos](/lua/server/functions/getplayerpos/) · [SetPlayerPos](/lua/server/functions/setplayerpos/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # GetTimeRatio > How fast the world clock runs - game seconds per real second. How fast the world clock runs - game seconds per real second. ## Syntax ```lua GetTimeRatio() ``` ## Returns `number` - `15` is the game's own pace, `0` frozen ## Example ```lua Log("the day runs at", GetTimeRatio(), "x") ``` ## See also [SetTimeRatio](/lua/server/functions/settimeratio/) · [GetWorldTime](/lua/server/functions/getworldtime/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # GetWeather > The sky profile every client follows. The sky profile every client follows. ## Syntax ```lua GetWeather() ``` ## Returns `string` - a profile name (`cloudless_sunny`, `foggy_storm` ...); `""` = each client's own ## Example ```lua Log("the sky is", GetWeather()) ``` ## See also [SetWeather](/lua/server/functions/setweather/) · [GetWeatherPresets](/lua/server/functions/getweatherpresets/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # GetWeatherPresets > The preset names and the profiles they stand for. The preset names and the profiles they stand for. ## Syntax ```lua GetWeatherPresets() ``` ## Returns `table` - `{preset = profile, ...}` ## Example ```lua for preset, profile in pairs(GetWeatherPresets()) do Log(preset, "->", profile) end ``` ## See also [SetWeather](/lua/server/functions/setweather/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # GetWorldTime > The world clock, in hours since midnight. The world clock, in hours since midnight. ## Syntax ```lua GetWorldTime() ``` ## Returns `number` - `0` .. `24`; `13.5` = 13:30 ## Example ```lua if GetWorldTime() > 20 or GetWorldTime() < 5 then GivePlayerItem(pid, "torch_weapon") end ``` ## See also [SetWorldTime](/lua/server/functions/setworldtime/) · [FormatWorldTime](/lua/server/functions/formatworldtime/) · [GetTimeRatio](/lua/server/functions/gettimeratio/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # GetZoneData > A value stored on a zone with SetZoneData. A value stored on a zone with SetZoneData. ## Syntax ```lua GetZoneData(id, key) ``` | Parameter | Type | | |---|---|---| | `id` | number | the zone | | `key` | string | the key | ## Returns `any` - the value; `nil` when unset or no such zone ## Example ```lua if GetZoneData(zone, "safe") then return false end ``` ## See also [SetZoneData](/lua/server/functions/setzonedata/) · the [Zones](/lua/server/#zones) group of the index # GetZoneInfo > A zone's shape. A zone's shape. ## Syntax ```lua GetZoneInfo(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the zone | ## Returns `table` - `{circle=, minX=, minY=, minZ=, maxX=, maxY=, maxZ=, x=, y=, radius=}`: `circle` true for a circle zone, the box's bounds, the circle's centre and radius (a box's centre and half its diagonal); `nil` when there is no such zone ## Example ```lua local z = GetZoneInfo(arena) Log(string.format("arena at %.1f %.1f, radius %.1f", z.x, z.y, z.radius)) ``` ## See also [CreateZone](/lua/server/functions/createzone/) · [CreateCircleZone](/lua/server/functions/createcirclezone/) · [IsPointInZone](/lua/server/functions/ispointinzone/) · the [Zones](/lua/server/#zones) group of the index # GetZonePlayers > The players inside a zone right now. The players inside a zone right now. ## Syntax ```lua GetZonePlayers(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the zone | ## Returns `table` - a list of pids ## Example ```lua for _, pid in ipairs(GetZonePlayers(arena)) do GameText(pid, "Fight!", 1500) end ``` ## See also [IsPlayerInZone](/lua/server/functions/isplayerinzone/) · [GetPlayerZones](/lua/server/functions/getplayerzones/) · the [Zones](/lua/server/#zones) group of the index # GetZones > Every zone the mode has made. Every zone the mode has made. ## Syntax ```lua GetZones() ``` ## Returns `table` - a list of zone ids ## Example ```lua for _, id in ipairs(GetZones()) do DestroyZone(id) end ``` ## See also [CreateZone](/lua/server/functions/createzone/) · [GetZoneInfo](/lua/server/functions/getzoneinfo/) · the [Zones](/lua/server/#zones) group of the index # GivePlayerBuff > Gives the player a buff of the game's tables. Gives the player a buff of the game's tables. `buff` is a key of [the buff list](/reference/buffs/): the id, the name (`well_rested`, case-insensitive) or the GUID. The player's client adds the game's buff once; the record lasts until [`RemovePlayerBuff`](/lua/server/functions/removeplayerbuff/), the `seconds` given, [`HealPlayer`](/lua/server/functions/healplayer/) or the respawn. `seconds` is the server's own clock - `0` or none means no clock; the game's own duration (the list's `duration` column, in game minutes) may end a timed buff's *visible* effect earlier, and the server does not re-apply it. `false` for an unknown key or a player not in the world. ## Syntax ```lua GivePlayerBuff(pid, buff [, seconds]) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `buff` | string \| number | the buff's name, id or GUID | | `seconds` | number | take it back after this long; `0` or none = keep it *(optional)* | ## Returns `boolean` - `true` when given ## Example ```lua -- the round's winner is well rested for two minutes GivePlayerBuff(winner, "well_rested", 120) ``` ## See also [RemovePlayerBuff](/lua/server/functions/removeplayerbuff/) · [HasPlayerBuff](/lua/server/functions/hasplayerbuff/) · [GetPlayerBuffs](/lua/server/functions/getplayerbuffs/) · [GetBuffInfo](/lua/server/functions/getbuffinfo/) · [ClaimBuffClasses](/lua/server/functions/claimbuffclasses/) · the [Buffs and the drink](/lua/server/#buffs-and-the-drink) group of the index # GivePlayerItem > Puts items in the player's inventory - or takes them out. Puts items in the player's inventory - or takes them out. `amount` (default `1`) of the item; a **negative** amount takes that many away. `item` is any key of [the item catalogue](/reference/items/): the id, the game's name (`shortswordBroad`), the English name (`Duelling longsword`) or the class GUID; an unknown key is logged and nothing happens. Items given here are the server's own in the [inventory audit](/lua/server/callbacks/onplayerauditviolation/). The `/give` built-in is the same call. ## Syntax ```lua GivePlayerItem(pid, item [, amount]) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `item` | string \| number | the item's name, id, English name or GUID | | `amount` | number | how many (`1`); negative takes *(optional)* | ## Returns `boolean` - `false` when not connected ## Example ```lua GivePlayerItem(pid, "longSwordDuel") GivePlayerItem(pid, "arrow_normal", 40) GivePlayerItem(pid, "torch_weapon", -1) -- takes the torch away ``` ## See also [CreatePickup](/lua/server/functions/createpickup/) · [GetPlayerInventory](/lua/server/functions/getplayerinventory/) · [GetItemClass](/lua/server/functions/getitemclass/) · the [Items and inventory](/lua/server/#items-and-inventory) group of the index # HasCollision > Whether the server holds the level's collision geometry. Whether the server holds the level's collision geometry. `true` when the operator exported the level's geometry and `server.toml` names it (`[validation] collision`, [the collision guide](/guides/collision/)): `RayCast` answers, `IsLineOfSight` can say no, the floor under a player counts as the ground of the terrain check. Without it the three functions answer `nil`, `true` and `nil`. ## Syntax ```lua HasCollision() ``` ## Returns `true` when the geometry is loaded ## Example ```lua if not HasCollision() then Log("no collision geometry: rays answer nothing") end ``` ## See also [RayCast](/lua/server/functions/raycast/) · [IsLineOfSight](/lua/server/functions/islineofsight/) · [GetGroundZ](/lua/server/functions/getgroundz/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # HasNavmesh > Whether the server has the level's navigation mesh. Whether the server has the level's navigation mesh. `[validation] navmesh` names the file the operator exported from their game ([the navigation guide](/guides/navigation/)). With it the NPC actors walk around walls and the functions below answer; without it they answer `nil` / `false` and an actor walks a straight line to its target. ## Syntax ```lua HasNavmesh() ``` ## Returns `boolean` ## Example ```lua if not HasNavmesh() then Log("no navmesh: the guards walk straight lines") end ``` ## See also [FindPath](/lua/server/functions/findpath/) · [MoveActor](/lua/server/functions/moveactor/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # HasPlayerBuff > Whether the server gave the player this buff and has not taken it back. Whether the server gave the player this buff and has not taken it back. ## Syntax ```lua HasPlayerBuff(pid, buff) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `buff` | string \| number | the buff's name, id or GUID | ## Returns `boolean` ## Example ```lua if not HasPlayerBuff(pid, "well_rested") then GivePlayerBuff(pid, "well_rested", 60) end ``` ## See also [GivePlayerBuff](/lua/server/functions/giveplayerbuff/) · [GetPlayerBuffs](/lua/server/functions/getplayerbuffs/) · the [Buffs and the drink](/lua/server/#buffs-and-the-drink) group of the index # HealActor > Makes an actor whole - full health, no wounds, no bleeding. Makes an actor whole - full health, no wounds, no bleeding. Every client shows the body straighten. Refused on a corpse. ## Syntax ```lua HealActor(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | ## Returns `boolean` - `false` for a dead actor or anything but an actor ## Example ```lua -- between rounds the champion is patched up HealActor(champion) ``` ## See also [GetActorInjuries](/lua/server/functions/getactorinjuries/) · [GetActorBleeding](/lua/server/functions/getactorbleeding/) · [SetActorHealth](/lua/server/functions/setactorhealth/) · [HealPlayer](/lua/server/functions/healplayer/) · the [NPC actors](/lua/server/#npc-actors) group of the index # HealPlayer > Makes the player whole - health, stamina, injuries, bleeding, buffs, drink. Makes the player whole - health, stamina, injuries, bleeding, buffs, drink. Full health and stamina, every injury healed, the bleeding stopped, every buff the server gave taken back, sober; the player's client shows it and the others see the body straighten. The `/heal` built-in does the same. ## Syntax ```lua HealPlayer(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `boolean` - `false` when not connected ## Example ```lua -- the winner leaves the arena as good as new HealPlayer(winner) SetPlayerPos(winner, lobbyX, lobbyY, lobbyZ) ``` ## See also [SetPlayerHealth](/lua/server/functions/setplayerhealth/) · [SetPlayerStamina](/lua/server/functions/setplayerstamina/) · [ClearPlayerBuffs](/lua/server/functions/clearplayerbuffs/) · [SpawnPlayer](/lua/server/functions/spawnplayer/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # HideHudText > Takes a HUD text off one player's screen. Takes a HUD text off one player's screen. ## Syntax ```lua HideHudText(id, pid) ``` | Parameter | Type | | |---|---|---| | `id` | number | the element | | `pid` | number | the player | ## Returns `boolean` ## Example ```lua HideHudText(arenaTimer, pid) -- they left the arena ``` ## See also [ShowHudText](/lua/server/functions/showhudtext/) · [HideHudTextForAll](/lua/server/functions/hidehudtextforall/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # HideHudTextForAll > Takes a HUD text off every screen (the element stays for later). Takes a HUD text off every screen (the element stays for later). ## Syntax ```lua HideHudTextForAll(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the element | ## Returns `boolean` ## Example ```lua HideHudTextForAll(banner) ``` ## See also [ShowHudTextForAll](/lua/server/functions/showhudtextforall/) · [DestroyHudText](/lua/server/functions/destroyhudtext/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # InviteToParty > Sends a party invitation - the mode's /invite. Sends a party invitation - the mode's /invite. The server checks both players (connected, not the same, the target in no party and with no invitation pending, the inviter's party not full), asks [`OnPartyInvite`](/lua/server/callbacks/onpartyinvite/), and puts the toast with its countdown on the target's screen - two keys answer it, or the mode's [`AcceptPartyInvite`](/lua/server/functions/acceptpartyinvite/) / [`DeclinePartyInvite`](/lua/server/functions/declinepartyinvite/). The party is made when the invitation is accepted, with the inviter leading, when they have none; an inviter who is already in one invites into it. The invitation belongs to that party: the inviter leaving it does not withdraw it; the party filling or ending, or a side disconnecting, does. ## Syntax ```lua InviteToParty(from, target) ``` | Parameter | Type | | |---|---|---| | `from` | number | the inviter | | `target` | number | the player to invite | ## Returns `true`, or `false, reason` - `"not connected"`, `"self"`, `"in a party"` (the target), `"full"`, `"pending"` (the target has one already) or `"refused"` (`OnPartyInvite` said no) ## Example ```lua elseif cmd == "invite" then local target = GetPlayerId(args) if not target then SendClientMessage(pid, COLOUR_RED, "No such player.") return true end local ok, reason = InviteToParty(pid, target) if ok then SendClientMessage(pid, COLOUR_SERVER, "Invited " .. GetPlayerName(target) .. ".") else SendClientMessage(pid, COLOUR_RED, "Cannot invite: " .. reason .. ".") end return true ``` ## See also [AcceptPartyInvite](/lua/server/functions/acceptpartyinvite/) · [DeclinePartyInvite](/lua/server/functions/declinepartyinvite/) · [OnPartyInvite](/lua/server/callbacks/onpartyinvite/) · [GetPlayerPartyInvite](/lua/server/functions/getplayerpartyinvite/) · the [Parties](/lua/server/#parties) group of the index # IsActorBleeding > Whether an actor is bleeding. Whether an actor is bleeding. ## Syntax ```lua IsActorBleeding(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | ## Returns `boolean` ## Example ```lua if IsActorBleeding(id) then SendClientMessageToAll(COLOUR_RED, GetEntityName(id) .. " is bleeding") end ``` ## See also [GetActorBleeding](/lua/server/functions/getactorbleeding/) · the [NPC actors](/lua/server/#npc-actors) group of the index # IsActorDead > Whether an actor is a corpse. Whether an actor is a corpse. ## Syntax ```lua IsActorDead(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | ## Returns `boolean` ## Example ```lua if IsActorDead(id) then DestroyEntity(id) end ``` ## See also [GetActorHealth](/lua/server/functions/getactorhealth/) · [OnActorDeath](/lua/server/callbacks/onactordeath/) · the [NPC actors](/lua/server/#npc-actors) group of the index # IsActorInjured > Whether an actor has a wound - anywhere, or on one part. Whether an actor has a wound - anywhere, or on one part. ## Syntax ```lua IsActorInjured(id [, part]) ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | | `part` | number | a body part `1` .. `6`; without it, any part *(optional)* | ## Returns `boolean` ## Example ```lua if IsActorInjured(id, BODY_PART_ARM_RIGHT) then Log(GetEntityName(id), "swings weakly") end ``` ## See also [GetActorInjuries](/lua/server/functions/getactorinjuries/) · [IsActorBleeding](/lua/server/functions/isactorbleeding/) · the [NPC actors](/lua/server/#npc-actors) group of the index # IsActorMoving > Whether an actor is on its way to a MoveActor target. Whether an actor is on its way to a MoveActor target. ## Syntax ```lua IsActorMoving(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | ## Returns `boolean` - `false` once arrived or stopped ## Example ```lua if not IsActorMoving(guard) then MoveActor(guard, x, y, z, 1.5) end ``` ## See also [MoveActor](/lua/server/functions/moveactor/) · [OnActorArrive](/lua/server/callbacks/onactorarrive/) · the [NPC actors](/lua/server/#npc-actors) group of the index # IsBanned > Whether a name or an address is banned right now, and why. Whether a name or an address is banned right now, and why. ## Syntax ```lua IsBanned(nameOrAddress) ``` | Parameter | Type | | |---|---|---| | `nameOrAddress` | string | a name or an address | ## Returns `string` - the reason, e.g. `"banned: speed hacking (9,000 min left)"`; `nil` when not banned ## Example ```lua local why = IsBanned(args) SendClientMessage(pid, COLOUR_SERVER, why or (args .. " is not banned")) ``` ## See also [Ban](/lua/server/functions/ban/) · [Unban](/lua/server/functions/unban/) · the [Accounts, admins, bans and the audit](/lua/server/#accounts-admins-bans-and-the-audit) group of the index # IsEntityRigid > Whether a prop is a physics body. Whether a prop is a physics body. ## Syntax ```lua IsEntityRigid(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | ## Returns `boolean` - `true` for a rigid prop ## Example ```lua if IsEntityRigid(prop) then Log("this one can be pushed") end ``` ## See also [CreateProp](/lua/server/functions/createprop/) · [GetEntityScale](/lua/server/functions/getentityscale/) · the [Props](/lua/server/#props) group of the index # IsHudTextShown > Whether a HUD text is on a player's screen. Whether a HUD text is on a player's screen. ## Syntax ```lua IsHudTextShown(id, pid) ``` | Parameter | Type | | |---|---|---| | `id` | number | the element | | `pid` | number | the player | ## Returns `boolean` ## Example ```lua if not IsHudTextShown(clock, pid) then ShowHudText(clock, pid) end ``` ## See also [ShowHudText](/lua/server/functions/showhudtext/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # IsLineOfSight > Whether nothing stands between two points. Whether nothing stands between two points. `true` when a ray from the first point reaches the second without meeting the level's geometry - a wall, a roof, a tree, a closed door. Always `true` without the geometry. The server uses the same test on hit claims when `[validation] line_of_sight` is on (a blow through a wall is refused). ## Syntax ```lua IsLineOfSight(x1, y1, z1, x2, y2, z2) ``` | Parameter | Type | | |---|---|---| | `x1` | number | metres | | `y1` | number | metres | | `z1` | number | metres | | `x2` | number | metres | | `y2` | number | metres | | `z2` | number | metres | ## Returns `true` when the line is clear ## Example ```lua local ax, ay, az = GetPlayerPos(archer) local tx, ty, tz = GetPlayerPos(target) if not IsLineOfSight(ax, ay, az + 1.5, tx, ty, tz + 1.5) then SendClientMessage(archer, COLOUR_SERVER, "No shot from here.") end ``` ## See also [RayCast](/lua/server/functions/raycast/) · [HasCollision](/lua/server/functions/hascollision/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # IsPartyFull > Whether the party is at [party] max_size. Whether the party is at [party] max_size. ## Syntax ```lua IsPartyFull(party) ``` | Parameter | Type | | |---|---|---| | `party` | number | the party | ## Returns `boolean` ## Example ```lua if IsPartyFull(party) then SendClientMessage(pid, COLOUR_RED, "The party is full.") return true end ``` ## See also [GetPartySize](/lua/server/functions/getpartysize/) · [InviteToParty](/lua/server/functions/invitetoparty/) · the [Parties](/lua/server/#parties) group of the index # IsPlayerAdmin > Whether the player is an admin. Whether the player is an admin. A logged-in owner of a name on `[accounts] admins`, or a player the mode promoted with [`SetPlayerAdmin`](/lua/server/functions/setplayeradmin/). It unlocks the server's admin-only built-in commands and whatever the mode gates on it. ## Syntax ```lua IsPlayerAdmin(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `boolean` ## Example ```lua function OnPlayerCommandText(pid, cmd, args) if cmd == "arena" then if not IsPlayerAdmin(pid) then SendClientMessage(pid, COLOUR_RED, "Admins only.") return true end moveArena(args) return true end return false end ``` ## See also [SetPlayerAdmin](/lua/server/functions/setplayeradmin/) · [GetAdminNames](/lua/server/functions/getadminnames/) · [IsPlayerLoggedIn](/lua/server/functions/isplayerloggedin/) · the [Accounts, admins, bans and the audit](/lua/server/#accounts-admins-bans-and-the-audit) group of the index # IsPlayerBleeding > Whether the player is bleeding. Whether the player is bleeding. ## Syntax ```lua IsPlayerBleeding(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `boolean` ## Example ```lua if IsPlayerBleeding(pid) then GivePlayerItem(pid, "bandage") end ``` ## See also [GetPlayerBleeding](/lua/server/functions/getplayerbleeding/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # IsPlayerConnected > Whether a pid belongs to a connected player. Whether a pid belongs to a connected player. `true` from the handshake to the disconnect - the player may still be loading the level. For "standing in the world" use [`IsPlayerInWorld`](/lua/server/functions/isplayerinworld/). ## Syntax ```lua IsPlayerConnected(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `boolean` ## Example ```lua if IsPlayerConnected(target) then SetPlayerPos(target, x, y, z) end ``` ## See also [IsPlayerInWorld](/lua/server/functions/isplayerinworld/) · [GetPlayers](/lua/server/functions/getplayers/) · the [Players](/lua/server/#players) group of the index # IsPlayerControllable > Whether the player's keyboard is theirs right now. Whether the player's keyboard is theirs right now. ## Syntax ```lua IsPlayerControllable(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `boolean` - `false` while held ## Example ```lua if not IsPlayerControllable(pid) then SendClientMessage(pid, COLOUR_RED, "Wait for the round to start.") end ``` ## See also [TogglePlayerControllable](/lua/server/functions/toggleplayercontrollable/) · the [Players](/lua/server/#players) group of the index # IsPlayerDead > Whether the player's health is 0 and they wait for the respawn. Whether the player's health is 0 and they wait for the respawn. ## Syntax ```lua IsPlayerDead(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `boolean` ## Example ```lua local function standing(pid) return IsPlayerInWorld(pid) and not IsPlayerDead(pid) end ``` ## See also [GetPlayerHealth](/lua/server/functions/getplayerhealth/) · [OnPlayerDeath](/lua/server/callbacks/onplayerdeath/) · [SpawnPlayer](/lua/server/functions/spawnplayer/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # IsPlayerDrunk > Whether the player is drunk. Whether the player is drunk. ## Syntax ```lua IsPlayerDrunk(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `boolean` ## Example ```lua if IsPlayerDrunk(pid) then return false end -- no duels drunk ``` ## See also [GetPlayerAlcohol](/lua/server/functions/getplayeralcohol/) · [OnPlayerDrunk](/lua/server/callbacks/onplayerdrunk/) · the [Buffs and the drink](/lua/server/#buffs-and-the-drink) group of the index # IsPlayerInjured > Whether the player has an injury - anywhere, or on one part. Whether the player has an injury - anywhere, or on one part. ## Syntax ```lua IsPlayerInjured(pid [, part]) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `part` | number | a body part `1` .. `6`; without it, any part *(optional)* | ## Returns `boolean` ## Example ```lua if IsPlayerInjured(pid, BODY_PART_ARM_RIGHT) then SendClientMessage(pid, COLOUR_RED, "Your sword arm is hurt.") end ``` ## See also [GetPlayerInjuries](/lua/server/functions/getplayerinjuries/) · [GetBodyPartName](/lua/server/functions/getbodypartname/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # IsPlayerInWorld > Whether the player is spawned and replicated. Whether the player is spawned and replicated. `false` while the level loads, while a spawn is held, after a despawn. Positions and vitals mean something only while this is `true`; a dead player waiting for the respawn is still in the world ([`IsPlayerDead`](/lua/server/functions/isplayerdead/)). ## Syntax ```lua IsPlayerInWorld(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `boolean` ## Example ```lua local function standing(pid) return IsPlayerInWorld(pid) and not IsPlayerDead(pid) end ``` ## See also [IsPlayerConnected](/lua/server/functions/isplayerconnected/) · [IsPlayerDead](/lua/server/functions/isplayerdead/) · [OnPlayerSpawn](/lua/server/callbacks/onplayerspawn/) · the [Players](/lua/server/#players) group of the index # IsPlayerInZone > Whether the player is inside a zone, as of the last tick's test. Whether the player is inside a zone, as of the last tick's test. ## Syntax ```lua IsPlayerInZone(pid, id) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `id` | number | the zone | ## Returns `boolean` ## Example ```lua function OnPlayerDamage(pid, attacker, damage) if IsPlayerInZone(pid, lobby) then return false end -- no fighting in the lobby end ``` ## See also [IsPointInZone](/lua/server/functions/ispointinzone/) · [GetPlayerZones](/lua/server/functions/getplayerzones/) · [GetZonePlayers](/lua/server/functions/getzoneplayers/) · the [Zones](/lua/server/#zones) group of the index # IsPlayerLoggedIn > Whether the player proved their registered name this session. Whether the player proved their registered name this session. A guest name is never "logged in"; a registered one is after `/login` or `/register`. ## Syntax ```lua IsPlayerLoggedIn(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `boolean` ## Example ```lua if IsPlayerRegistered(pid) and not IsPlayerLoggedIn(pid) then return false end -- no commands before the login ``` ## See also [IsPlayerRegistered](/lua/server/functions/isplayerregistered/) · [OnPlayerLogin](/lua/server/callbacks/onplayerlogin/) · [IsPlayerAdmin](/lua/server/functions/isplayeradmin/) · the [Accounts, admins, bans and the audit](/lua/server/#accounts-admins-bans-and-the-audit) group of the index # IsPlayerRegistered > Whether the player's name has a password on record. Whether the player's name has a password on record. ## Syntax ```lua IsPlayerRegistered(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `boolean` ## Example ```lua if not IsPlayerRegistered(pid) then SendClientMessage(pid, COLOUR_SERVER, "Claim your name with /register .") end ``` ## See also [IsPlayerLoggedIn](/lua/server/functions/isplayerloggedin/) · [OnPlayerLogin](/lua/server/callbacks/onplayerlogin/) · the [Accounts, admins, bans and the audit](/lua/server/#accounts-admins-bans-and-the-audit) group of the index # IsPointInZone > Whether a point lies inside a zone. Whether a point lies inside a zone. ## Syntax ```lua IsPointInZone(id, x, y [, z]) ``` | Parameter | Type | | |---|---|---| | `id` | number | the zone | | `x` | number | metres | | `y` | number | metres | | `z` | number | metres (`0` without) *(optional)* | ## Returns `boolean` ## Example ```lua local x, y, z = GetEntityPos(horse) if IsPointInZone(stable, x, y, z) then Log("the horse is home") end ``` ## See also [IsPlayerInZone](/lua/server/functions/isplayerinzone/) · [GetZoneInfo](/lua/server/functions/getzoneinfo/) · the [Zones](/lua/server/#zones) group of the index # IsReachable > Whether a walk joins two points on the navigation mesh. Whether a walk joins two points on the navigation mesh. The same test as [`FindPath`](/lua/server/functions/findpath/) without the corners - a spawn point that can be walked out of, a goal that can be reached. ## Syntax ```lua IsReachable(x1, y1, z1, x2, y2, z2) ``` | Parameter | Type | | |---|---|---| | `x1` | number | the start | | `y1` | number | | | `z1` | number | | | `x2` | number | the end | | `y2` | number | | | `z2` | number | | ## Returns `boolean` - `false` off the mesh, unreachable, or without a navmesh ## Example ```lua if not IsReachable(spawnX, spawnY, spawnZ, goalX, goalY, goalZ) then goal = pickAnother() end ``` ## See also [FindPath](/lua/server/functions/findpath/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # Kick > Disconnects the player with a reason. Disconnects the player with a reason. The player's client shows the reason and leaves; [`OnPlayerDisconnect`](/lua/server/callbacks/onplayerdisconnect/) follows with `"kicked: "`. Nothing keeps them from rejoining - for that, [`Ban`](/lua/server/functions/ban/). ## Syntax ```lua Kick(pid [, reason]) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `reason` | string | shown to the player (`"kicked"` without one) *(optional)* | ## Returns `boolean` - `false` when not connected ## Example ```lua function OnPlayerText(pid, text) if text:find("%f[%w]cheat%f[%W]") then Kick(pid, "no talk of cheats") return false end return true end ``` ## See also [Ban](/lua/server/functions/ban/) · [OnPlayerDisconnect](/lua/server/callbacks/onplayerdisconnect/) · the [Players](/lua/server/#players) group of the index # KillTimer > Stops a timer. Stops a timer. ## Syntax ```lua KillTimer(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the id `SetTimer` returned | ## Returns `boolean` - `true` when there was such a timer ## Example ```lua local heartbeat = SetTimer(function() Log("alive") end, 60000, true) -- ... KillTimer(heartbeat) ``` ## See also [SetTimer](/lua/server/functions/settimer/) · the [Server and timers](/lua/server/#server-and-timers) group of the index # Log > Writes a line to the server log, prefixed [lua]. Writes a line to the server log, prefixed `[lua]`. Every argument is converted with `tostring` and joined with spaces, like `print` - and `print` **is** this function in a game mode. The line lands in the server's log (the console and the log file), never in a player's chat. ## Syntax ```lua Log(...) ``` | Parameter | Type | | |---|---|---| | `...` | any | the values to write | ## Returns nothing ## Example ```lua Log("spawned", GetPlayerName(pid), "at", x, y, z) ``` ## See also [SendClientMessage](/lua/server/functions/sendclientmessage/) · the [Server and timers](/lua/server/#server-and-timers) group of the index # MountPlayer > Puts a player in the saddle of a horse. Puts a player in the saddle of a horse. Control goes to the player and their client mounts the horse - it may be anywhere; the game walks or teleports the player onto it. `false` when it is not a horse, someone else rides it, or the player is not in the world. ## Syntax ```lua MountPlayer(pid, id) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `id` | number | the horse | ## Returns `boolean` ## Example ```lua local horse = GetNearestEntity(pid, ENTITY_HORSE, 10) if horse and not GetEntityRider(horse) then MountPlayer(pid, horse) end ``` ## See also [CreateHorse](/lua/server/functions/createhorse/) · [GetPlayerMount](/lua/server/functions/getplayermount/) · [GetEntityRider](/lua/server/functions/getentityrider/) · [OnPlayerMount](/lua/server/callbacks/onplayermount/) · the [Horses](/lua/server/#horses) group of the index # MoveActor > Walks an actor to a point - around the walls when the server has the navigation mesh. Walks an actor to a point - around the walls when the server has the navigation mesh. At `speed` metres per second, facing its way - about 1.5 walks, 4 runs, 6.5 sprints (the body's clips follow the speed). [`OnActorArrive`](/lua/server/callbacks/onactorarrive/) fires when it gets there. A new target replaces the old one; a pose ([`SetActorAnim`](/lua/server/functions/setactoranim/)) is cleared. With the level's navigation mesh ([`HasNavmesh`](/lua/server/functions/hasnavmesh/), [the navigation guide](/guides/navigation/)) the actor takes the walk the game's own people would - corner by corner, around walls and through doorways; a target off the mesh (in a wall, on a roof) or a server without the mesh gets the straight line, where the body stops at a wall and catches up when the line comes out. ## Syntax ```lua MoveActor(id, x, y, z [, speed]) ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | | `x` | number | metres | | `y` | number | metres | | `z` | number | metres | | `speed` | number | metres per second (`1.5`) *(optional)* | ## Returns `boolean` - `false` for anything but a living actor ## Example ```lua MoveActor(guard, 1300, 1100, -1, 1.5) -- a walk MoveActor(runner, tx, ty, tz, 4) -- a run ``` ## See also [StopActor](/lua/server/functions/stopactor/) · [TurnActor](/lua/server/functions/turnactor/) · [IsActorMoving](/lua/server/functions/isactormoving/) · [OnActorArrive](/lua/server/callbacks/onactorarrive/) · the [NPC actors](/lua/server/#npc-actors) group of the index # NearestNavmeshPoint > The nearest point on the navigation mesh. The nearest point on the navigation mesh. Where to put a spawn, a prop or an actor so that it stands on walkable ground: the point on the mesh nearest the one given, within 2 m sideways and 4 m up or down; `nil` when the mesh is farther, or without a navmesh. ## Syntax ```lua NearestNavmeshPoint(x, y, z) ``` | Parameter | Type | | |---|---|---| | `x` | number | metres | | `y` | number | metres | | `z` | number | metres | ## Returns `x, y, z` - the point on the mesh; `nil` when none is that close ## Example ```lua local x, y, z = NearestNavmeshPoint(gx, gy, gz) if x then MoveActor(guard, x, y, z, 1.5) end ``` ## See also [GetNavmeshHeight](/lua/server/functions/getnavmeshheight/) · [FindPath](/lua/server/functions/findpath/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # PlaySound > Plays one of the game's sounds at a point for everyone nearby. Plays one of the game's sounds at a point for everyone nearby. `trigger` is an audio trigger of the game's sound banks by name - `lightning`, `c_neck_snap`, `male_spit`, `special_barber_scissors` ... ([the audio triggers](/reference/audio-triggers/) list all 15,000) - played the game's own way from a short-lived emitter at the point: each player hears it from where it is. The emitter stays `seconds` (`0` = 10); a looping trigger ends with it. The same reach and return as [`SpawnEffect`](/lua/server/functions/spawneffect/). ## Syntax ```lua PlaySound(trigger, x, y, z [, seconds, world]) ``` | Parameter | Type | | |---|---|---| | `trigger` | string | the audio trigger's name | | `x` | number | metres | | `y` | number | metres | | `z` | number | metres | | `seconds` | number | how long the sound source stays; `0` = 10 *(optional)* | | `world` | number | the virtual world (`0`) *(optional)* | ## Returns `number` - how many players heard it ## Example ```lua -- thunder over the arena as the round starts PlaySound("lightning", arenaX, arenaY, arenaZ + 20) ``` ## See also [SpawnEffect](/lua/server/functions/spawneffect/) · [GameTextForAll](/lua/server/functions/gametextforall/) · the [Effects and sounds](/lua/server/#effects-and-sounds) group of the index # RayCast > The nearest surface along a line. The nearest surface along a line. Shoots a ray from one point to the other through the level's static geometry and answers with the first surface it meets: where, which way it faces, how far along, the engine's material id of a mesh triangle (0 for the primitives), and - when the surface belongs to a game entity (a door, a chest, a ladder) - the entity's class and name. Players, actors and horses are not in the geometry; the doors the server's records say are open are let through. ## Syntax ```lua RayCast(x1, y1, z1, x2, y2, z2) ``` | Parameter | Type | | |---|---|---| | `x1` | number | metres, the start | | `y1` | number | metres | | `z1` | number | metres | | `x2` | number | metres, the end | | `y2` | number | metres | | `z2` | number | metres | ## Returns a table `{x, y, z, nx, ny, nz, distance, material, class, name}` - the point, the normal, the metres along the line, the material, the owning entity's class and name (empty strings for the level's own geometry); `nil` when nothing is in the way, or without the geometry ## Example ```lua local hit = RayCast(px, py, pz + 1.5, px + 20 * dx, py + 20 * dy, pz + 1.5) if hit then SendClientMessage(pid, COLOUR_SERVER, string.format("a wall %.1f m ahead", hit.distance)) end ``` ## See also [IsLineOfSight](/lua/server/functions/islineofsight/) · [GetGroundZ](/lua/server/functions/getgroundz/) · [HasCollision](/lua/server/functions/hascollision/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # ReloadGameMode > Reloads this mode at the end of the tick, without restarting the server. Reloads this mode at the end of the tick, without restarting the server. The running mode is shut down (`OnGameModeExit`), everything it made is torn down - zones, HUD texts, props, actors, state bags, nameplates, colours, teams, timers, `SetPlayerData`, the admins it promoted - and the script is read again from disk and initialised (`OnGameModeInit`), then told about every player again (`OnPlayerConnect`, `OnPlayerLogin`, `OnPlayerSpawn`). The players, their vitals, inventories, buffs, horses, drops, doors and containers stay as they are; everyone reads `the game mode was reloaded: `. A script that fails to load leaves the built-in freeroam in charge until the next reload; a missing file refuses the reload. `/reload` (admins) and `[gamemode] watch = true` do the same. ## Syntax ```lua ReloadGameMode([reason]) ``` | Parameter | Type | | |---|---|---| | `reason` | string | a word for the log (`"the script asked"` without one) *(optional)* | ## Returns nothing ## Example ```lua function OnPlayerCommandText(pid, cmd, args) if cmd == "restart" and IsPlayerAdmin(pid) then ReloadGameMode("/restart by " .. GetPlayerName(pid)) return true end return false end ``` ## See also [OnGameModeInit](/lua/server/callbacks/ongamemodeinit/) · [OnGameModeExit](/lua/server/callbacks/ongamemodeexit/) · the [Server and timers](/lua/server/#server-and-timers) group of the index # RemovePlayerBuff > Takes a buff off the player. Takes a buff off the player. Removes the server's record and every copy of the buff on the player's character, including ones the game gave by itself. ## Syntax ```lua RemovePlayerBuff(pid, buff) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `buff` | string \| number | the buff's name, id or GUID | ## Returns `boolean` - `true` when the key resolved and the player is connected ## Example ```lua RemovePlayerBuff(pid, "well_rested") ``` ## See also [GivePlayerBuff](/lua/server/functions/giveplayerbuff/) · [ClearPlayerBuffs](/lua/server/functions/clearplayerbuffs/) · the [Buffs and the drink](/lua/server/#buffs-and-the-drink) group of the index # RemovePlayerFromParty > Takes a player out of their party - the mode's /leave and /kick. Takes a player out of their party - the mode's /leave and /kick. `reason` `"left"` (the default) or `"kicked"` is what [`OnPlayerLeaveParty`](/lua/server/callbacks/onplayerleaveparty/) hears. The leader leaving hands the lead on (or ends the party, by `[party] leader_leaves`); a party left with one member ends. ## Syntax ```lua RemovePlayerFromParty(pid [, reason]) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the member | | `reason` | string | `"left"` or `"kicked"` *(optional)* | ## Returns `boolean` - `false` when in no party ## Example ```lua elseif cmd == "leave" then if not RemovePlayerFromParty(pid, "left") then SendClientMessage(pid, COLOUR_RED, "You are in no party.") end return true ``` ## See also [AddPlayerToParty](/lua/server/functions/addplayertoparty/) · [DisbandParty](/lua/server/functions/disbandparty/) · [OnPlayerLeaveParty](/lua/server/callbacks/onplayerleaveparty/) · the [Parties](/lua/server/#parties) group of the index # SendClientEvent > A named event with a string payload to one player's client script. A named event with a string payload to one player's client script. The client script's `KcdMp.on_event(name, fn)` handler for `name` receives it (or its `KcdMp.on_any_event`); a client without a script, or without a handler for the name, ignores it. `payload` is a string - format it however the two halves agree. Nothing is queued for a client that has not loaded the level yet. ## Syntax ```lua SendClientEvent(pid, name [, payload]) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `name` | string | the event's name | | `payload` | string | the string to send (`""` without) *(optional)* | ## Returns `boolean` - `false` when not connected ## Example ```lua -- a marker the client script draws SendClientEvent(pid, "marker", string.format("%.1f,%.1f,%.1f", x, y, z)) ``` ## See also [SendClientEventToAll](/lua/server/functions/sendclienteventtoall/) · [OnClientEvent](/lua/server/callbacks/onclientevent/) · [SetPlayerState](/lua/server/functions/setplayerstate/) · the [Script events](/lua/server/#script-events) group of the index # SendClientEventToAll > The same event to every connected client. The same event to every connected client. ## Syntax ```lua SendClientEventToAll(name [, payload]) ``` | Parameter | Type | | |---|---|---| | `name` | string | the event's name | | `payload` | string | the string to send (`""` without) *(optional)* | ## Returns nothing ## Example ```lua SendClientEventToAll("round", tostring(round)) ``` ## See also [SendClientEvent](/lua/server/functions/sendclientevent/) · [SetGlobalState](/lua/server/functions/setglobalstate/) · the [Script events](/lua/server/#script-events) group of the index # SendClientMessage > A line in one player's chat. A line in one player's chat. The line appears in the player's chat window in `colour` (`0xRRGGBBAA`; the [colour constants](/lua/server/constants/#colours) name the usual ones). Long lines wrap; keep them to a sentence or two. ## Syntax ```lua SendClientMessage(pid, colour, text) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `colour` | number | `0xRRGGBBAA` | | `text` | string | the line | ## Returns `boolean` - `false` when not connected ## Example ```lua SendClientMessage(pid, COLOUR_RED, "You cannot do that here.") SendClientMessage(pid, COLOUR_SERVER, string.format("%d player(s) online", GetPlayerCount())) ``` ## See also [SendClientMessageToAll](/lua/server/functions/sendclientmessagetoall/) · [GameText](/lua/server/functions/gametext/) · [Log](/lua/server/functions/log/) · the [Chat and commands](/lua/server/#chat-and-commands) group of the index # SendClientMessageToAll > The same line in everyone's chat. The same line in everyone's chat. ## Syntax ```lua SendClientMessageToAll(colour, text) ``` | Parameter | Type | | |---|---|---| | `colour` | number | `0xRRGGBBAA` | | `text` | string | the line | ## Returns nothing ## Example ```lua SendClientMessageToAll(COLOUR_YELLOW, string.format("%s wins the round!", GetPlayerName(winner))) ``` ## See also [SendClientMessage](/lua/server/functions/sendclientmessage/) · [GameTextForAll](/lua/server/functions/gametextforall/) · the [Chat and commands](/lua/server/#chat-and-commands) group of the index # SendPartyMessage > One chat line to every member - the mode's /p. One chat line to every member - the mode's /p. ## Syntax ```lua SendPartyMessage(party, colour, text) ``` | Parameter | Type | | |---|---|---| | `party` | number | the party | | `colour` | number | 0xRRGGBBAA | | `text` | string | the line | ## Returns `boolean` - `false` for an unknown party ## Example ```lua elseif cmd == "p" then local party = GetPlayerParty(pid) if not party then SendClientMessage(pid, COLOUR_RED, "You are in no party.") return true end SendPartyMessage(party, 0x80C0FFFF, "[Party] " .. GetPlayerName(pid) .. ": " .. args) return true ``` ## See also [SendClientMessage](/lua/server/functions/sendclientmessage/) · [GetPartyMembers](/lua/server/functions/getpartymembers/) · the [Parties](/lua/server/#parties) group of the index # SetActorAnim > Puts a pose on a standing actor - a clip of the game's animation set. Puts a pose on a standing actor - a clip of the game's animation set. `clip` is a clip name of [the male animation set](/reference/animations/) (`behavior_sitting_variation01_loop`, `greetings_wave_big_over`, `woodchopping_loop_01` ...) or one of the aliases the API names: `sit`, `wave`, `bow`, `nod`, `pray`, `chop`, `sweep`, `smith` (`ACTOR_ANIM` in [Constants](/lua/server/constants/#poses)). `loop` `true` (the default) plays it until cleared; `false` plays it once. `nil` clears the pose; so do [`MoveActor`](/lua/server/functions/moveactor/) and a death. The pose rides in the actor's state bag (key `anim`), so a player who arrives later finds the guard sitting. A chore without its prop mimes - a smith without an anvil. ## Syntax ```lua SetActorAnim(id, clip [, loop]) ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | | `clip` | string \| nil | a clip name or an alias; `nil` clears the pose | | `loop` | boolean | `true` (the default) loops; `false` plays once *(optional)* | ## Returns `boolean` - `false` for anything but a living actor ## Example ```lua StopActor(guard) SetActorAnim(guard, "sit") -- an alias: loops SetActorAnim(herald, "greetings_wave_big_over", false) -- a clip by name, once SetActorAnim(guard, nil) -- stands up ``` ## See also [MoveActor](/lua/server/functions/moveactor/) · [StopActor](/lua/server/functions/stopactor/) · [SetEntityState](/lua/server/functions/setentitystate/) · the [NPC actors](/lua/server/#npc-actors) group of the index # SetActorHealth > Sets an actor's health; 0 kills it. Sets an actor's health; 0 kills it. Clamped to `0` .. `100`; `0` kills it now ([`OnActorDeath`](/lua/server/callbacks/onactordeath/) with attacker `-1`). Refused on a dead actor - a corpse stays a corpse; [`DestroyEntity`](/lua/server/functions/destroyentity/) and [`CreateActor`](/lua/server/functions/createactor/) again. ## Syntax ```lua SetActorHealth(id, health) ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | | `health` | number | the new health | ## Returns `boolean` - `false` for a dead actor or anything but an actor ## Example ```lua SetActorHealth(id, 100) -- patched up SetActorHealth(id, 0) -- executed ``` ## See also [GetActorHealth](/lua/server/functions/getactorhealth/) · [IsActorDead](/lua/server/functions/isactordead/) · [OnActorDeath](/lua/server/callbacks/onactordeath/) · the [NPC actors](/lua/server/#npc-actors) group of the index # SetActorHostile > Sets an actor on a player - or stands it down. Sets an actor on a player - or stands it down. `true` makes the player the actor's opponent: their game may lock on to the actor's body, and the actor faces them, walks after them (`[actors] chase_speed`, up to `chase_range`) and swings every `[actors] swing_interval` seconds within `[actors] reach`, with the weapon of its preset or its fists; a blow that lands comes to the mode as [`OnActorAttack`](/lua/server/callbacks/onactorattack/). A player's blow on the actor does the same by itself when `[actors] fight_back` is on. `false` stands it down - so do the opponent's death or leaving, another world, `chase_range`, [`MoveActor`](/lua/server/functions/moveactor/) and the actor's own death. ## Syntax ```lua SetActorHostile(pid, id, hostile) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `id` | number | the actor | | `hostile` | boolean | `true` = the actor fights the player; `false` = peace | ## Returns `boolean` - `false` for anything but a living actor or a player not in the world ## Example ```lua -- the arena's champion squares up before the first blow local champion = CreateActor("test_cuman_ai", ax, ay, az, 180, "The Champion") SetActorHostile(pid, champion, true) ``` ## See also [CreateActor](/lua/server/functions/createactor/) · [OnActorAttack](/lua/server/callbacks/onactorattack/) · [OnActorDamage](/lua/server/callbacks/onactordamage/) · [StopActor](/lua/server/functions/stopactor/) · the [NPC actors](/lua/server/#npc-actors) group of the index # SetContainerItems > Rewrites a container's contents; whoever has it open sees the new list. Rewrites a container's contents; whoever has it open sees the new list. Each entry is a stack: the item **class GUID** (names are not resolved here - [`GetItemClass`](/lua/server/functions/getitemclass/) turns a name or an id into the GUID), an amount (`1`) and a condition in percent (`100`). An empty list empties the chest. Items taken from a container the server filled are the server's own in the inventory audit. ## Syntax ```lua SetContainerItems(key, items) ``` | Parameter | Type | | |---|---|---| | `key` | string | the container's level name | | `items` | table | a list of `{class=, amount=, health=}` (`amount` and `health` optional) | ## Returns nothing ## Example ```lua -- the arena's armoury restocks between rounds SetContainerItems(ARMOURY, { {class = GetItemClass("longSwordDuel"), amount = 2}, {class = GetItemClass("arrow_normal"), amount = 60}, {class = GetItemClass("bandage"), amount = 5, health = 100}, }) ``` ## See also [GetContainerItems](/lua/server/functions/getcontaineritems/) · [GetContainerUser](/lua/server/functions/getcontaineruser/) · [GetItemClass](/lua/server/functions/getitemclass/) · the [Doors and containers](/lua/server/#doors-and-containers) group of the index # SetDogMode > Tells a dog to stay, follow or roam. Tells a dog to stay, follow or roam. `mode` is one of the game's dog modes - `DOG_STAY` (0), `DOG_FOLLOW` (1, what a new dog does), `DOG_FREE` (2) and the others of the list above. It is kept on the dog's state bag as `mode`, so it survives the master walking out of range and back, and [`GetEntityState`](/lua/server/functions/getentitystate/)`(dog, "mode")` reads the same number. False for an id that is not a dog or a mode outside 0-7. The `/dog stay|follow|free` built-in does exactly this. ## Syntax ```lua SetDogMode(id, mode) ``` | Parameter | Type | | |---|---|---| | `id` | number | the dog's entity id | | `mode` | number | `DOG_STAY`, `DOG_FOLLOW`, `DOG_FREE`, ... (0-7) | ## Returns `boolean` - true when the mode was set ## Example ```lua -- the dog waits while its master is in the arena function OnPlayerEnterZone(pid, zone) local dog = GetPlayerDog(pid) if dog and zone == "arena" then SetDogMode(dog, DOG_STAY) end end ``` ## See also [GetDogMode](/lua/server/functions/getdogmode/) · [GetPlayerDog](/lua/server/functions/getplayerdog/) · [CreateDog](/lua/server/functions/createdog/) · the [Dogs](/lua/server/#dogs) group of the index # SetDoorState > Opens, closes, locks or unlocks a door on every client. Opens, closes, locks or unlocks a door on every client. ## Syntax ```lua SetDoorState(key, open, locked) ``` | Parameter | Type | | |---|---|---| | `key` | string | the door's level name | | `open` | boolean | open | | `locked` | boolean | locked | ## Returns nothing ## Example ```lua SetDoorState(GATE, true, false) -- the gate opens for the round SetTimer(function() SetDoorState(GATE, false, true) end, 30000) ``` ## See also [GetDoorState](/lua/server/functions/getdoorstate/) · [OnPlayerUseDoor](/lua/server/callbacks/onplayerusedoor/) · the [Doors and containers](/lua/server/#doors-and-containers) group of the index # SetEntityController > Hands the simulation of an entity to a player, or to nobody. Hands the simulation of an entity to a player, or to nobody. The way a horse changes hands: the new controller's client spawns and drives the real thing, the others see a puppet. `nil` gives it to nobody - it stands still until the minder hands it to the nearest player. Refused while someone else rides it. ## Syntax ```lua SetEntityController(id, pid) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | | `pid` | number \| nil | the new controller; `nil` = nobody | ## Returns `boolean` - `false` when refused ## Example ```lua SetEntityController(horse, pid) ``` ## See also [GetEntityController](/lua/server/functions/getentitycontroller/) · [MountPlayer](/lua/server/functions/mountplayer/) · the [World entities](/lua/server/#world-entities) group of the index # SetEntityData > Stores a value on a world entity, private to the server. Stores a value on a world entity, private to the server. Any Lua value; gone with the entity and on a reload. For a value the clients read use [`SetEntityState`](/lua/server/functions/setentitystate/). ## Syntax ```lua SetEntityData(id, key, value) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | | `key` | string | the key | | `value` | any | the value; `nil` removes the key | ## Returns `boolean` - `false` when there is no such entity ## Example ```lua local id = CreatePickup("longSwordDuel", x, y, z) SetEntityData(id, "owner", winner) ``` ## See also [GetEntityData](/lua/server/functions/getentitydata/) · [SetEntityState](/lua/server/functions/setentitystate/) · [SetZoneData](/lua/server/functions/setzonedata/) · the [Storage and persistence](/lua/server/#storage-and-persistence) group of the index # SetEntityPos > Moves an entity. Moves an entity. Its controller, if any, puts the real thing there; a static prop or a loose horse is moved outright on every screen. Without `yaw` it keeps its heading. ## Syntax ```lua SetEntityPos(id, x, y, z [, yaw]) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | | `x` | number | metres | | `y` | number | metres | | `z` | number | metres | | `yaw` | number | degrees *(optional)* | ## Returns `boolean` - `false` when there is no such entity ## Example ```lua SetEntityPos(horse, x, y, z, 90) ``` ## See also [GetEntityPos](/lua/server/functions/getentitypos/) · [MoveActor](/lua/server/functions/moveactor/) · the [World entities](/lua/server/#world-entities) group of the index # SetEntityState > Sets a key of an entity's bag, read by every client that sees the entity. Sets a key of an entity's bag, read by every client that sees the entity. The bag travels with the entity's spawn to whoever comes into range and is dropped when it leaves their view - `KcdMp.state.entity[id][key]` while the entity is in view. Gone with the entity. An NPC actor's pose rides in its bag under the key `anim` ([`SetActorAnim`](/lua/server/functions/setactoranim/)). ## Syntax ```lua SetEntityState(id, key, value) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | | `key` | string | 1-48 characters | | `value` | string \| number \| boolean \| nil | kept as a string; `nil` removes the key | ## Returns `boolean` - `false` when there is no such entity or out of bounds ## Example ```lua local horse = CreateHorse(x, y, z, yaw, pid) SetEntityState(horse, "owner", GetPlayerName(pid)) -- the client scripts can label it ``` ## See also [GetEntityState](/lua/server/functions/getentitystate/) · [GetEntityStates](/lua/server/functions/getentitystates/) · [SetEntityData](/lua/server/functions/setentitydata/) · the [State bags](/lua/server/#state-bags) group of the index # SetEntityVirtualWorld > Moves an entity into another virtual world. Moves an entity into another virtual world. Only the players of that world see it from the next snapshot on. A ridden horse is refused - it is where its rider is. ## Syntax ```lua SetEntityVirtualWorld(id, world) ``` | Parameter | Type | | |---|---|---| | `id` | number | the entity | | `world` | number | the world; `0` = the shared one | ## Returns `boolean` - `false` when refused or no such entity ## Example ```lua SetEntityVirtualWorld(prop, arenaWorld) ``` ## See also [GetEntityVirtualWorld](/lua/server/functions/getentityvirtualworld/) · [SetPlayerVirtualWorld](/lua/server/functions/setplayervirtualworld/) · the [World entities](/lua/server/#world-entities) group of the index # SetGameModeText > Names the mode in the server log and the server browser. Names the mode in the server log and the server browser. ## Syntax ```lua SetGameModeText(name) ``` | Parameter | Type | | |---|---|---| | `name` | string | the mode's name, e.g. `"freeroam"` | ## Returns nothing ## Example ```lua SetGameModeText("duel_arena") ``` ## See also [GetLevel](/lua/server/functions/getlevel/) · the [Server and timers](/lua/server/#server-and-timers) group of the index # SetGlobalState > Sets a key of the world's bag, read by every client. Sets a key of the world's bag, read by every client. ## Syntax ```lua SetGlobalState(key, value) ``` | Parameter | Type | | |---|---|---| | `key` | string | 1-48 characters | | `value` | string \| number \| boolean \| nil | kept as a string; `nil` removes the key | ## Returns `boolean` - `false` when the key or the value is out of bounds or the bag is full ## Example ```lua SetGlobalState("round", 3) -- KcdMp.state.global.round == "3" on every client SetGlobalState("flag_carrier", GetPlayerName(pid)) SetGlobalState("flag_carrier", nil) -- removed ``` ## See also [GetGlobalState](/lua/server/functions/getglobalstate/) · [GetGlobalStates](/lua/server/functions/getglobalstates/) · [SetPlayerState](/lua/server/functions/setplayerstate/) · [SetEntityState](/lua/server/functions/setentitystate/) · the [State bags](/lua/server/#state-bags) group of the index # SetHudText > Changes a HUD text's text. Changes a HUD text's text. Re-sent to everyone the element is shown to. A change every second is fine; every tick is not. ## Syntax ```lua SetHudText(id, text) ``` | Parameter | Type | | |---|---|---| | `id` | number | the element | | `text` | string | the new line | ## Returns `boolean` - `false` when there is no such element ## Example ```lua SetHudText(score, string.format("Red %d - Blue %d", red, blue)) ``` ## See also [GetHudText](/lua/server/functions/gethudtext/) · [CreateHudText](/lua/server/functions/createhudtext/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # SetHudTextAlign > Changes which side of a HUD text sits at its x. Changes which side of a HUD text sits at its x. ## Syntax ```lua SetHudTextAlign(id, align) ``` | Parameter | Type | | |---|---|---| | `id` | number | the element | | `align` | number | `HUD_ALIGN_LEFT`, `HUD_ALIGN_CENTRE` or `HUD_ALIGN_RIGHT` | ## Returns `boolean` ## Example ```lua SetHudTextAlign(banner, HUD_ALIGN_CENTRE) ``` ## See also [CreateHudText](/lua/server/functions/createhudtext/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # SetHudTextColour > Recolours a HUD text. Recolours a HUD text. ## Syntax ```lua SetHudTextColour(id, colour) ``` | Parameter | Type | | |---|---|---| | `id` | number | the element | | `colour` | number | `0xRRGGBBAA` | ## Returns `boolean` ## Example ```lua SetHudTextColour(timer, secondsLeft <= 10 and COLOUR_RED or COLOUR_WHITE) ``` ## See also [CreateHudText](/lua/server/functions/createhudtext/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # SetHudTextPos > Moves a HUD text. Moves a HUD text. ## Syntax ```lua SetHudTextPos(id, x, y) ``` | Parameter | Type | | |---|---|---| | `id` | number | the element | | `x` | number | `0` .. `1` of the width | | `y` | number | `0` .. `1` of the height | ## Returns `boolean` ## Example ```lua SetHudTextPos(banner, 0.5, 0.1) ``` ## See also [CreateHudText](/lua/server/functions/createhudtext/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # SetHudTextScale > Resizes a HUD text. Resizes a HUD text. ## Syntax ```lua SetHudTextScale(id, scale) ``` | Parameter | Type | | |---|---|---| | `id` | number | the element | | `scale` | number | `1` = the HUD's own size; `0.5` .. `5` | ## Returns `boolean` ## Example ```lua SetHudTextScale(banner, 2) ``` ## See also [CreateHudText](/lua/server/functions/createhudtext/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # SetPartyData > The mode's private storage on a party. The mode's private storage on a party. A key and any value the mode keeps with the party; gone with it. `nil` removes the key. ## Syntax ```lua SetPartyData(party, key, value) ``` | Parameter | Type | | |---|---|---| | `party` | number | the party | | `key` | string | the key | | `value` | any | the value; `nil` removes | ## Returns `boolean` - `false` for an unknown party ## Example ```lua SetPartyData(party, "round", 3) ``` ## See also [GetPartyData](/lua/server/functions/getpartydata/) · [SetPlayerData](/lua/server/functions/setplayerdata/) · the [Parties](/lua/server/#parties) group of the index # SetPartyLeader > Hands the lead to a member - the mode's /leader. Hands the lead to a member - the mode's /leader. ## Syntax ```lua SetPartyLeader(party, pid) ``` | Parameter | Type | | |---|---|---| | `party` | number | the party | | `pid` | number | the member who leads from now | ## Returns `boolean` - `false` when they are not a member ## Example ```lua elseif cmd == "leader" then local party, target = GetPlayerParty(pid), GetPlayerId(args) if party and GetPartyLeader(party) == pid and target then SetPartyLeader(party, target) end return true ``` ## See also [GetPartyLeader](/lua/server/functions/getpartyleader/) · [OnPartyLeaderChange](/lua/server/callbacks/onpartyleaderchange/) · the [Parties](/lua/server/#parties) group of the index # SetPartyMemberLabel > A line under the member's name in the frames - a role, a score. A line under the member's name in the frames - a role, a score. Cosmetic; goes with the membership. `""` clears it. ## Syntax ```lua SetPartyMemberLabel(pid, text) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the member | | `text` | string | the label; `""` none | ## Returns `boolean` - `false` when in no party ## Example ```lua SetPartyMemberLabel(pid, "healer") ``` ## See also [GetPartyMemberLabel](/lua/server/functions/getpartymemberlabel/) · [SetPartyName](/lua/server/functions/setpartyname/) · the [Parties](/lua/server/#parties) group of the index # SetPartyName > The party's title, shown over the members' frames. The party's title, shown over the members' frames. ## Syntax ```lua SetPartyName(party, text) ``` | Parameter | Type | | |---|---|---| | `party` | number | the party | | `text` | string | the title; `""` none | ## Returns `boolean` - `false` for an unknown party ## Example ```lua SetPartyName(party, "The Kingsmen") ``` ## See also [GetPartyName](/lua/server/functions/getpartyname/) · [SetPartyMemberLabel](/lua/server/functions/setpartymemberlabel/) · the [Parties](/lua/server/#parties) group of the index # SetPlayerAdmin > Makes the player an admin for the session - or takes it back. Makes the player an admin for the session - or takes it back. The `[accounts] admins` list in `server.toml` is the persistent way; this one lasts until the disconnect or a reload (the listed admins keep theirs). ## Syntax ```lua SetPlayerAdmin(pid, admin) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `admin` | boolean | `true` promotes, `false` demotes (`true` without) | ## Returns `boolean` - `false` when not connected ## Example ```lua -- the first player on an empty server runs it function OnPlayerSpawn(pid) if GetPlayerCount() == 1 then SetPlayerAdmin(pid, true) end end ``` ## See also [IsPlayerAdmin](/lua/server/functions/isplayeradmin/) · [GetAdminNames](/lua/server/functions/getadminnames/) · the [Accounts, admins, bans and the audit](/lua/server/#accounts-admins-bans-and-the-audit) group of the index # SetPlayerAlcohol > Sets the player's blood-alcohol level; the drunk state is judged at once. Sets the player's blood-alcohol level; the drunk state is judged at once. Above the threshold the player is drunk on the spot - the game's drunkenness buff on their character, the sway on the others' screens, `OnPlayerDrunk(pid, true)`; `0` sobers them (the hangover follows as after a real night). ## Syntax ```lua SetPlayerAlcohol(pid, level) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `level` | number | `0` .. `1` | ## Returns nothing ## Example ```lua -- /drunk: a party trick for admins SetPlayerAlcohol(pid, 0.6) ``` ## See also [GetPlayerAlcohol](/lua/server/functions/getplayeralcohol/) · [IsPlayerDrunk](/lua/server/functions/isplayerdrunk/) · [OnPlayerDrunk](/lua/server/callbacks/onplayerdrunk/) · the [Buffs and the drink](/lua/server/#buffs-and-the-drink) group of the index # SetPlayerColor > The same function as SetPlayerColour. `SetPlayerColor` is another name for [SetPlayerColour](/lua/server/functions/setplayercolour/); the two are the same function. # SetPlayerColour > The colour of the player's label and of their name in the Tab roster. The colour of the player's label and of their name in the Tab roster. `0xRRGGBBAA`; `0` puts the default back. The alpha byte matters - `0x4080FF00` is invisible. `SetPlayerColor` is the same function. ## Syntax ```lua SetPlayerColour(pid, colour) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `colour` | number | `0xRRGGBBAA`; `0` = the default | ## Returns `boolean` - `false` when not connected ## Example ```lua -- /colour rrggbb local rgb = tonumber(args:match("^%s*#?(%x%x%x%x%x%x)%s*$") or "", 16) SetPlayerColour(pid, rgb and (rgb * 256 + 255) or 0) ``` ## See also [GetPlayerColour](/lua/server/functions/getplayercolour/) · [SetPlayerNameplate](/lua/server/functions/setplayernameplate/) · [SetPlayerTeam](/lua/server/functions/setplayerteam/) · the [Players](/lua/server/#players) group of the index # SetPlayerData > Stores a value on the player, private to the server, for the session. Stores a value on the player, private to the server, for the session. Any Lua value - a string, a number, a boolean, a table. Cleared when the player disconnects and on a reload. Never replicated: for a value the clients read use [`SetPlayerState`](/lua/server/functions/setplayerstate/); for one that should survive the visit, [`SetSavedData`](/lua/server/functions/setsaveddata/). ## Syntax ```lua SetPlayerData(pid, key, value) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `key` | string | the key | | `value` | any | the value; `nil` removes the key | ## Returns `boolean` - `false` when not connected ## Example ```lua SetPlayerData(pid, "team", "red") SetPlayerData(pid, "kills", (GetPlayerData(pid, "kills") or 0) + 1) ``` ## See also [GetPlayerData](/lua/server/functions/getplayerdata/) · [SetSavedData](/lua/server/functions/setsaveddata/) · [SetPlayerState](/lua/server/functions/setplayerstate/) · the [Storage and persistence](/lua/server/#storage-and-persistence) group of the index # SetPlayerHealth > Sets the player's health; 0 kills. Sets the player's health; 0 kills. Clamped to `0 .. max`; the player's client shows the new value. `0` kills the player at once - [`OnPlayerDeath`](/lua/server/callbacks/onplayerdeath/) with attacker `-1`, the respawn after `[combat] respawn_seconds`. A dead player's health stays `0` until they respawn; use [`HealPlayer`](/lua/server/functions/healplayer/) or [`SpawnPlayer`](/lua/server/functions/spawnplayer/) to bring one back. ## Syntax ```lua SetPlayerHealth(pid, health) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `health` | number | the new health | ## Returns `boolean` - `false` when not connected ## Example ```lua -- /slap : a nudge SetPlayerHealth(target, GetPlayerHealth(target) - 10) ``` ## See also [GetPlayerHealth](/lua/server/functions/getplayerhealth/) · [HealPlayer](/lua/server/functions/healplayer/) · [OnPlayerDeath](/lua/server/callbacks/onplayerdeath/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # SetPlayerNameplate > The label over the player's body on every other screen. The label over the player's body on every other screen. By default the label is the player's name; this replaces it - a rank, a team tag, a title. `""` puts the name back. At most 48 characters. The label keeps its colour ([`SetPlayerColour`](/lua/server/functions/setplayercolour/)) and hides behind walls like the name does. ## Syntax ```lua SetPlayerNameplate(pid, text) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `text` | string | the label; `""` = the name again | ## Returns `boolean` - `false` when not connected ## Example ```lua SetPlayerNameplate(pid, "[GUARD] " .. GetPlayerName(pid)) ``` ## See also [GetPlayerNameplate](/lua/server/functions/getplayernameplate/) · [SetPlayerColour](/lua/server/functions/setplayercolour/) · [SetPlayerTeam](/lua/server/functions/setplayerteam/) · the [Players](/lua/server/#players) group of the index # SetPlayerPos > Moves the player's game to a point - a teleport. Moves the player's game to a point - a teleport. The client puts the player there on the next frame and the server's record follows; reports from before the move are dropped, so honest clients never trip the speed check. `z` below `0` puts the player on the terrain at `x, y`. A mounted player is moved with the horse. Without `yaw` the player keeps their heading. ## Syntax ```lua SetPlayerPos(pid, x, y, z [, yaw]) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `x` | number | metres | | `y` | number | metres | | `z` | number | metres; below `0` = on the terrain | | `yaw` | number | degrees to face *(optional)* | ## Returns `boolean` - `false` when not connected ## Example ```lua -- /goto : next to another player, facing the same way local tx, ty, tz = GetPlayerPos(target) SetPlayerPos(pid, tx + 1.5, ty, tz, GetPlayerYaw(target)) ``` ## See also [GetPlayerPos](/lua/server/functions/getplayerpos/) · [SpawnPlayer](/lua/server/functions/spawnplayer/) · [SetEntityPos](/lua/server/functions/setentitypos/) · the [Players](/lua/server/#players) group of the index # SetPlayerSkill > Raises a skill of the player's character to a level. Raises a skill of the player's character to a level. `skill` is one of the game's skill names - `marksmanship`, `fencing`, `weapon_sword`, `heavy_weapons`, `horse_riding`, `stealth` ... ([Stats and skills](/reference/stats-and-skills/)) - and `level` `1` .. `30`. Kept on the record, re-applied at every spawn, never lowered; an unknown name does nothing. ## Syntax ```lua SetPlayerSkill(pid, skill, level) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `skill` | string | the skill's name | | `level` | number | `1` .. `30` | ## Returns `boolean` - `false` for an empty name, a level outside `1`..`30` or a player not connected ## Example ```lua SetPlayerSkill(pid, "weapon_sword", 15) ``` ## See also [GetPlayerSkill](/lua/server/functions/getplayerskill/) · [SetPlayerStat](/lua/server/functions/setplayerstat/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # SetPlayerStamina > Sets the player's stamina. Sets the player's stamina. Clamped to `0 .. max`. A swing thrown with less stamina than it costs lands weakly - a mode may tire a player on purpose. ## Syntax ```lua SetPlayerStamina(pid, stamina) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `stamina` | number | the new stamina | ## Returns `boolean` - `false` when not connected ## Example ```lua -- both duelists start fresh SetPlayerStamina(a, GetPlayerMaxStamina(a)) SetPlayerStamina(b, GetPlayerMaxStamina(b)) ``` ## See also [GetPlayerStamina](/lua/server/functions/getplayerstamina/) · [HealPlayer](/lua/server/functions/healplayer/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # SetPlayerStat > Raises a core stat of the player's character to a level. Raises a core stat of the player's character to a level. `stat` is one of the game's core stats - `strength`, `agility`, `vitality`, `speech` ([Stats and skills](/reference/stats-and-skills/)) - and `level` `1` .. `30`. The level is kept on the player's record for the session and re-applied at every spawn; the game **never lowers** a level, so this only raises. Every player starts as the level's character, level 5 everywhere, and `[spawn] stat_level` raises the four core stats for everyone at the spawn; a hunting bow needs strength 13 to be held drawn. The name is not checked against the game's list - a misspelt one is recorded and does nothing. ## Syntax ```lua SetPlayerStat(pid, stat, level) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `stat` | string | the stat's name | | `level` | number | `1` .. `30` | ## Returns `boolean` - `false` for an empty name, a level outside `1`..`30` or a player not connected ## Example ```lua -- archers get the strength for a war bow SetPlayerStat(pid, "strength", 20) SetPlayerSkill(pid, "marksmanship", 18) ``` ## See also [GetPlayerStat](/lua/server/functions/getplayerstat/) · [SetPlayerSkill](/lua/server/functions/setplayerskill/) · the [Vitals, stats and skills](/lua/server/#vitals-stats-and-skills) group of the index # SetPlayerState > Sets a key of a player's bag, read by every client. Sets a key of a player's bag, read by every client. Every client has every player's bag from its join on - `KcdMp.state.player[pid][key]`; the client's own pid is `KcdMp.player_id`. Gone with the player's session. ## Syntax ```lua SetPlayerState(pid, key, value) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `key` | string | 1-48 characters | | `value` | string \| number \| boolean \| nil | kept as a string; `nil` removes the key | ## Returns `boolean` - `false` when not connected or out of bounds ## Example ```lua SetPlayerTeam(pid, 2) SetPlayerState(pid, "team", 2) -- the client scripts colour the label by it ``` ## See also [GetPlayerState](/lua/server/functions/getplayerstate/) · [GetPlayerStates](/lua/server/functions/getplayerstates/) · [SetGlobalState](/lua/server/functions/setglobalstate/) · [SetPlayerData](/lua/server/functions/setplayerdata/) · the [State bags](/lua/server/#state-bags) group of the index # SetPlayerTeam > Puts the player in a team - teammates cannot hurt each other. Puts the player in a team - teammates cannot hurt each other. Any number is a team; `NO_TEAM` (`-1`) is none. **A hit between two players of one team is refused** before [`OnPlayerDamage`](/lua/server/callbacks/onplayerdamage/) and starts no fight. Nothing else is implied - no colour, no label, no spawn: those are the mode's to set alongside. A mode that wants friendly fire back writes its rule in `OnPlayerDamage` and leaves teams unset. ## Syntax ```lua SetPlayerTeam(pid, team) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `team` | number | the team; `NO_TEAM` (`-1`) = none | ## Returns `boolean` - `false` when not connected ## Example ```lua local function join(pid, team) SetPlayerTeam(pid, team) SetPlayerColour(pid, team == 1 and 0xFF4040FF or 0x4080FFFF) SetPlayerState(pid, "team", team) -- the client scripts read KcdMp.state.player[pid].team end ``` ## See also [GetPlayerTeam](/lua/server/functions/getplayerteam/) · [SetPlayerColour](/lua/server/functions/setplayercolour/) · [OnPlayerDamage](/lua/server/callbacks/onplayerdamage/) · [SetPlayerState](/lua/server/functions/setplayerstate/) · the [Players](/lua/server/#players) group of the index # SetPlayerVirtualWorld > Moves the player into another virtual world. Moves the player into another virtual world. From the next snapshot on the player sees, and is seen by, the players and entities of `world` only; the others part with them as if they had left and meet them again when they come back. Their mount comes along; a loose horse they controlled stays behind for whoever is nearest. Chat, the roster, the scoreboard, doors and containers stay global. Fights and hits stay inside a world. The client never learns its world - nothing changes on the player's screen but who is around. Instanced duels, private lobbies, a hidden staging area for the next round. ## Syntax ```lua SetPlayerVirtualWorld(pid, world) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `world` | number | the world; `0` = the shared one | ## Returns `boolean` - `false` when not connected ## Example ```lua -- a private arena per duel: the two see nobody else local function startDuel(a, b) duelWorld = duelWorld + 1 SetPlayerVirtualWorld(a, duelWorld) SetPlayerVirtualWorld(b, duelWorld) end local function endDuel(a, b) SetPlayerVirtualWorld(a, 0) SetPlayerVirtualWorld(b, 0) end ``` ## See also [GetPlayerVirtualWorld](/lua/server/functions/getplayervirtualworld/) · [SetEntityVirtualWorld](/lua/server/functions/setentityvirtualworld/) · [CreateHorse](/lua/server/functions/createhorse/) · the [Players](/lua/server/#players) group of the index # SetRain > Forces rain on every client, or hands the rain back to the weather. Forces rain on every client, or hands the rain back to the weather. The rain is a lever on top of the weather profile: the profile sets the clouds, the fog, the light and its own rain probability; this forces the amount. `-1` lets the profile decide again. `/rain` is the built-in. ## Syntax ```lua SetRain(intensity) ``` | Parameter | Type | | |---|---|---| | `intensity` | number | `0` .. `1`; `-1` = off, the weather decides | ## Returns nothing ## Example ```lua SetWeather("storm", 5) SetRain(1) ``` ## See also [GetRain](/lua/server/functions/getrain/) · [SetWeather](/lua/server/functions/setweather/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # SetSavedData > Saves a value on the player's name - it is there on their next visit. Saves a value on the player's name - it is there on their next visit. Strings (a number is converted); `nil` removes the key. Written into the player's record with the visits and the position; for a registered name, only when its owner is logged in. ## Syntax ```lua SetSavedData(pid, key, value) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `key` | string | the key | | `value` | string \| nil | the value; `nil` removes the key | ## Returns `boolean` - `false` when not connected ## Example ```lua function OnPlayerDeath(pid, attacker) if attacker >= 0 then SetSavedData(attacker, "wins", (tonumber(GetSavedData(attacker, "wins")) or 0) + 1) end end ``` ## See also [GetSavedData](/lua/server/functions/getsaveddata/) · [GetSavedPlayer](/lua/server/functions/getsavedplayer/) · [SetServerData](/lua/server/functions/setserverdata/) · the [Storage and persistence](/lua/server/#storage-and-persistence) group of the index # SetServerData > Saves a value in the server-wide store (data/server.json). Saves a value in the server-wide store (data/server.json). One key/value store for the mode, persisted beside the player records; strings, `nil` removes the key. A record for the whole server: rounds played, a leaderboard, the last map rotation. ## Syntax ```lua SetServerData(key, value) ``` | Parameter | Type | | |---|---|---| | `key` | string | the key | | `value` | string \| nil | the value; `nil` removes the key | ## Returns nothing ## Example ```lua SetServerData("rounds_played", tostring(rounds)) ``` ## See also [GetServerData](/lua/server/functions/getserverdata/) · [SetSavedData](/lua/server/functions/setsaveddata/) · the [Storage and persistence](/lua/server/#storage-and-persistence) group of the index # SetSpawnInfo > Where and as what the player's next spawn happens. Where and as what the player's next spawn happens. Sets the point and the outfit for the next [`SpawnPlayer`](/lua/server/functions/spawnplayer/) or the spawn that follows [`OnPlayerRequestSpawn`](/lua/server/callbacks/onplayerrequestspawn/). The presets are GUIDs from the game's tables - [clothing presets](/reference/clothing-presets/) and [weapon presets](/reference/weapon-presets/); `""` or `nil` keeps the server's `[spawn]` defaults. `appearance` is the soul whose face and body the **other** players see on this player's body - a soul of the `NPC` or `NPC_Female` archetype from [the souls](/reference/souls/) by name, id or GUID; `""` picks one from the server's `[spawn] appearances` pool by the player's name, so a player looks the same every visit. The point is remembered until the next `SetSpawnInfo`; respawns after a death use it too. ## Syntax ```lua SetSpawnInfo(pid, x, y, z, yaw [, clothingPreset, weaponPreset, appearance]) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `x` | number | metres | | `y` | number | metres | | `z` | number | metres; below `0` = on the terrain | | `yaw` | number | degrees to face (`0` without) | | `clothingPreset` | string | a clothing preset GUID; `""` = the server default *(optional)* | | `weaponPreset` | string | a weapon preset GUID; `""` = the server default *(optional)* | | `appearance` | string | the soul whose face the others see (name, id or GUID); `""` = the server's pool *(optional)* | ## Returns `boolean` - `false` when not connected ## Example ```lua local RED_TEAM_OUTFIT = "52169773-0c2b-407a-a123-8b403e224718" -- UC_HenryTrosky, a clothing preset GUID local LONGSWORD = "00928214-01bb-452f-b322-724cffe6ebdc" -- longsword_5_01, a weapon preset GUID function OnPlayerRequestSpawn(pid) local x, y, z, yaw = GetRandomSpawnPoint("red") SetSpawnInfo(pid, x, y, z, yaw, RED_TEAM_OUTFIT, LONGSWORD, "test_cuman_ai") return true end ``` ## See also [SpawnPlayer](/lua/server/functions/spawnplayer/) · [OnPlayerRequestSpawn](/lua/server/callbacks/onplayerrequestspawn/) · [GetDefaultSpawn](/lua/server/functions/getdefaultspawn/) · [AddSpawnPoint](/lua/server/functions/addspawnpoint/) · the [Players](/lua/server/#players) group of the index # SetTimer > Calls a function after a delay, once or repeatedly. Calls a function after a delay, once or repeatedly. The function runs on the simulation thread in the tick the timer falls due - the same place a callback runs, so it may call anything a callback may. A repeating timer runs every `ms` milliseconds until [`KillTimer`](/lua/server/functions/killtimer/); a one-shot timer runs once and is gone. Timers belong to the mode: a reload discards them. The shortest interval is one tick (about 33 ms). ## Syntax ```lua SetTimer(fn, ms [, repeating]) ``` | Parameter | Type | | |---|---|---| | `fn` | function | the function to call (no arguments) | | `ms` | number | the delay, and the interval of a repeating timer, in milliseconds | | `repeating` | boolean | `true` repeats every `ms`; `false` or nothing fires once *(optional)* | ## Returns `number` - the timer's id, for `KillTimer` ## Example ```lua -- a countdown: "3", "2", "1", "Fight!" local left = 3 local timer timer = SetTimer(function() if left > 0 then GameTextForAll(tostring(left), 900) left = left - 1 else KillTimer(timer) GameTextForAll("Fight!", 1500) end end, 1000, true) -- once, in twenty seconds SetTimer(function() DestroyEntity(corpse) end, 20000) ``` ## See also [KillTimer](/lua/server/functions/killtimer/) · [OnTick](/lua/server/callbacks/ontick/) · [GetServerTime](/lua/server/functions/getservertime/) · the [Server and timers](/lua/server/#server-and-timers) group of the index # SetTimeRatio > Sets how fast the world clock runs. Sets how fast the world clock runs. ## Syntax ```lua SetTimeRatio(ratio) ``` | Parameter | Type | | |---|---|---| | `ratio` | number | game seconds per real second; `15` = the game's own pace, `0` = frozen | ## Returns nothing ## Example ```lua SetTimeRatio(0) -- high noon for ever SetTimeRatio(60) -- a day in 24 minutes ``` ## See also [GetTimeRatio](/lua/server/functions/gettimeratio/) · [SetWorldTime](/lua/server/functions/setworldtime/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # SetWeather > Changes the sky for everyone - by a preset name or a level profile. Changes the sky for everyone - by a preset name or a level profile. A **preset** is a friendly name for one of the level's time-of-day profiles: `clear` (or `sunny`), `fair`, `cloudy`, `overcast`, `showers`, `drizzle` (or `fog`), `storm`, `dry_storm` ([`GetWeatherPresets`](/lua/server/functions/getweatherpresets/) maps them; [Weather](/reference/weather/) lists the profiles). A profile name passes through as it is. Each client blends the new sky in over `blendSeconds` (`[world] weather_blend`, 10 s, without them). `""` leaves every client's sky as it is. The `/weather` built-in is the same call. ## Syntax ```lua SetWeather(presetOrProfile [, blendSeconds]) ``` | Parameter | Type | | |---|---|---| | `presetOrProfile` | string | a preset or a profile name; `""` = leave the skies alone | | `blendSeconds` | number | seconds the change blends in over (`[world] weather_blend`) *(optional)* | ## Returns `boolean` - `false` for a name that is neither a preset nor a profile ## Example ```lua -- the storm rolls in over the last minute of the round SetWeather("storm", 60) SetTimer(function() SetWeather("clear", 20) end, 90000) ``` ## See also [GetWeather](/lua/server/functions/getweather/) · [GetWeatherPresets](/lua/server/functions/getweatherpresets/) · [SetRain](/lua/server/functions/setrain/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # SetWorldTime > Sets the world clock for everyone. Sets the world clock for everyone. Every client's calendar follows. The game's own calendar only moves **forward**: a jump backwards is applied as a jump to the same time the next day. ## Syntax ```lua SetWorldTime(hours) ``` | Parameter | Type | | |---|---|---| | `hours` | number | hours since midnight, `0` .. `24` (`13.5` = 13:30) | ## Returns nothing ## Example ```lua -- /time hh:mm local h, m = args:match("^(%d+):(%d+)$") if h then SetWorldTime(tonumber(h) + tonumber(m) / 60) end ``` ## See also [GetWorldTime](/lua/server/functions/getworldtime/) · [SetTimeRatio](/lua/server/functions/settimeratio/) · [FormatWorldTime](/lua/server/functions/formatworldtime/) · the [The world - clock, weather, terrain, the navmesh, the geometry](/lua/server/#the-world---clock-weather-terrain-the-navmesh-the-geometry) group of the index # SetZoneData > Stores a value on a zone, private to the server. Stores a value on a zone, private to the server. Any Lua value; gone with the zone. The mode's way to mark what a zone is for. ## Syntax ```lua SetZoneData(id, key, value) ``` | Parameter | Type | | |---|---|---| | `id` | number | the zone | | `key` | string | the key | | `value` | any | the value; `nil` removes the key | ## Returns `boolean` - `false` when there is no such zone ## Example ```lua local safe = CreateCircleZone(x, y, 20) SetZoneData(safe, "safe", true) ``` ## See also [GetZoneData](/lua/server/functions/getzonedata/) · [SetPlayerData](/lua/server/functions/setplayerdata/) · [SetEntityData](/lua/server/functions/setentitydata/) · the [Zones](/lua/server/#zones) group of the index # ShowHudText > Shows a HUD text on one player's screen. Shows a HUD text on one player's screen. Usually called from [`OnPlayerSpawn`](/lua/server/callbacks/onplayerspawn/) so a late joiner gets the mode's elements too - [`ShowHudTextForAll`](/lua/server/functions/showhudtextforall/) only reaches the players connected at the time. ## Syntax ```lua ShowHudText(id, pid) ``` | Parameter | Type | | |---|---|---| | `id` | number | the element | | `pid` | number | the player | ## Returns `boolean` - `false` when the element or the player does not exist ## Example ```lua function OnPlayerSpawn(pid) ShowHudText(clock, pid) ShowHudText(score, pid) end ``` ## See also [HideHudText](/lua/server/functions/hidehudtext/) · [ShowHudTextForAll](/lua/server/functions/showhudtextforall/) · [IsHudTextShown](/lua/server/functions/ishudtextshown/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # ShowHudTextForAll > Shows a HUD text to everyone connected now. Shows a HUD text to everyone connected now. ## Syntax ```lua ShowHudTextForAll(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the element | ## Returns `boolean` ## Example ```lua ShowHudTextForAll(banner) ``` ## See also [ShowHudText](/lua/server/functions/showhudtext/) · [HideHudTextForAll](/lua/server/functions/hidehudtextforall/) · the [GameText and HUD](/lua/server/#gametext-and-hud) group of the index # ShowPartyFrames > Whether this player sees the party frames. Whether this player sees the party frames. `[party] frames` is the default for everyone; a mode that draws its own frames from a client script (`KcdMp.party`, `KcdMp.on_party_change` on the client) hides the server's for its players. ## Syntax ```lua ShowPartyFrames(pid, shown) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `shown` | boolean | the frames on or off | ## Returns `boolean` - `false` when not connected ## Example ```lua ShowPartyFrames(pid, false) -- the client script draws its own ``` ## See also [SetPartyName](/lua/server/functions/setpartyname/) · the [Parties](/lua/server/#parties) group of the index # SpawnDecal > Puts a decal of a material on whatever is at a point. Puts a decal of a material on whatever is at a point. A mark on the ground under a spawn, a stain on a wall: `material` is one of the game's decal materials ([the decal materials](/reference/decal-materials/): `Materials/decals/decal_blood_a`, `decal_burned_ash`, `chalk_cross` ...), `size` metres across, `seconds` how long it stays (`0` = the engine's own default). `normal` is which way the decal faces - `{x, y, z}` or three numbers; a floor (`0, 0, 1`) without it. The same reach and return as [`SpawnEffect`](/lua/server/functions/spawneffect/). ## Syntax ```lua SpawnDecal(material, x, y, z [, size, seconds, normal, world]) ``` | Parameter | Type | | |---|---|---| | `material` | string | the decal material | | `x` | number | metres | | `y` | number | metres | | `z` | number | metres | | `size` | number | metres across (`1`) *(optional)* | | `seconds` | number | how long it stays; `0` = the engine's default *(optional)* | | `normal` | table \| number | which way it faces as `{x=, y=, z=}` (or three numbers `nx, ny, nz`); a floor without *(optional)* | | `world` | number | the virtual world (`0`) *(optional)* | ## Returns `number` - how many players got it ## Example ```lua -- a mark on the arena floor where the loser fell local x, y, z = GetPlayerPos(loser) SpawnDecal("Materials/decals/decal_blood_a", x, y, z, 1.5, 120) ``` ## See also [SpawnEffect](/lua/server/functions/spawneffect/) · [PlaySound](/lua/server/functions/playsound/) · the [Effects and sounds](/lua/server/#effects-and-sounds) group of the index # SpawnEffect > Plays one of the game's particle effects at a point for everyone nearby. Plays one of the game's particle effects at a point for everyone nearby. `name` is a particle effect of the game's libraries by its full name - `WH_Particels.smokes.smithery`, `professions.blacksmith.forge_fire`, `cinematics.fires.fire_big_a` ... ([the particle effects](/reference/particle-effects/) list all 2,600). `scale` `1` plays it as authored. `dir` is the effect's **up** - `{x, y, z}` or three numbers; straight up (`0, 0, 1`) without it. A looping effect plays until the player's level unloads. `world` is the virtual world (`0`, the shared one, without it). ## Syntax ```lua SpawnEffect(name, x, y, z [, scale, dir, world]) ``` | Parameter | Type | | |---|---|---| | `name` | string | the particle effect's full name | | `x` | number | metres | | `y` | number | metres | | `z` | number | metres | | `scale` | number | `1` = as authored *(optional)* | | `dir` | table \| number | the effect's up as `{x=, y=, z=}` (or three numbers `dx, dy, dz` in its place); straight up without *(optional)* | | `world` | number | the virtual world (`0`) *(optional)* | ## Returns `number` - how many players got it; `0` for an empty name or nobody in range ## Example ```lua -- the smithy's smoke two metres ahead of the player local x, y, z = GetPlayerPos(pid) local r = math.rad(GetPlayerYaw(pid)) SpawnEffect("WH_Particels.smokes.smithery", x - math.sin(r) * 2, y + math.cos(r) * 2, z) -- a big fire, half size, in a private arena world SpawnEffect("cinematics.fires.fire_big_a", fx, fy, fz, 0.5, {x = 0, y = 0, z = 1}, arenaWorld) ``` ## See also [SpawnDecal](/lua/server/functions/spawndecal/) · [PlaySound](/lua/server/functions/playsound/) · [CreateProp](/lua/server/functions/createprop/) · the [Effects and sounds](/lua/server/#effects-and-sounds) group of the index # SpawnPlayer > Spawns - or respawns - the player at their SetSpawnInfo point. Spawns - or respawns - the player at their SetSpawnInfo point. Puts a player whose level is loaded into the world at the point [`SetSpawnInfo`](/lua/server/functions/setspawninfo/) set (the server's default without one), or moves and re-outfits one who already is; [`OnPlayerSpawn`](/lua/server/callbacks/onplayerspawn/) follows. The way to release a player held by [`OnPlayerRequestSpawn`](/lua/server/callbacks/onplayerrequestspawn/) returning `false`, and to respawn the dead when `[combat] respawn_seconds` is `0`. A spawn heals: full health and stamina, injuries and the server's buffs gone. ## Syntax ```lua SpawnPlayer(pid) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | ## Returns `boolean` - `false` when not connected ## Example ```lua -- a lobby: hold everyone, release them when the round starts function OnPlayerRequestSpawn(pid) waiting[#waiting + 1] = pid return false end local function startRound() for _, pid in ipairs(waiting) do SetSpawnInfo(pid, GetRandomSpawnPoint("arena")) SpawnPlayer(pid) end waiting = {} end ``` ## See also [SetSpawnInfo](/lua/server/functions/setspawninfo/) · [OnPlayerRequestSpawn](/lua/server/callbacks/onplayerrequestspawn/) · [OnPlayerSpawn](/lua/server/callbacks/onplayerspawn/) · [OnPlayerDeath](/lua/server/callbacks/onplayerdeath/) · the [Players](/lua/server/#players) group of the index # sscanf > The arguments of a command as typed values - a player, a number, a word, the rest of the line - in one call. The arguments of a command as typed values - a player, a number, a word, the rest of the line - in one call. The name is SA-MP's on purpose: the same job, one letter per argument. `args` is the string [`OnPlayerCommandText`](/lua/server/callbacks/onplayercommandtext/) hands you; `format` is one letter per argument, in order: | letter | the argument | what you get | |---|---|---| | `u` | a player: a pid or a name (or a fragment of one), as [`GetPlayerId`](/lua/server/functions/getplayerid/) reads it | the pid | | `d` | a whole number (`-3`, `50`) | a number | | `f` | a number (`0.5`, `12`) | a number | | `s` | one word - or a `"quoted string"` taken whole | a string | | `z` | the rest of the line, from here to the end | a string | A `?` after a letter makes that argument optional: `nil` when it is not there. Words are split on spaces; whatever follows the last letter is ignored. It returns the values in the format's order. When a required argument is missing or does not read - a number that is not one, a player nobody is called - it returns **`false` and the reason** (`"argument 2 (abc) is not a whole number"`, `"no player called xyz"`), ready for a usage line: check the first value against `false`, not against `nil`, when the first letter is optional. ## Syntax ```lua sscanf(args, format) ``` | Parameter | Type | | |---|---|---| | `args` | string | the command's arguments as [`OnPlayerCommandText`](/lua/server/callbacks/onplayercommandtext/) gives them | | `format` | string | one letter per argument (`u d f s z`), a `?` after a letter for an optional one | ## Returns `any ...` - the values in order, or `false, reason` ## Example ```lua -- /pay local target, amount = sscanf(args, "ud") if target == false then return SendClientMessage(pid, COLOUR_RED, "usage: /pay ") end -- /hurt [player] [amount]: both optional, the caller and 30 by default local target, amount = sscanf(args, "u?d?") if target == false then return SendClientMessage(pid, COLOUR_RED, amount) end -- the reason target, amount = target or pid, amount or 30 -- /say : a word, then the rest of the line whole local channel, text = sscanf(args, "sz") -- /arena [yaw] local x, y, z, yaw = sscanf(args, "ffff?") ``` ## See also [OnPlayerCommandText](/lua/server/callbacks/onplayercommandtext/) · [GetPlayerId](/lua/server/functions/getplayerid/) · [SendClientMessage](/lua/server/functions/sendclientmessage/) · the [Chat and commands](/lua/server/#chat-and-commands) group of the index # StartFight > Puts two players in a fight so their games can lock on to each other. Puts two players in a fight so their games can lock on to each other. From here either one's game may pick the other's body as the opponent - the direction indicators, the combat stance. The server starts a fight by itself when a swing reaches a body and on `/fight `; this is the mode's way (`reason` `"mode"`). On a fight that is already running it **restarts the `[combat] fight_timeout` clock** - a duel mode calls it every second so two circling duelists never lose the lock. `false` when pvp is off, one of the two is dead or not in the world, or they are in different virtual worlds. Teammates can be put in a fight, but their hits stay refused. ## Syntax ```lua StartFight(a, b) ``` | Parameter | Type | | |---|---|---| | `a` | number | one player | | `b` | number | the other | ## Returns `boolean` - `true` when the two fight now ## Example ```lua -- the arena keeps the duel alive while it lasts SetTimer(function() if duel and duel.live then StartFight(duel.a, duel.b) end end, 1000, true) ``` ## See also [EndFight](/lua/server/functions/endfight/) · [AreFighting](/lua/server/functions/arefighting/) · [GetPlayerOpponents](/lua/server/functions/getplayeropponents/) · [OnFightStart](/lua/server/callbacks/onfightstart/) · the [Combat](/lua/server/#combat) group of the index # StopActor > Stops an actor where it is. Stops an actor where it is. No `OnActorArrive`. Also ends a chase started by [`SetActorHostile`](/lua/server/functions/setactorhostile/) only as far as the walk goes - the fight of record stays until its timeout. ## Syntax ```lua StopActor(id) ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | ## Returns `boolean` - `false` for anything but an actor ## Example ```lua StopActor(guard) SetActorAnim(guard, "sit") ``` ## See also [MoveActor](/lua/server/functions/moveactor/) · [IsActorMoving](/lua/server/functions/isactormoving/) · the [NPC actors](/lua/server/#npc-actors) group of the index # TogglePlayerControllable > Holds or releases the player's keyboard. Holds or releases the player's keyboard. `false` freezes the player where they stand: the keyboard does nothing on their client, the mouse still looks around, **T** and **Enter** still open the chat. `true` gives the keyboard back. The server's own login hold uses the same lever for a registered name until its `/login`. ## Syntax ```lua TogglePlayerControllable(pid, controllable) ``` | Parameter | Type | | |---|---|---| | `pid` | number | the player | | `controllable` | boolean | `false` holds, `true` releases | ## Returns `boolean` - `false` when not connected ## Example ```lua -- freeze everyone for the countdown for _, pid in ipairs(GetPlayers()) do TogglePlayerControllable(pid, false) end SetTimer(function() for _, pid in ipairs(GetPlayers()) do TogglePlayerControllable(pid, true) end GameTextForAll("Go!", 1500) end, 3000) ``` ## See also [IsPlayerControllable](/lua/server/functions/isplayercontrollable/) · [SetPlayerVirtualWorld](/lua/server/functions/setplayervirtualworld/) · the [Players](/lua/server/#players) group of the index # TurnActor > Turns a standing actor to face a direction. Turns a standing actor to face a direction. ## Syntax ```lua TurnActor(id, yaw) ``` | Parameter | Type | | |---|---|---| | `id` | number | the actor | | `yaw` | number | degrees; `0` = facing +Y, counter-clockwise | ## Returns `boolean` - `false` for anything but an actor ## Example ```lua -- face the player local px, py = GetPlayerPos(pid) local ax, ay = GetEntityPos(guard) TurnActor(guard, math.deg(math.atan(-(px - ax), py - ay)) % 360) ``` ## See also [MoveActor](/lua/server/functions/moveactor/) · [StopActor](/lua/server/functions/stopactor/) · the [NPC actors](/lua/server/#npc-actors) group of the index # Unban > Lifts every ban on a name or an address. Lifts every ban on a name or an address. ## Syntax ```lua Unban(nameOrAddress) ``` | Parameter | Type | | |---|---|---| | `nameOrAddress` | string | a name or an address | ## Returns `boolean` - `true` when there was one ## Example ```lua if Unban(args) then SendClientMessage(pid, COLOUR_SERVER, args .. " may join again") end ``` ## See also [Ban](/lua/server/functions/ban/) · [IsBanned](/lua/server/functions/isbanned/) · the [Accounts, admins, bans and the audit](/lua/server/#accounts-admins-bans-and-the-audit) group of the index # Getting started > What a client script is, how the server sends it to the players, what of the game's own Lua the sandbox gives it, its limits and where its output goes. A **client script** is a Lua file that runs inside a player's game, in the game's own Lua state, next to the KCD:MP client. It is the game mode's half on the player's screen: a marker in the world, a sound, a bit of UI, a value read from the game that the server cannot see. A game mode works without one - the server's chat lines, GameTexts and HUD texts need nothing on the client - and most modes need none. A mode that wants more puts its client files next to itself, and the server sends them to every player who joins. ## How a script reaches the player The server sends it. A mode with a client half lives in a folder of its own, the way a C# plugin does, with the client files in `client/` next to it: ``` gamemodes/arena/arena.lua the server half - [gamemode] script names it gamemodes/arena/client/*.lua the client half - sent to every joining player, run in name order ``` Nothing is asked of the players: the files arrive with the join, before the roster and the mode's first events, and run once the level is ready - so a handler registered at the top of a file sees the event the mode sends from `OnPlayerSpawn`. The launcher and the game say so when a server does this ("runs 2 client scripts in your game, sandboxed to the game"). `[client] scripts` in the server's configuration names another folder (a mode in a single file, or the built-in one, has no `client/` of its own). The limits: 64 files, 256 KB each, 2 MB together. `/reload` on the server sends the folder again - the running scripts are dropped first (their handlers, their timers), then the new ones run; the `watch` setting does the same by itself when a client file changes on disk. A script runs once, when it arrives; what it defines stays for the session and is gone with the game or replaced by the next `/reload`. Several files of one folder share one environment: a function the first file defines, the second can call. For development, a file on the player's own disk can still be run by hand: [`KcdMp_exec`](/lua/client/console/kcdmp_exec/) in the **F9** window, or `-KcdMp_exec ` in the launcher's *Game arguments*. Such a file has the game's whole Lua, no sandbox - it is the player's own. ## What the script has A script the server sent runs in a **sandbox**: the boundary is the game. It has everything it needs to draw, read the world and talk to the server, and nothing that reaches the player's computer beyond the game - no files, no other programs, no browser, no console, no saves. What is there is listed below; a name that is not listed is not there (`nil`), and a script that wants one more should say so - the list grows on request. ### The KcdMp table The API on this side, every member on [its own page](/lua/client/): - [script events](/lua/client/#script-events) to and from the game mode - `KcdMp.on_event`, `KcdMp.send_event`; - [the state bags](/lua/client/#state-bags) the mode set - `KcdMp.state`, `KcdMp.on_state`, `KcdMp.player_id`; - [helpers](/lua/client/#helpers) and [console commands](/lua/client/#console-commands). ### The game's own Lua, as the sandbox gives it The script runs in the game's Lua state, in an environment of its own. What it holds: | | | |---|---| | the base library | `assert`, `error`, `ipairs`, `next`, `pairs`, `pcall`, `select`, `tonumber`, `tostring`, `type`, `unpack`, `xpcall`, `rawequal`, `rawget`, `rawset`, `setmetatable`, `getmetatable` (not on strings), `collectgarbage`, `loadstring` (its chunks run in the sandbox too), `print` (into the client log) | | `string`, `math`, `table`, `coroutine` | copies of the game's - a script may change its own copy, not the game's | | `os.clock()`, `os.time()` | the two the game has | | `System` | the log (`LogAlways`, `Log`, `Warning`, `Error`), the drawing for this frame (`DrawLabel(pos, size, text, r, g, b, a)`, `DrawLine(a, b, r, g, b, a)`, `DrawText`, `Draw2DLine`), the entities (`GetEntity`, `GetEntityByName`, `GetEntities`, `GetEntitiesByClass`, `GetEntitiesInSphere`, `GetNearestEntityByClass`, `GetPhysicalEntitiesInBox`, `SpawnEntity`, `RemoveEntity` ...), the world (`RayTraceCheck`, `RayWorldIntersection`, `GetTerrainElevation({x=, y=, z=})`, `IsPointIndoors`, `IsPointVisible`, `ProjectToScreen`, the view camera's `GetViewCameraPos` / `Dir` / `Fov`, `GetViewport`), the clocks (`GetCurrTime`, `GetFrameTime`, `GetFrameID`, `GetLocalOSTime`), the look of the world (`SetPostProcessFxParam`, `SetWind`, the ambient colour, the sky highlight, `ActivateLight`) | | `Script.SetTimer(ms, fn)`, `Script.SetTimerForFunction(ms, fn)`, `Script.KillTimer(id)` | the game's own timers - one shot; call again for a loop. A `/reload` kills the ones a script left running | | `Game` | the game's own table without its saves, loads and the recording | | `Calendar` | the game's clock - `GetWorldHourOfDay()`, `GetWorldTime()` (game seconds since day zero) | | `UIAction` | the game's own UI elements from Lua - `ShowElement`, `HideElement`, `CallFunction`, `SetVariable`, the listeners: the road to UI in the game's own look | | `Particle` | `SpawnEffect`, `CreateDecal` | | `player` | the local player entity: `player:GetWorldPos()`, `player.soul` (`GetStatLevel`, `GetSkillLevel`, `HasPerk` ...), `player.actor`, `player.human` (`IsMounted`, `IsWeaponDrawn` ...), `player.inventory` (`GetInventoryTable`, `HasItem` ...) | | `KcdMp` | [the API](/lua/client/) - the events, the state bags, the helpers | What is not there, on purpose: `dofile`, `loadfile`, `require` (any file on the disk), `io`, `package`, `debug`, `getfenv` / `setfenv`, `System.ExecuteCommand` and the console, `System.BrowseURL`, `System.Quit`, `System.LoadTextFile`, the saves, `Script.LoadScript`. The entity tables (`player`, what `System.GetEntity` returns) are the game's own with every function of theirs - its scripts (`Scripts.pak`) show the names and signatures, and a list of them is planned for this reference. Two warnings: inside the game the script has the game's power over the player's own client, so it can still break their game; and a script that changes the player's own health, items or position is cheating in the server's eyes - the server judges what the client reports, and the [inventory audit](/lua/server/callbacks/onplayerauditviolation/) is one of the judges. Values, combat, health and items stay the server's: a client script gets no say in them. ### Not an API The `KcdMp` table also holds the client's own machinery - `KcdMp.remote` (the other players' bodies by net id), `KcdMp.labels`, the locomotion and animation helpers. They change without notice; a script that reads them should expect to be fixed after an update. ## A first script The marker round trip: the mode sends a point, the script draws a label there until the player is close, then tells the mode. The server folder ships it whole as the **marker** example mode (`gamemodes/marker/marker.lua` with `client/marker.lua`: a checkpoint run around the spawn, laps counted by the server). ```lua -- gamemodes/marker/client/marker.lua local marker -- {x=, y=, z=} or nil KcdMp.on_event("marker", function(payload) local x, y, z = payload:match("^([^,]+),([^,]+),(.+)$") marker = {x = tonumber(x), y = tonumber(y), z = tonumber(z)} print("marker at " .. payload) end) -- the drawing functions show for one frame: draw from the frame hook, not a timer KcdMp.on_frame(function() if marker and player then local p = player:GetWorldPos() local d = math.sqrt((p.x - marker.x) ^ 2 + (p.y - marker.y) ^ 2) System.DrawLabel({x = marker.x, y = marker.y, z = marker.z + 1.5}, 1.4, string.format("%.0f m", d), 1, 0.85, 0.3, 1) if d < 2 then KcdMp.send_event("marker_reached", "") marker = nil end end end) ``` ```lua -- gamemodes/marker/marker.lua, the game mode's side function OnPlayerSpawn(pid) SendClientEvent(pid, "marker", "1290.0,1095.0,26.3") end function OnClientEvent(pid, name, payload) -- the client says it is there; the mode checks GetPlayerPos before it counts if name == "marker_reached" then GameText(pid, "Checkpoint!", 1500) end end ``` ## Limits and errors - A script may send at most **30 events a second and 4 KB each** to the server; more is dropped. - A client half is at most **64 files, 256 KB each, 2 MB together**; a file over the limit is left out with a line in the server's log. - An error inside an event or state handler is logged (`[KcdMp] event 'name' handler: ...`) and the handler is left in place; a frame handler that fails is logged and removed; a syntax or load-time error in a file is logged with the file's name and line (`[KcdMp] client script marker.lua: marker.lua:12: ...`) and the other files still run. - `print(...)` and `System.LogAlways("[KcdMp] ...")` land in the KCD:MP client log, `%LOCALAPPDATA%\KcdMp\client.log`; the F9 window, where the server allows it, shows the console's own output. - The game's console splits a line on `;` and treats `a=b` as an assignment: a text passed through a console command must avoid both. The script events encode their payload, so they carry anything. # Client API > Everything a client script may use on a player's game - the KcdMp table's functions and properties and the console commands - each with its own page. A **client script** is a Lua file the server sends to every player who joins and their game runs, in a sandbox - the mode's own half on the screen: a marker, a sound, a bit of UI, a value read from the game. It talks to the server's game mode through **script events** and reads the mode's **state bags**; everything else it does is the game's own Lua, as far as the sandbox lets it. The `KcdMp` table is the whole API on this side; the [guide](/lua/client/getting-started/) says how a script reaches the player and what the game gives it. | Guide | | |---|---| | [Getting started](/lua/client/getting-started/) | what a client script is, how the server sends it, what of the game's Lua the sandbox gives it, limits and logging | | Topic | | |---|---| | [Script events](#script-events) | 2 functions, 1 property | | [State bags](#state-bags) | 1 function, 3 properties | | [Helpers](#helpers) | 5 functions, 1 property | | [Console commands](#console-commands) | 4 console commands | | [The party](#the-party) | 2 properties | ## Script events Named events with a string payload, both ways between the game mode and the client script: the mode's `SendClientEvent` lands in a handler registered with [`KcdMp.on_event`](/lua/client/functions/on_event/); [`KcdMp.send_event`](/lua/client/functions/send_event/) goes up into the mode's `OnClientEvent`. The payload is whatever string the two halves agree on - a number, a comma list, JSON. | Function | What it does | |---|---| | [`KcdMp.on_event`](/lua/client/functions/on_event/) | Registers the handler for one event name from the game mode. | | [`KcdMp.send_event`](/lua/client/functions/send_event/) | Sends an event to the game mode's OnClientEvent. | | Property | What it holds | |---|---| | [`KcdMp.on_any_event`](/lua/client/properties/on_any_event/) | A catch-all handler for events without one of their own. | ## State bags The game mode's **state bags** as every client sees them: string keys and values the mode set with `SetGlobalState`, `SetPlayerState` and `SetEntityState`. The global and the players' bags arrive whole when the client joins and every change arrives at once; an entity's bag comes with the entity when it enters view and goes when it leaves. Values are strings (`"3"`, `"true"`); a removed key reads `nil`. Two hooks tell a script about changes. | Function | What it does | |---|---| | [`KcdMp.on_state`](/lua/client/functions/on_state/) | Registers a handler for one key, whatever bag it changes in. | | Property | What it holds | |---|---| | [`KcdMp.state`](/lua/client/properties/state/) | The bags - global, per player, per entity - as tables of strings. | | [`KcdMp.player_id`](/lua/client/properties/player_id/) | This client's own player id. | | [`KcdMp.on_state_change`](/lua/client/properties/on_state_change/) | A hook called on every change of any bag. | ## Helpers The frame hook, small conveniences the `KcdMp` table offers on top of the game's own Lua, and a switch a script may flip. Everything else a client script does - drawing, sounds, reading the player - is the game's Lua, described in the [guide](/lua/client/getting-started/#the-games-own-lua-as-the-sandbox-gives-it). | Function | What it does | |---|---| | [`KcdMp.on_frame`](/lua/client/functions/on_frame/) | Runs a function every frame - where a script draws. | | [`KcdMp.level`](/lua/client/functions/level/) | The name of the level the game runs. | | [`KcdMp.player_pos`](/lua/client/functions/player_pos/) | The local player's position as a string. | | [`KcdMp.count`](/lua/client/functions/count/) | How many entities of a class the level holds. | | [`KcdMp.census`](/lua/client/functions/census/) | The entity classes of the level with the most instances. | | Property | What it holds | |---|---| | [`KcdMp.label_occlusion`](/lua/client/properties/label_occlusion/) | Whether the labels over the other players hide behind walls. | ## Console commands The client adds a few commands to the game's console. A player reaches them through the **F9** window of the KCD:MP overlay - a line typed there is a console command, and a line starting with `lua ` runs Lua directly. The window is closed unless the server opens it (`[client] console` in its configuration; a development server does, a public one has no reason to) or the game runs offline with `-KcdMp_console`. A script the server sent has no console at all - the sandbox keeps `System.ExecuteCommand` away from it - and talks to the server through the script events; a script run by hand through `KcdMp_exec` has the game's whole Lua and may call `System.ExecuteCommand("...")`. Two things to know about the game's console: it splits a line on `;` and treats `a=b` as a variable assignment, so a text with either has to avoid them (the script events encode their payload for exactly this reason). | Command | What it does | |---|---| | [`KcdMp_exec`](/lua/client/console/kcdmp_exec/) | Runs a Lua file from disk - the development way to try a client script. | | [`KcdMp_log`](/lua/client/console/kcdmp_log/) | Writes a line into the KCD:MP client log. | | [`KcdMp_say`](/lua/client/console/kcdmp_say/) | Sends a chat line, as if typed. | | [`KcdMp_net`](/lua/client/console/kcdmp_net/) | The connection's figures - snapshots decoded, bytes, the acknowledgement. | ## The party The party this player is in (v38), as the server keeps it - the members with their labels and the others' vitals at any distance - for a script that draws its own frames or reacts to the group. The server draws the standard frames unless the mode hides them per player (`ShowPartyFrames` on the server); a script that draws its own reads [`KcdMp.party`](/lua/client/properties/party/) and hooks [`KcdMp.on_party_change`](/lua/client/properties/on_party_change/). The invitation toast and its keys (Y / N, `KcdMp_party_keys` changes them) are the client's own. | Property | What it holds | |---|---| | [`KcdMp.party`](/lua/client/properties/party/) | The party as the server last sent it. | | [`KcdMp.on_party_change`](/lua/client/properties/on_party_change/) | A hook called with the party after every change. | # KcdMp_exec > Runs a Lua file from disk - the development way to try a client script. Runs a Lua file from disk - the development way to try a client script. The file is read from disk and run on the game thread on the next frame, with the game's whole Lua (no sandbox: it is the player's own file); a relative path is relative to the KCD:MP install folder (where `KcdMp_client.dll` lives). The same file can be named on the game's command line as `-KcdMp_exec ` - through the launcher's *Game arguments* - to run two seconds after the level is ready. A syntax error is reported in the client log with its line. The scripts a server sends need none of this: they arrive with the join and run by themselves. ## Syntax ```text KcdMp_exec ``` | Parameter | Type | | |---|---|---| | `file` | path | the Lua file, relative to the install folder or absolute | ## Returns nothing ## Example ```lua KcdMp_exec scripts/arena_client.lua ``` ## See also [KcdMp_log](/lua/client/console/kcdmp_log/) · the [Console commands](/lua/client/#console-commands) group of the index # KcdMp_log > Writes a line into the KCD:MP client log. Writes a line into the KCD:MP client log. The client log is `%LOCALAPPDATA%\KcdMp\client.log`. A script's `System.LogAlways("[KcdMp] ...")` lines land there too - any line starting with `[KcdMp]` is mirrored - which is the easier way from Lua. ## Syntax ```text KcdMp_log ``` | Parameter | Type | | |---|---|---| | `text` | string | the line; no `;` or `=` | ## Returns nothing ## Example ```lua KcdMp_log the marker script is loaded ``` ## See also [KcdMp_exec](/lua/client/console/kcdmp_exec/) · the [Console commands](/lua/client/#console-commands) group of the index # KcdMp_net > The connection's figures - snapshots decoded, bytes, the acknowledgement. The connection's figures - snapshots decoded, bytes, the acknowledgement. A diagnostic line in the client log and the F9 window: how many snapshots arrived as deltas, whole or were dropped, their bytes, and the last acknowledgement - the client's side of the server's traffic figures. For a player who asks "is it me or the server?". ## Syntax ```text KcdMp_net ``` ## Returns nothing ## Example ```lua KcdMp_net ``` ## See also [KcdMp_log](/lua/client/console/kcdmp_log/) · the [Console commands](/lua/client/#console-commands) group of the index # KcdMp_say > Sends a chat line, as if typed. Sends a chat line, as if typed. The line goes to the server like one typed in the chat box: a `/` line is a command for the mode and the server's built-ins. ## Syntax ```text KcdMp_say ``` | Parameter | Type | | |---|---|---| | `text` | string | the line; no `;` or `=` | ## Returns nothing ## Example ```lua KcdMp_say /duel ``` ## See also [KcdMp_exec](/lua/client/console/kcdmp_exec/) · the [Console commands](/lua/client/#console-commands) group of the index # KcdMp.census > The entity classes of the level with the most instances. The entity classes of the level with the most instances. ## Syntax ```lua KcdMp.census(top) ``` | Parameter | Type | | |---|---|---| | `top` | number | how many classes to list | ## Returns `number, string` - `total, list` - the number of entities and a string `"Class n, Class n, ..."` of the `top` most common ## Example ```lua local total, list = KcdMp.census(5) System.LogAlways(string.format("[KcdMp] %d entities: %s", total, list)) ``` ## See also [KcdMp.count](/lua/client/functions/count/) · the [Helpers](/lua/client/#helpers) group of the index # KcdMp.count > How many entities of a class the level holds. How many entities of a class the level holds. ## Syntax ```lua KcdMp.count(cls) ``` | Parameter | Type | | |---|---|---| | `cls` | string | an entity class name (`"NPC"`, `"Horse"`, `"AnimDoor"`, `"Stash"` ...) | ## Returns `number` - `0` when none or the class is unknown ## Example ```lua System.LogAlways("[KcdMp] doors: " .. KcdMp.count("AnimDoor")) ``` ## See also [KcdMp.census](/lua/client/functions/census/) · the [Helpers](/lua/client/#helpers) group of the index # KcdMp.level > The name of the level the game runs. The name of the level the game runs. ## Syntax ```lua KcdMp.level() ``` ## Returns `string` - `klaster`, `trosecko`, `kutnohorsko`; `nil` when unknown ## Example ```lua if KcdMp.level() == "klaster" then System.LogAlways("[KcdMp] the monastery") end ``` ## See also [KcdMp.player_pos](/lua/client/functions/player_pos/) · the [Helpers](/lua/client/#helpers) group of the index # KcdMp.on_event > Registers the handler for one event name from the game mode. Registers the handler for one event name from the game mode. One handler per name; a second call replaces the first. The handler gets the payload and the name. An error inside it is logged (`[KcdMp] event 'name' handler: ...`), never fatal. Events without a handler go to [`KcdMp.on_any_event`](/lua/client/properties/on_any_event/). ## Syntax ```lua KcdMp.on_event(name, fn) ``` | Parameter | Type | | |---|---|---| | `name` | string | the event's name, as the mode sends it | | `fn` | function | `function(payload, name) end` | ## Returns nothing ## Example ```lua KcdMp.on_event("marker", function(payload) local x, y, z = payload:match("^([^,]+),([^,]+),(.+)$") marker = {x = tonumber(x), y = tonumber(y), z = tonumber(z)} System.LogAlways("[KcdMp] marker at " .. x .. " " .. y) end) ``` ## See also [KcdMp.on_any_event](/lua/client/properties/on_any_event/) · [KcdMp.send_event](/lua/client/functions/send_event/) · the [Script events](/lua/client/#script-events) group of the index # KcdMp.on_frame > Runs a function every frame - where a script draws. Runs a function every frame - where a script draws. The game's drawing functions (`System.DrawLabel`, `System.DrawLine` ...) show what they draw for one frame only, so a mark that should stay is drawn again every frame from here; a timer would blink. The handler gets the frame's length in seconds. Several handlers may be registered; one that raises an error is logged (`[KcdMp] frame handler: ...`) and removed, so a broken script cannot fill the log sixty times a second. The handlers go with the script set on a `/reload`. Keep the work small: it runs on the game's thread, every frame. ## Syntax ```lua KcdMp.on_frame(fn) ``` | Parameter | Type | | |---|---|---| | `fn` | function | `function(dt) end` - `dt` the frame time in seconds | ## Returns nothing ## Example ```lua KcdMp.on_frame(function() if marker then System.DrawLabel({x = marker.x, y = marker.y, z = marker.z + 1.6}, 1.4, "here", 1, 0.85, 0.3, 1) end end) ``` ## See also [KcdMp.on_event](/lua/client/functions/on_event/) · the [Helpers](/lua/client/#helpers) group of the index # KcdMp.on_state > Registers a handler for one key, whatever bag it changes in. Registers a handler for one key, whatever bag it changes in. One handler per key. The handler gets the new value (`nil` when removed), the scope (`"global"`, `"player"`, `"entity"`) and the id. Runs before [`KcdMp.on_state_change`](/lua/client/properties/on_state_change/) for the same change. ## Syntax ```lua KcdMp.on_state(key, fn) ``` | Parameter | Type | | |---|---|---| | `key` | string | the key to watch | | `fn` | function | `function(value, scope, id) end` | ## Returns nothing ## Example ```lua -- remember every player's team as the mode puts it in their bags KcdMp.on_state("team", function(value, scope, pid) if scope == "player" then teamOf[pid] = tonumber(value) end end) ``` ## See also [KcdMp.on_state_change](/lua/client/properties/on_state_change/) · [KcdMp.state](/lua/client/properties/state/) · the [State bags](/lua/client/#state-bags) group of the index # KcdMp.player_pos > The local player's position as a string. The local player's position as a string. A quick readout for logs - `"1280.5 1088.0 26.3"`. For numbers, read the player entity directly: `player:GetWorldPos()` gives `{x=, y=, z=}`. ## Syntax ```lua KcdMp.player_pos() ``` ## Returns `string` - `"x y z"` with one decimal; `"none"` before the player exists ## Example ```lua System.LogAlways("[KcdMp] I am at " .. KcdMp.player_pos()) ``` ## See also [KcdMp.level](/lua/client/functions/level/) · the [Helpers](/lua/client/#helpers) group of the index # KcdMp.send_event > Sends an event to the game mode's OnClientEvent. Sends an event to the game mode's OnClientEvent. The server accepts at most 30 events a second and 4 KB each from one client; more is dropped. The payload travels as the string given (`""` without one) - the mode trusts it no further than any other input. ## Syntax ```lua KcdMp.send_event(name [, payload]) ``` | Parameter | Type | | |---|---|---| | `name` | string | the event's name | | `payload` | string | the string to send *(optional)* | ## Returns nothing ## Example ```lua KcdMp.send_event("marker_reached", tostring(markerIndex)) ``` ## See also [KcdMp.on_event](/lua/client/functions/on_event/) · the [Script events](/lua/client/#script-events) group of the index # KcdMp.label_occlusion > Whether the labels over the other players hide behind walls. Whether the labels over the other players hide behind walls. `true` by default: a label is hidden when something stands between the player's eyes and the body. Set it to `false` to see every label through everything - a debugging aid, and a choice a mode may make for its players. ## Syntax ```lua KcdMp.label_occlusion ``` ## Returns `boolean`; `nil` counts as `true` ## Example ```lua KcdMp.label_occlusion = false ``` ## See also the [Helpers](/lua/client/#helpers) group of the index # KcdMp.on_any_event > A catch-all handler for events without one of their own. A catch-all handler for events without one of their own. Set it to a function to receive every event no [`KcdMp.on_event`](/lua/client/functions/on_event/) handler claims. `nil` (the default) ignores them. ## Syntax ```lua KcdMp.on_any_event ``` ## Returns `function | nil` - `function(name, payload) end`, or `nil` for no hook ## Example ```lua KcdMp.on_any_event = function(name, payload) System.LogAlways("[KcdMp] unhandled event " .. name .. ": " .. payload) end ``` ## See also [KcdMp.on_event](/lua/client/functions/on_event/) · the [Script events](/lua/client/#script-events) group of the index # KcdMp.on_party_change > A hook called with the party after every change. A hook called with the party after every change. Set it to a function to hear every PartyState (membership, leader, name, labels, the frames switch) and every vitals update (at most twice a second). The argument is [`KcdMp.party`](/lua/client/properties/party/); an empty party (`id` 0) means the player left or the party ended. An error inside is logged (`[KcdMp] on_party_change: ...`). ## Syntax ```lua KcdMp.on_party_change ``` ## Returns `function | nil` - `function(party) end`, or `nil` for no hook ## Example ```lua KcdMp.on_party_change = function(party) if party.id ~= 0 then print("party " .. party.id .. ": " .. #party.members .. " member(s)") end end ``` ## See also [KcdMp.party](/lua/client/properties/party/) · the [The party](/lua/client/#the-party) group of the index # KcdMp.on_state_change > A hook called on every change of any bag. A hook called on every change of any bag. Set it to a function to hear every change: `scope` is `"global"`, `"player"` or `"entity"`; `id` the pid or entity id (`0` for the global bag); `value` the new string, `nil` when the key was removed. An error inside it is logged, never fatal. ## Syntax ```lua KcdMp.on_state_change ``` ## Returns `function | nil` - `function(scope, id, key, value) end`, or `nil` for no hook ## Example ```lua KcdMp.on_state_change = function(scope, id, key, value) System.LogAlways(string.format("[KcdMp] state %s %s %s = %s", scope, tostring(id), key, tostring(value))) end ``` ## See also [KcdMp.on_state](/lua/client/functions/on_state/) · [KcdMp.state](/lua/client/properties/state/) · the [State bags](/lua/client/#state-bags) group of the index # KcdMp.party > The party as the server last sent it. The party as the server last sent it. `id` is 0 in no party. `members` come in join order, the client's own player among them; each has the pid, the name, the mode's `label`, and the vitals of the last update - `health`, `maxHealth`, `stamina`, `maxStamina`, `injuries` (bits as the game's body parts 1-6), `dead`, `bleeding`, `loading` (not in the world) - with `vitals` false until the first update arrived (the own entry never has them: the game's HUD does). `frames` says whether the server's frames are shown to this player. Read it live; a copy goes stale within half a second. ## Syntax ```lua KcdMp.party ``` ## Returns `table` - `{id = number, leader = pid, name = string, frames = boolean, members = {{pid, name, label, health, maxHealth, stamina, maxStamina, injuries, dead, bleeding, loading, vitals}, ...}}` ## Example ```lua -- the weakest other member, for a script that marks who needs help local function weakest() local party, best, low = KcdMp.party, nil, 2 if not party or party.id == 0 then return nil end for _, m in ipairs(party.members) do if m.pid ~= KcdMp.player_id and m.vitals and not m.dead and m.maxHealth > 0 and m.health / m.maxHealth < low then best, low = m, m.health / m.maxHealth end end return best end ``` ## See also [KcdMp.on_party_change](/lua/client/properties/on_party_change/) · [KcdMp.player_id](/lua/client/properties/player_id/) · the [The party](/lua/client/#the-party) group of the index # KcdMp.player_id > This client's own player id. This client's own player id. Set when the server welcomes the client; `nil` before. The key into `KcdMp.state.player` for the client's own bag, and the pid the mode sees this player as. ## Syntax ```lua KcdMp.player_id ``` ## Returns `number` - the pid; `nil` before the welcome ## Example ```lua local me = KcdMp.state.player[KcdMp.player_id] or {} ``` ## See also [KcdMp.state](/lua/client/properties/state/) · the [State bags](/lua/client/#state-bags) group of the index # KcdMp.state > The bags - global, per player, per entity - as tables of strings. The bags - global, per player, per entity - as tables of strings. `KcdMp.state.global[key]` is the world's bag; `KcdMp.state.player[pid][key]` a player's (every player's, from the join on; the client's own pid is [`KcdMp.player_id`](/lua/client/properties/player_id/)); `KcdMp.state.entity[id][key]` an entity's while it is in view. A player's table appears with their first key and goes with their leave; read `KcdMp.state.player[pid]` defensively. ## Syntax ```lua KcdMp.state ``` ## Returns `table` - `{global = {key = value}, player = {[pid] = {key = value}}, entity = {[id] = {key = value}}}` ## Example ```lua local round = tonumber(KcdMp.state.global.round) or 0 local mine = KcdMp.state.player[KcdMp.player_id] local team = mine and mine.team ``` ## See also [KcdMp.on_state](/lua/client/functions/on_state/) · [KcdMp.on_state_change](/lua/client/properties/on_state_change/) · [KcdMp.player_id](/lua/client/properties/player_id/) · the [State bags](/lua/client/#state-bags) group of the index # Reference > The game's lists a script or a chat command names things from - items, souls, buffs, meshes, presets, stats and skills, animation clips, every level's doors and containers - plus the weather presets and the built-in chat commands. Wherever the API takes a key that names something of the game - an item, a soul, a buff, a mesh, a preset, an animation clip, a door - the thing comes from one of these lists. They are the same for every scripting language; the API pages link into them. The lists in the first table are **generated from the installed game's own files** - the tables, the animation databases, the levels - by the same tool that writes the server's tables export, so the **ids** in them are exactly the ids the server resolves. An id is a row number of a name-sorted export: stable for one export of one game build, shifted by a game patch that adds things - keep the **name** or the **GUID** in anything durable. | List | What is in it | The API that takes it | |---|---|---| | [Items](/reference/items/) | every item class by category: id, name, English name, weight, price, GUID | [`GivePlayerItem`](/lua/server/functions/giveplayeritem/), [`CreatePickup`](/lua/server/functions/createpickup/), [`GetItemInfo`](/lua/server/functions/getiteminfo/), `/give`, `/item` | | [Souls](/reference/souls/) | every soul by archetype - horses, dogs, people, animals: id, name, GUID | [`CreateHorse`](/lua/server/functions/createhorse/), [`CreateDog`](/lua/server/functions/createdog/), [`CreateActor`](/lua/server/functions/createactor/), [`SetSpawnInfo`](/lua/server/functions/setspawninfo/)'s appearance, `/horse`, `/dog` | | [Buffs](/reference/buffs/) | every buff by class: id, name, English name, duration, GUID | [`GivePlayerBuff`](/lua/server/functions/giveplayerbuff/), [`ClaimBuffClasses`](/lua/server/functions/claimbuffclasses/), `[combat] claimed_buffs` | | [Meshes](/reference/meshes/) | every static mesh of the object files by folder: id, name, path | [`CreateProp`](/lua/server/functions/createprop/), `/prop` | | [Consumables](/reference/consumables/) | every food, drink, potion, poison and ointment with its health, alcohol, buff and regeneration | [`OnPlayerUseItem`](/lua/server/callbacks/onplayeruseitem/) | | [Clothing presets](/reference/clothing-presets/) | every outfit by gender, with its pieces and GUID | [`SetSpawnInfo`](/lua/server/functions/setspawninfo/), [`CreateActor`](/lua/server/functions/createactor/), `[spawn] clothing_preset` | | [Weapon presets](/reference/weapon-presets/) | every set of arms with its weapons and GUID | [`SetSpawnInfo`](/lua/server/functions/setspawninfo/), [`CreateActor`](/lua/server/functions/createactor/), `[spawn] weapon_preset` | | [Stats and skills](/reference/stats-and-skills/) | the character's stats and skills by name | [`SetPlayerStat`](/lua/server/functions/setplayerstat/), [`SetPlayerSkill`](/lua/server/functions/setplayerskill/) | | [Animations](/reference/animations/) | every clip of the male animation set by fragment family | [`SetActorAnim`](/lua/server/functions/setactoranim/) | | [Particle effects](/reference/particle-effects/) | every particle effect by library | [`SpawnEffect`](/lua/server/functions/spawneffect/) | | [Audio triggers](/reference/audio-triggers/) | every sound trigger by set | [`PlaySound`](/lua/server/functions/playsound/) | | [Decal materials](/reference/decal-materials/) | every decal material | [`SpawnDecal`](/lua/server/functions/spawndecal/) | | [Levels, doors and containers](/reference/levels/) | the three levels and every door and stash placed in each, with the key and the position | [`SetDoorState`](/lua/server/functions/setdoorstate/), [`GetContainerItems`](/lua/server/functions/getcontaineritems/), `[server] level` | Two pages follow the server's code rather than the game's files: | Page | | |---|---| | [Weather](/reference/weather/) | the presets and the level sky profiles they stand for - [`SetWeather`](/lua/server/functions/setweather/), `/weather` | | [Chat commands](/reference/chat-commands/) | the commands the server answers in every game mode, and who may use each | The lists are the server's own export of the game: [Exporting the game's tables](/guides/game-tables/) makes the same file for your server, so the ids here are the ids it resolves. Every key of `server.toml` is on [Server configuration](/getting-started/server-config/). # Parties > How players form parties, what the server does on its own - the group, the invitation, the frames, no friendly fire - and the callbacks and functions a game mode builds its party commands and rules around. Players group up, the server keeps the group and shows every member the others' health and stamina in party frames on the left of the screen, and the game mode decides everything else. Every callback and function below has its own page in the [index](/lua/server/#parties). ## What a party is A small group of players - **five** by default - with a **leader**. It comes into being when the first invitation is accepted and ends when it falls to one member: there is no party of one. A player is in at most one party and has at most one invitation pending. Any member may invite; whether that stays so is the mode's rule (see `OnPartyInvite`). The server does these things by itself: - **No friendly fire.** A hit between two members is refused before it ever reaches `OnPlayerDamage`, the way a hit between teammates is, and starts no fight. `[party] friendly_fire = true` gives it back. - **The frames.** Each member sees the others as a column of frames under the game's HUD: name, a label the mode may set, health and stamina bars, injury and bleeding marks, the leader's name in gold, greyed while dead or loading. The bars stay live at any distance - a member who walks off, or is in another virtual world, is still on the frame. Nothing on the frame says where a member is: no distance, no direction. - **The invitation.** The invited player gets a toast with a countdown and two keys to accept or decline (**Y** and **N**; `KcdMp_party_keys ` in their console changes them); the mode's own `/accept` command answers the same invitation. An invitation times out after `[party] invite_timeout` seconds and is withdrawn when the party fills or disbands. - **The leader.** When the leader leaves, the next member in join order leads (`[party] leader_leaves = "disband"` ends the party instead). A disconnect leaves the party at once; nothing is remembered across sessions. Everything a player *types* is the mode's. The server ships no party commands: `/invite`, `/accept`, `/decline`, `/leave`, `/kick`, `/leader`, `/p` are a dozen lines of the mode (the example below), which is where every rule lives - who may invite whom, a level gate, leader-only invitations, what the party chat looks like. The shipped freeroam mode carries these commands as its example; a server owner keeps, changes or drops them. A client script sees the party too - `KcdMp.party` and the hook `KcdMp.on_party_change` in [the client API](/lua/client/#the-party) - so a mode that wants frames of its own hides the server's with `ShowPartyFrames(pid, false)` and draws from that. Parties and [teams](/lua/server/combat/#teams) are separate things: a party is a group with a leader, frames and invitations; a team is a number that turns friendly fire off. A mode may use both. ## Callbacks | Callback | When | |---|---| | [`OnPartyInvite(from, target)`](/lua/server/callbacks/onpartyinvite/) | before the invitation is sent; **`return false` refuses it** - the place for leader-only invitations or any other rule | | [`OnPartyInviteResponse(from, target, answer)`](/lua/server/callbacks/onpartyinviteresponse/) | `"accepted"`, `"declined"`, `"timeout"`, or `"cancelled"` (the party filled or disbanded first, or a side disconnected) | | [`OnPartyCreate(party, leader)`](/lua/server/callbacks/onpartycreate/) | the group exists; fires before the first two joins | | [`OnPlayerJoinParty(party, pid, reason)`](/lua/server/callbacks/onplayerjoinparty/) | every member arrives through here, the leader too: `"create"`, `"invite"` or `"mode"` | | [`OnPlayerLeaveParty(party, pid, reason)`](/lua/server/callbacks/onplayerleaveparty/) | `"left"`, `"kicked"`, `"disconnect"` or `"disband"` | | [`OnPartyLeaderChange(party, pid, previous)`](/lua/server/callbacks/onpartyleaderchange/) | a hand-over, by the mode or by the leader leaving | | [`OnPartyDisband(party, reason)`](/lua/server/callbacks/onpartydisband/) | `"empty"` (down to one member), `"mode"` or `"leader"`; fires last, after every leave | ## Functions A party is a **number**; ids are never reused while the server runs, so an id a mode kept never points at a newer group. | Function | Returns | What it does | |---|---|---| | [`InviteToParty(from, target)`](/lua/server/functions/invitetoparty/) | `true`, or `false, reason` | sends the invitation; `reason` is `"not connected"`, `"self"`, `"in a party"`, `"full"`, `"pending"` or `"refused"` (`OnPartyInvite` said no) | | [`AcceptPartyInvite(pid)`](/lua/server/functions/acceptpartyinvite/) | `boolean` | the mode's `/accept`; joins the inviter's party, creating it when they have none | | [`DeclinePartyInvite(pid)`](/lua/server/functions/declinepartyinvite/) | `boolean` | the mode's `/decline` | | [`GetPlayerPartyInvite(pid)`](/lua/server/functions/getplayerpartyinvite/) | `from, seconds` or `nil` | the pending invitation | | [`AddPlayerToParty(host, pid)`](/lua/server/functions/addplayertoparty/) | `boolean` | no invitation: puts `pid` into `host`'s party, making it when there is none - a queue, a raid maker | | [`RemovePlayerFromParty(pid, reason)`](/lua/server/functions/removeplayerfromparty/) | `boolean` | `"left"` (the default) or `"kicked"` | | [`SetPartyLeader(party, pid)`](/lua/server/functions/setpartyleader/) | `boolean` | `pid` must be a member | | [`DisbandParty(party)`](/lua/server/functions/disbandparty/) | `boolean` | everyone leaves with `"disband"` | | [`GetPlayerParty(pid)`](/lua/server/functions/getplayerparty/) | `number` or `nil` | | | [`GetPartyLeader(party)`](/lua/server/functions/getpartyleader/) | `number` or `nil` | | | [`GetPartyMembers(party)`](/lua/server/functions/getpartymembers/) | `table` of pids | in join order | | [`GetPartySize(party)`](/lua/server/functions/getpartysize/) / `IsPartyFull(party)` | `number` / `boolean` | against `[party] max_size` | | [`ArePartyMembers(a, b)`](/lua/server/functions/arepartymembers/) | `boolean` | for the mode's own rules - loot, chat, a duel refused between friends | | [`GetParties()`](/lua/server/functions/getparties/) | `table` of party ids | | | [`SetPartyName(party, text)`](/lua/server/functions/setpartyname/) / `GetPartyName(party)` | | the title over the frames; `""` none | | [`SetPartyMemberLabel(pid, text)`](/lua/server/functions/setpartymemberlabel/) / [`GetPartyMemberLabel(pid)`](/lua/server/functions/getpartymemberlabel/) | `boolean` / `string` | a line under the name in the frame - a role, a score; `""` none | | [`ShowPartyFrames(pid, shown)`](/lua/server/functions/showpartyframes/) | `boolean` | per player; `[party] frames` is the default for everyone | | [`SendPartyMessage(party, colour, text)`](/lua/server/functions/sendpartymessage/) | `boolean` | one chat line to every member - the `/p` command is the mode's | | [`SetPartyData(party, key, value)`](/lua/server/functions/setpartydata/) / [`GetPartyData(party, key)`](/lua/server/functions/getpartydata/) | | the mode's private storage on a party, gone with it | The C# tier has the same names on `IServerApi` and `IGameMode`, with `IParty` (`Id`, `Leader`, `Members`, `Name`, `Data`) and `IPlayer.Party` / `IPlayer.PartyLabel`. ## Configuration `[party]` in `server.toml` ([the reference page](/getting-started/server-config/#party)): | Key | Default | Meaning | |---|---|---| | `max_size` | `5` | members per party | | `invite_timeout` | `30` | seconds until a pending invitation times out | | `frames` | `true` | the frames are on for everyone until the mode says otherwise per player | | `leader_leaves` | `"next"` | `"next"` hands the lead to the next member in join order; `"disband"` ends the party | | `friendly_fire` | `false` | `true` lets members hurt each other | ## A mode's commands What the shipped freeroam mode carries - `/invite `, `/accept`, `/decline`, `/leave`, `/kick `, `/leader `, `/disband` and `/p ` - with [`GetPlayerId`](/lua/server/functions/getplayerid/) for the name and the `false, reason` of `InviteToParty` for the refusal: ```lua function OnPlayerCommandText(pid, cmd, args) if cmd == "invite" then local target = GetPlayerId(args) if not target then return SendClientMessage(pid, COLOUR_RED, "No such player.") end local ok, reason = InviteToParty(pid, target) if ok then SendClientMessage(pid, COLOUR_SERVER, "Invited " .. GetPlayerName(target) .. ".") else SendClientMessage(pid, COLOUR_RED, "Cannot invite: " .. reason .. ".") end return true elseif cmd == "accept" then if not AcceptPartyInvite(pid) then SendClientMessage(pid, COLOUR_RED, "Nobody invited you.") end return true elseif cmd == "decline" then DeclinePartyInvite(pid) return true elseif cmd == "leave" then if not RemovePlayerFromParty(pid, "left") then SendClientMessage(pid, COLOUR_RED, "You are in no party.") end return true elseif cmd == "kick" or cmd == "leader" then local party, target = GetPlayerParty(pid), GetPlayerId(args) if not party or GetPartyLeader(party) ~= pid then return SendClientMessage(pid, COLOUR_RED, "You lead no party.") end if not target or GetPlayerParty(target) ~= party then return SendClientMessage(pid, COLOUR_RED, "Not in your party.") end if cmd == "kick" then RemovePlayerFromParty(target, "kicked") else SetPartyLeader(party, target) end return true elseif cmd == "disband" then local party = GetPlayerParty(pid) if party and GetPartyLeader(party) == pid then DisbandParty(party) end return true elseif cmd == "p" then local party = GetPlayerParty(pid) if not party then return SendClientMessage(pid, COLOUR_RED, "You are in no party.") end SendPartyMessage(party, 0x80C0FFFF, "[Party] " .. GetPlayerName(pid) .. ": " .. args) return true end return false end function OnPartyInvite(from, target) SendClientMessage(target, COLOUR_SERVER, GetPlayerName(from) .. " invites you to a party - /accept or /decline.") end function OnPlayerJoinParty(party, pid, reason) SendPartyMessage(party, COLOUR_SERVER, GetPlayerName(pid) .. " joined the party.") end function OnPlayerLeaveParty(party, pid, reason) if reason ~= "disband" then SendPartyMessage(party, COLOUR_SERVER, GetPlayerName(pid) .. " left the party (" .. reason .. ").") end end ``` Leader-only invitations are one more line at the top of `OnPartyInvite`: `if GetPlayerParty(from) and GetPartyLeader(GetPlayerParty(from)) ~= from then return false end`. # Chat commands > The chat commands the server answers itself in every game mode - who may use each, what it takes, and how a mode overrides one. A `/` line typed in the chat is dispatched in this order: the server's own account and fight commands, then the game mode ([`OnPlayerCommandText`](/lua/server/callbacks/onplayercommandtext/) in Lua, `OnPlayerCommand` in C#; `true` = handled), then the **built-ins** below, then `Unknown command: /x`. A mode overrides any built-in by handling its name; a mode's `/help` that prints a line and returns `false` is followed by the server's own list. Commands are never echoed to the chat. `[commands]` in [`server.toml`](/getting-started/server-config/#commands) switches the built-ins: `builtin = false` turns them all off, `disabled` turns some off by name, `public` names the ones anyone may use - every other built-in answers **admins only** ("Admins only." to everyone else). Admins are the logged-in owners of `[accounts] admins` or players the mode promoted ([`SetPlayerAdmin`](/lua/server/functions/setplayeradmin/)). ## The server's own Always answered, before the mode sees the line, whatever `[commands]` says. | Command | | |---|---| | `/register ` | claims the caller's name: from then on it needs the password (at least `[accounts] min_password_length` characters, no spaces). Off when `[accounts] registration = false` | | `/login ` | proves a registered name; three wrong tries kick. A registered name not logged in within `[accounts] login_grace_seconds` is kicked | | `/fight ` | starts a fight with that player - both may lock on to each other. Refused when pvp is off | | `/peace` | ends every fight of the caller | ## Public by default `[commands] public = ["help", "pos", "players", "items", "uptime"]`. | Command | | |---|---| | `/help` | the commands the caller may use - the mode's line first when it prints one, then this list | | `/pos` | the server's record of the caller: position, yaw, reports received, ping | | `/players` | who is online | | `/items ` | the first eight items whose name, English name or category holds the words, with their ids ([items](/reference/items/)) | | `/uptime` | how long the caller has been on, and the server tick | ## Admins only by default | Command | | |---|---| | `/give [count]` | puts items in the caller's inventory - the item by name, id, GUID or English name (several words allowed; a trailing number is the count): `/give duelling longsword 2` | | `/item ` | places one of the item as a pickup in front of the caller, in their virtual world | | `/tp x y z` \| `/tp ` | teleports the caller to a point (`z` below `0` = on the terrain) or next to a player, following them into their virtual world | | `/goto ` | the same as `/tp ` | | `/horse [soul]` | the horse next to the caller, or theirs called over, or a new one; with a soul named ([horses](/reference/souls/horse/), by name, id or GUID) always a new horse of that breed, mounted | | `/horses ` | the first eight horse breeds whose name holds the words | | `/dog [soul]` | a dog at the caller's heel ([dogs](/reference/souls/dog/)), on the game's own companion AI; `/dog` again sends it away | | `/dog stay`, `/dog follow`, `/dog free` | the dog waits where it is, comes along again, or roams ([`SetDogMode`](/lua/server/functions/setdogmode/)) | | `/prop [scale] [rigid]` | places a static mesh 2.5 m ahead ([meshes](/reference/meshes/) by id, file name or path): `/prop barrel_a`, `/prop 441 1.5 rigid` | | `/props ` | searches the meshes | | `/time [hh:mm]` | the world clock: shows it, or sets it for everyone | | `/rain [0-1 \| off]` | the rain override: shows it, forces an amount, or hands the rain back to the weather | | `/weather [preset \| profile] [blend seconds]` | alone lists the presets; with one, changes the sky for everyone ([weather](/reference/weather/)) | | `/heal [player]` | full health and stamina, injuries, bleeding, alcohol and buffs gone - the caller's or the named player's | | `/kick [reason]` | disconnects the player | | `/kickban [minutes]` | kicks and bans the name and the address; without minutes, for good | | `/unban ` | lifts a ban | | `/reload` | reloads the game mode without a restart | The example modes add their own: `freeroam.lua` has `/tag`, `/colour`, `/team`, `/actor` (its `heal` arm heals the demo character, `hostile [player]` sets it on you or on the player named), `/hurt [player] [amount]` (takes health off a player without a blow), `/kill [player]` (the server's death without a blow), `/fx [effect]` and `/sfx [trigger]`, and for a server with [world data](/guides/#the-games-data) `/actor come` (the demo character walks to you along the navigation mesh), `/los [name]` (whether the line to that player is clear, or what stands 30 m ahead) and `/ground` (the floor under you against the terrain's height); `duel_arena.lua` has `/duel`, `/leave`, `/score`, `/queue`, `/arena`. A mode's commands are whatever its `OnPlayerCommandText` answers; the [getting-started guide](/lua/server/getting-started/#a-command-with-arguments) shows one with typed arguments (`sscanf`: a player, a number, the rest of the line, in one call). # Stats and skills > The game's core stats and skills by name: what SetPlayerStat and SetPlayerSkill take. The **stats** and **skills** of Kingdom Come: Deliverance II as the game names them (`Libs/Tables/rpg/stat.xml`, `skill.xml`). `SetPlayerStat(pid, stat, level)` and `SetPlayerSkill(pid, skill, level)` ([Lua](/lua/server/functions/setplayerstat/), [C#](/csharp/server/)) take the **name** column and a level from 1 to 30; the level is kept on the player's record and re-applied at every spawn, and the game never lowers a level. `GetPlayerStat` / `GetPlayerSkill` answer the level of record (0 = never set). The player of the multiplayer level starts at level 5 everywhere; `[spawn] stat_level` in `server.toml` raises the four core stats for everyone at the spawn. ## Stats | name | shown as | |---|---| | `strength` | Strength | | `agility` | Agility | | `vitality` | Vitality | | `speech` | Speech | | `prestige` | Blacksmith Prestige | `prestige` is the blacksmithing prestige of the story game, not a combat stat. ## Skills A **hidden** skill is one the game's own character screen does not show; the name is still the table's, and whether the engine takes a level for it is untested. | name | shown as | category | hidden | |---|---|---|---| | `alchemy` | Alchemy | NonCombat | | | `armourer` | Armourer | NonCombat | yes | | `bard` | Fox | NonCombat | yes | | `bowyery` | Bowyery | NonCombat | yes | | `cooking` | Cooking | NonCombat | yes | | `craftsmanship` | Craftsmanship | NonCombat | | | `defense` | Defence | Combat | yes | | `drinking` | Drinking | NonCombat | | | `fencing` | Warfare | Combat | | | `first_aid` | First Aid | NonCombat | yes | | `fishing` | Fishing | NonCombat | yes | | `gambling` | | NonCombat | yes | | `gunsmithing` | Gunsmith | NonCombat | yes | | `heavy_weapons` | Heavy Weapons | Combat | | | `horse_riding` | | NonCombat | | | `houndmaster` | Houndmaster | NonCombat | | | `marksmanship` | Marksmanship | Combat | | | `mining` | Mining | NonCombat | yes | | `scholarship` | Scholarship | NonCombat | | | `shoemaking` | Cobbler | NonCombat | yes | | `stealth` | Stealth | NonCombat | | | `survival` | Survival | NonCombat | | | `tailoring` | Tailor | NonCombat | yes | | `thievery` | Thievery | NonCombat | | | `weapon_dagger` | Dagger | Combat | yes | | `weapon_large` | Polearms | Combat | | | `weapon_shield` | Shield | Combat | yes | | `weapon_sword` | Swords | Combat | | | `weapon_unarmed` | Unarmed | Combat | | | `weaponsmithing` | Weaponsmith | NonCombat | yes | # Weather > The weather presets a mode or an admin may name and the level sky profiles they stand for. The sky every client shows is one of the level's **time-of-day profiles** - the same eight on all three levels - and the server names it for everyone: [`SetWeather`](/lua/server/functions/setweather/) in a mode, `/weather` in the chat, `[world] weather` in `server.toml` for the start. A **preset** is a friendly name for a profile; a profile name passes through as it is, which also admits the profiles the game's own quests use (`q_*` names in the level's mission file). Each client blends a change in over `[world] weather_blend` seconds (10 by default) unless the call names its own blend. | Preset | Profile | What it looks like | |---|---|---| | `clear`, `sunny` | `cloudless_sunny` | a clear sky | | `fair` | `semicloudy_clear` | a few clouds, clear light | | `cloudy` | `cloudy_no_rain` | overcast without rain | | `overcast` | `summer_overcast` | a heavy summer sky | | `showers` | `cloudy_frequent_showers` | clouds and passing rain | | `drizzle`, `fog` | `foggy_drizzly` | fog and a fine rain | | `storm` | `foggy_storm` | a storm with rain | | `dry_storm` | `foggy_storm_no_rain` | the storm's sky without the rain | `""` (an empty name) leaves every client's sky as it is - the game's own rotation goes on. The **rain** is a lever on top of the profile: [`SetRain`](/lua/server/functions/setrain/) (`/rain`, `[world] rain`) forces an amount from `0` to `1` whatever the profile's own rain probability says; `-1` hands it back. [`GetWeatherPresets`](/lua/server/functions/getweatherpresets/) returns this table to a mode.