Lua Functions

Pick Lua in the language menu of the Functions tab to write your server rules in Lua 5.4. NetStack compiles your code on the server and runs it in the same sandbox as JavaScript, with the same limits and the same all-or-nothing behaviour.

Anatomy

Define a function called run. It receives ctx and args, and whatever it returns is sent back to the caller.

function run(ctx, args)
  return { ok = true }
end
  • args is a table with whatever your game passed to call(), so read it as args.itemId. Arrays in args start at index 1, as usual in Lua.
  • Return a table, string, number, boolean or nil. A table with keys 1..n is sent as a JSON array, any other table as an object.
  • local function helpers, metatables and setmetatable-style objects are fine in the same file. require is not available: keep everything in one file.
local MAX_HP = 100

local function heal_amount(level)
  return math.floor(10 + level * 1.5)
end

function run(ctx, args)
  local hp = ctx.player:get("hp") or MAX_HP
  hp = math.min(MAX_HP, hp + heal_amount(ctx.player:get("level") or 1))
  ctx.player:set("hp", hp)
  return { hp = hp }
end

The API in Lua

Call methods with :. The . form (ctx.player.get("hp")) also works, so you cannot get it wrong.

Lua What it does
ctx.player.id ID of the calling player.
ctx.player:get(key) Read a Player Property, or nil. Use or for a default: ctx.player:get("gold") or 0.
ctx.player:set(key, value) Write a Player Property.
ctx.player:delete(key) Remove a Player Property.
ctx.player:has(key), ctx.player:keys() Check for a property, list property names.
ctx.players Array of everyone in the room (use ipairs). Each has id, get, set, delete, has and keys.
ctx.room:get / set / delete / has / keys Room Properties.
ctx.room:broadcast(event, data) Send an event to every player in the room.
ctx.room:state(player_id), ctx.room:state_at(player_id, time) A player's realtime state, now or at a recent server time.
ctx.global:get / set / delete / has / keys Global Properties shared by every room.
ctx.now Server time in milliseconds when the call started.
print(...), ctx:log(...) Write a line that shows up in test runs.
error(NetStackError(code, message)) Reject the call. fail(code, message) does the same.

get() returns a copy. Change the copy, then set() it back:

function run(ctx, args)
  local inventory = ctx.player:get("inventory") or json.array()
  local slot = nil
  for i, id in ipairs(inventory) do
    if id == args.itemId then slot = i break end
  end
  if not slot then
    error(NetStackError("ITEM_NOT_OWNED", "You do not own that item."))
  end
  table.remove(inventory, slot)
  ctx.player:set("inventory", inventory)
  ctx.room:broadcast("itemUsed", { playerId = ctx.player.id, itemId = args.itemId })
  return { remaining = #inventory }
end

Empty lists and json.array()

Lua has one kind of table, so an empty {} could mean an empty list or an empty object. NetStack sends and stores an empty {} as a JSON object. When you mean an empty list, use json.array() (or wrap an existing table: json.array(t)), so the property is saved as [] and your game client sees an array. Tables loaded from list properties keep being lists even after you remove every item.

json.encode(value) and json.decode(text) are available too.

Rejecting a call

Call error(NetStackError(code, message)) or fail(code, message). The caller receives the code and message, and none of the changes made so far are kept. Plain error("text") and runtime errors (such as indexing nil) are reported as FUNCTION_ERROR with the line number, which you can see in the Test run panel. pcall and error work as usual if you want to catch errors yourself.

function run(ctx, args)
  local amount = args.amount
  if math.type(amount) ~= "integer" or amount < 1 or amount > 100 then
    fail("BAD_AMOUNT", "Amount must be between 1 and 100.")
  end
  local gold = (ctx.player:get("gold") or 0) + amount
  ctx.player:set("gold", gold)
  return { gold = gold }
end

Working with other players

function run(ctx, args)
  local target = nil
  for _, p in ipairs(ctx.players) do
    if p.id == args.toPlayerId then target = p end
  end
  if not target then fail("PLAYER_NOT_IN_ROOM", "That player is not here.") end
  target:set("gold", (target:get("gold") or 0) + 5)
  return { ok = true }
end

What is supported

  • local variables (including <const>), functions, closures, varargs (..., select), multiple return values.
  • if, numeric and generic for, while, repeat ... until, break, and goto continue to skip to the next loop iteration.
  • Metatables (setmetatable, __index, __add and friends) for objects and classes.
  • The string library, including Lua patterns (string.match, gsub, gmatch, find, format), table (insert, remove, sort, concat, unpack), math, os.time and os.clock, pcall, error, tostring, tonumber, type, pairs, ipairs.

require, io, load, debug, coroutines and other goto targets are not available. You get a clear error with a line number if you use one.

Numbers

Integer and float division work as in Lua (7 // 2 is 3, 7 / 2 is 3.5), but all numbers are 64-bit floating point on the server, like JSON. Integers are exact up to 2^53, and integer overflow does not wrap around. Properties are stored as JSON, so 2.0 comes back as 2.

Limits

The same as every Function: 150 ms of CPU and 32 MB of memory per call, no network, filesystem or timers, and up to 20,000 characters of source. See Limits and plans.