# Lua scripting Scripts are written in the in-game editor (`J` by default, rebindable under *Options → Controls* → *Codecraft*) and run **on the server**. The top bar's **Run Script** executes `main.lua`, which is the entrypoint. This same documentation is browsable in-game from the editor: **Help → Lua API Documentation**, or press **F1** on a function while editing. Because a script runs on the server thread from start to finish, everything it does happens at once and the game waits for it to finish. Loops that place millions of blocks will freeze the server, so keep them reasonable. A script can also keep listening *after* it has finished, with [events](#events). ```lua print("hello, player!") ``` ## print(...) Writes to the chat of the player who ran the script, tab-separated, like Minecraft commands do. ```lua print("blocks placed:", 12) ``` Whole numbers go through the Lua wrapper and are printed as `12.0`. To print them without the decimal, concatenate them into a string: ```lua print("blocks placed: " .. 12) -- -> blocks placed: 12 ``` ## run(command) Runs a Minecraft command from the server command source, with full server permissions and no player position or entity. The command may be written with or without a leading slash. The function returns `true` when the command is submitted, or `false` and a reason when the argument is invalid. A `true` result means the command was submitted; it does not guarantee the command succeeded. ```lua run("time set day") run("weather clear") ``` For commands that need a player or coordinates, use explicit selectors and coordinates in the command string. The command source is the server, not the player running Lua. ## Blocks Coordinates are **absolute world coordinates** — never relative to the player — in the dimension the running player stands in. Press `F3` to read your own coordinates, then use them in the script. | Function | Returns | | --------------------------------------- | --------------------------------------------------- | | `world.set_block(x, y, z, block)` | `true`, or `false` and a reason | | `world.remove_block(x, y, z[, drops])` | `true`, or `false` and a reason | | `world.get_block(x, y, z)` | block id string, or `nil` and a reason | | `world.get_dimension()` | dimension id | | `world.get_time()` / `world.set_time(ticks)` | world clock time in ticks | | `world.get_weather()` / `world.set_weather(weather[, ticks])` | `clear`, `rain` or `thunder` | | `world.get_biome(x, y, z)` | biome id, or `nil` and a reason | | `world.players()` | array of online player names | ### world.set_block(x, y, z, block) Places a block and updates neighbours and clients, like `/setblock` does. `block` is a block id, with or without the `minecraft:` namespace, and may carry block states: ```lua world.set_block(10, 64, -3, "minecraft:stone") world.set_block(10, 65, -3, "gold_block") -- namespace optional world.set_block(10, 66, -3, "minecraft:oak_stairs[facing=north]") world.set_block(11, 66, -3, "minecraft:wall_torch[facing=south]") -- needs a wall behind it ``` The block is placed even if something is in the way. Blocks that cannot survive where they are put (a torch without a wall, a flower without ground) drop themselves again, and the call reports it as a failure. Replacing a block that holds items, such as a chest, drops the contents like `/setblock` does. ### world.remove_block(x, y, z[, drops]) Removes the block. Without `drops` the block just vanishes, silently and without items. With `true` it breaks the way a player breaking it would: items, sound and particles. ```lua world.remove_block(10, 64, -3) -- vanish world.remove_block(10, 65, -3, true) -- break it, dropping items ``` ### world.get_block(x, y, z) Returns the block id at that position, including its block states, so the result can be handed straight back to `world.set_block`: ```lua print(world.get_block(10, 64, -3)) -- -> minecraft:grass_block[snowy=false] ``` Air is `"minecraft:air"`, a string, and every string is *true* in Lua — compare against the id rather than testing the value: ```lua local block = world.get_block(10, 64, -3) if block ~= "minecraft:air" then print("something is there: " .. block) end ``` ## Entities Entity ids returned by `entities.nearby` and `entities.spawn` are UUID strings. The nearby query only checks loaded entities in the executing player's current dimension; it excludes the script owner, its radius defaults to 16 blocks and is capped at 128. Entity positions are absolute. | Function | Purpose | | -------- | ------- | | `entities.nearby([radius[, type]])` | UUIDs of nearby entities, optionally filtered by type id | | `entities.spawn(type, x, y, z)` | Spawn a summonable entity and return its UUID | | `entities.get(uuid)` | Return type id, x, y, z and custom/display name | | `entities.teleport(uuid, x, y, z)` | Move an entity in its current dimension | | `entities.remove(uuid)` | Remove an entity (players are protected) | | `entities.set_name(uuid, name)` | Set a visible custom name | | `entities.set_health(uuid, health)` | Set living entity health up to its maximum | ```lua local ids = entities.nearby(12, "minecraft:zombie") for _, id in ipairs(ids) do local type, x, y, z, name = entities.get(id) print(name .. " is at " .. x .. ", " .. y .. ", " .. z) end ``` ## Scoreboards Scoreboard helpers operate on the server scoreboard. Objective names follow vanilla's 1–16 character limit. `create_objective` defaults to the `dummy` criterion; built-in criteria such as `deathCount` and `health` are also accepted. `display` accepts `list`, `sidebar` or `below_name`. | Function | Purpose | | -------- | ------- | | `scoreboard.create_objective(name[, criterion[, display_name]])` | Create an objective | | `scoreboard.remove_objective(name)` | Remove an objective | | `scoreboard.set(player, objective, value)` | Set a score | | `scoreboard.add(player, objective, value)` | Add to a score | | `scoreboard.get(player, objective)` | Read a score (`nil` when unset) | | `scoreboard.reset(player[, objective])` | Clear one score or all of a player's scores | | `scoreboard.display(objective, slot)` | Show an objective in a display slot | ```lua scoreboard.create_objective("coins", "dummy", "Coins") scoreboard.add("Alex", "coins", 5) scoreboard.display("coins", "sidebar") ``` ## HUD and boss bars Titles, subtitles and action-bar messages go to the player who ran the script by default; pass an online player name to target someone else. Title timings are measured in ticks (20 ticks per second). Boss bars are saved server-side, identified by a resource id; ids without a namespace use `codecraft:`. A new boss bar is shown to the script owner by default. `bossbar_visible` can add or remove any online player. | Function | Purpose | | -------- | ------- | | `hud.title(text)` / `hud.subtitle(text)` | Show a title or subtitle | | `hud.action_bar(text)` | Show text above the hotbar | | `hud.title_times(fade_in, stay, fade_out)` | Set title timings in ticks | | `hud.clear_titles([reset])` | Clear title and subtitle | | `hud.bossbar_add(id, name[, max])` | Create a boss bar (max defaults to 100) | | `hud.bossbar_remove(id)` | Remove a boss bar | | `hud.bossbar_value(id, value)` / `hud.bossbar_max(id, value)` | Change boss bar progress | | `hud.bossbar_visible(id, visible)` | Show or hide it for the script owner | ```lua hud.title_times(10, 60, 20) hud.title("Welcome!") hud.action_bar("You have " .. scoreboard.get("Alex", "coins") .. " coins") hud.bossbar_add("round", "Round progress", 10) hud.bossbar_value("round", 3) ``` ## Items and inventories Item ids can omit the `minecraft:` namespace. Inventory slots are indexed from 0 to 35 in the player's main inventory. The optional player argument names an online player; when omitted, the script owner is used. Excess items from `items.give` drop at the target player's feet. `items.clear` and `items.count` only affect the main inventory. | Function | Purpose | | -------- | ------- | | `items.give(item, count[, player])` | Give items; overflow drops at the player | | `items.count(item[, player])` | Count matching items in the main inventory | | `items.clear(item[, player])` | Remove matching items; also returns the removed count | | `items.get_slot(slot[, player])` | Read an inventory slot (item id and count, or `nil`) | | `items.set_slot(slot, item, count[, player])` | Replace a slot; count 0 clears it | ```lua items.give("gold_ingot", 8) print("You now have " .. items.count("minecraft:gold_ingot")) items.set_slot(0, "minecraft:diamond_sword", 1) ``` All mutating helpers return `true` on success or `false` and a reason on invalid input or missing targets. Read helpers return their value, or `nil` and a reason when lookup fails. ## Events Listeners let a script react to the game *after* it has finished running. Register one with `events.on_(callback)`; from then on the callback runs whenever the event happens. | Registration | Callback signature | | ----------------------------------- | ----------------------------------------------------------- | | `events.on_use_item(cb)` | `cb(player, item, count, hand)` | | `events.on_break_block(cb)` | `cb(player, x, y, z, block)` | | `events.on_chat(cb)` | `cb(player, message)` | | `events.on_player_join(cb)` | `cb(player)` | | `events.on_player_leave(cb)` | `cb(player)` | | `events.on_tick(cb)` | `cb(tick)` | `player` is always the name of the player who caused the event. Other values depend on the event: - **on_use_item** — fires when a player right-clicks to use the item in their hand: `item` is the item id (`"minecraft:stick"`), `count` the stack size, and `hand` `"main"` or `"off"`. An empty hand does not fire. The click still does whatever it would normally do — the listener only observes it. - **on_break_block** — fires *after* the block is broken (`x, y, z` now hold air), with the id of the block that was there. - **on_chat** — fires with the plain text of the message. The message is sent to chat as usual. - **on_player_join / on_player_leave** — fire when a player joins or leaves, including the running player themselves. - **on_tick** — fires at the end of every server tick with the tick counter, a whole number that grows by one every tick (20 ticks per second). Keep tick callbacks cheap: they run twenty times a second, and a slow one lags the whole server. Callbacks run on the server thread and have the same powers as the script that registered them — they can call `print` and the Minecraft API tables. An error inside a callback is printed to the owner's chat; it never stops the game or the other listeners. ```lua events.on_use_item(function(player, item, count, hand) if item == "minecraft:stick" then print(player .. " waved a stick (" .. hand .. " hand)") end end) events.on_break_block(function(player, x, y, z, block) if block == "minecraft:diamond_ore" then print(player .. " struck diamond at " .. x .. ", " .. y .. ", " .. z) end end) ``` ### Listening resets Pressing **Run Script** replaces the previous run completely: all listeners from the previous run are dropped, and only the ones the new run registers are active. If a run registers none, the old listeners go quiet. Likewise, when the running player disconnects their script stops with them — a script cannot outlive its owner. If you run the same script twice, its listeners are *not* doubled — each run starts from a clean slate. ## Examples A pillar four blocks tall: ```lua for y = 64, 67 do world.set_block(10, y, -3, "minecraft:cobblestone") end ``` A 7×7 platform: ```lua for x = -3, 3 do for z = -3, 3 do world.set_block(10 + x, 64, -3 + z, "minecraft:stone_bricks") end end ``` A room with walls, a floor and an empty inside, i.e. hollowing out a box: ```lua local x, y, z = 10, 64, -3 -- corner of the room local width, height, depth = 7, 4, 7 for dx = 0, width - 1 do for dy = 0, height - 1 do for dz = 0, depth - 1 do local shell = dx == 0 or dx == width - 1 or dy == 0 or dy == height - 1 or dz == 0 or dz == depth - 1 local px, py, pz = x + dx, y + dy, z + dz if shell then world.set_block(px, py, pz, "minecraft:stone_bricks") else world.remove_block(px, py, pz) end end end end ``` Copy the block type of one place to another: ```lua local block = world.get_block(10, 64, -3) if block then world.set_block(20, 70, 5, block) end ``` Clear an area of everything that is not air (leaves, grass, and so on): ```lua for x = 0, 15 do for y = 60, 80 do for z = 0, 15 do if world.get_block(x, y, z) ~= "minecraft:air" then world.remove_block(x, y, z) end end end end ``` ## Checking whether a call worked Every block function returns a reason as its second value, which is worth printing while a script misbehaves: ```lua local ok, reason = world.set_block(10, 64, -3, "minecraft:stone") if not ok then print("could not place the block: " .. reason) end ``` | Reason | What it means | | ------------------------------------------ | ------------------------------------------------------------------------- | | `usage: world.set_block(...)` | too few arguments | | `x, y and z must be numbers` | a coordinate is missing, `nil`, or a string like `"10"` | | `block must be a string, e.g. "minecraft:stone"` | the block was given as a number or table rather than a string | | `'X' is not a block` | unknown block id, a misspelled state, or a tag such as `#minecraft:logs` | | `y must be between -64 and 319, not 400` | outside the world's build height | | `the chunk at x, z is not loaded` | too far away from any player, and not force-loaded | | `'X' does not fit at x, y, z` | the block was placed and removed itself again (no support block) | | `there is nothing to remove at x, y, z` | the target block is already air | ## Limits - No reach or permission checks: a script can change any block in a **loaded** chunk of the running player's dimension. Keep an eye on what you run. - Only loaded chunks can be read or edited — those around players, or force-loaded. - Block entity data is not exposed: a placed chest is empty, and a sign has no text. - Only `main.lua` is executed. Code in the other project files is not loaded, so `require` does not find them yet. - The Lua runtime is LuaJ (Lua 5.1) with only the base library loaded: `tostring`, `tonumber`, `type`, `pcall`, `pairs`, `ipairs`, `assert`, `error` are available, but the `string`, `math`, `table` and `coroutine` libraries are not, so `math.floor(2.7)` fails with *attempt to index a nil value*.