Cookbook
Short, complete answers to common tasks. Each recipe is a whole main.luau or a piece you can paste into one. The names are explained in the API reference.
Commands and settings
A command with arguments and a setting
local reward = cs.cvar("bounty_reward", "500", { help = "Money for the bounty", min = 0, max = 16000 })
cs.command("bounty", function(player, args)
local amount = tonumber(args[1]) or reward:int()
cs.reply(player, "The bounty is $" .. amount)
end, { help = "bounty [amount]" })
An admin command that targets a player
-- Finds one connected player whose name holds the text (any case).
local function find(text: string): Player?
local found = nil
for _, p in cs.players() do
if p.name:lower():find(text:lower(), 1, true) then
if found then
return nil -- more than one: be precise
end
found = p
end
end
return found
end
cs.command("freeze", function(admin, args)
local p = args[1] and find(args[1])
if not p then
cs.reply(admin, "freeze <name>: no single player matches")
return
end
if admin and not admin:can_target(p) then
cs.reply(admin, "You cannot target " .. p.name)
return
end
p:freeze(true)
cs.after(5, function()
if p.connected then
p:freeze(false)
end
end)
cs.chat(nil, "{red}" .. p.name .. "{default} is frozen for 5 seconds")
end, { admin = true, help = "freeze <name>" })
admin = true lets only admins whose admins.toml entry allows freeze run it. Player:slay, Player:slap, Player:kick and Player:ban work the same way.
A key bind
Commands starting with + and - are a key's press and release: players bind them (bind mouse3 +hook).
cs.command("+hook", function(player) if player then player:data().hooking = true end end)
cs.command("-hook", function(player) if player then player:data().hooking = false end end)
Players
Give weapons when players spawn
cs.on("player_equip", function(ev)
ev:block() -- no knife and pistol from the game
end, { before = true })
cs.on("player_spawn", function(ev)
local p = ev.player
p:give("weapon_knife")
p:give("weapon_deagle", { ammo = 35 })
p:give("item_assaultsuit")
end)
Respawn the dead after a moment
cs.on("player_killed", function(ev)
local p = ev.player
cs.after(2, function()
if p.connected and not p.alive and (p.team == "t" or p.team == "ct") then
p:respawn()
end
end, { player = p })
end)
For a whole mode with respawns, cs.register_mode with respawn = 2 does this for you (see Modes).
Money for each kill
cs.on("player_killed", function(ev)
local killer = ev.attacker and ev.attacker.player
if killer and killer ~= ev.player then
killer.money = math.min(16000, killer.money + 300)
cs.chat(killer, "{green}+$300{default} for killing " .. ev.player.name)
end
end)
Low gravity, speed and auto bunny hop
cs.command("moon", function(player)
if not player then return end
player.gravity = 0.4
player:set_movement({ auto_bhop = true, bhop_cap = 0 })
end)
Movement settings travel to the player's game, so its prediction stays exact. player:reset_movement() gives the server's settings back.
Slides that do not stop on a ramp's seams
cs.on("player_spawn", function(ev)
ev.player:set_movement({ ramp_fix = true })
end)
On maps whose slide ramps are built from several brushes, a fast slide can stop dead on a seam. ramp_fix lets the player slide on; walls, floors and pixel surf are left alone.
Remember something about a player during the game
cs.on("player_killed", function(ev)
local killer = ev.attacker and ev.attacker.player
if killer then
local d = killer:data()
d.streak = (d.streak or 0) + 1
if d.streak == 5 then
cs.chat(nil, "{green}" .. killer.name .. "{default} is on a rampage!")
end
end
ev.player:data().streak = 0
end)
player:data() is gone when the player leaves or the map changes.
Keep a player's preference for good
local prefs = cs.store("prefs") -- plugin_data/<plugin>/prefs.store
cs.command("sounds", function(player, args)
if not player then return end
local on = args[1] ~= "off"
prefs:set(player.id .. ":sounds", on)
cs.reply(player, "Sounds " .. (if on then "on" else "off"))
end)
local function wants_sounds(p: Player): boolean
return prefs:get(p.id .. ":sounds") ~= false -- on unless turned off
end
Key it by player.id, the player's permanent ID; a name can change.
The HUD
A notice
cs.notify(nil, "The bomb zone is closed", {
title = "Warning", kind = "warning", position = "top_right", duration = 6,
})
A countdown and a bar that stay on screen
cs.hud_widget(nil, "round_clock", { kind = "timer", seconds = 60, label = "Escape", x = 0.5, y = 0.08, align = "center" })
local function show_power(p: Player, power: number)
cs.hud_widget(p, "power", { kind = "bar", x = 0.02, y = 0.9, w = 200, h = 12, value = power, max = 100,
color = "#e8a33a", back = "#00000080", label = "Power" })
end
-- later: cs.hud_remove(nil, "round_clock")
A widget with the same id is changed in place.
A menu
cs.command("guns", function(player)
if not player then return end
cs.menu(player, "Choose a weapon", { "AK-47", "M4A1", "AWP" }, function(p, key)
local guns = { "weapon_ak47", "weapon_m4a1", "weapon_awp" }
if guns[key] and p.alive then
p:give(guns[key])
end
end)
end)
A window with buttons
cs.command("vote", function(player)
if not player then return end
cs.window(player, "vote", {
title = "Next map?",
size = { 420, 180 },
body = { kind = "row", gap = 12, children = {
{ kind = "button", id = "de_dust2", text = "Dust 2", key = 1, grow = 1 },
{ kind = "button", id = "de_inferno", text = "Inferno", key = 2, grow = 1 },
} },
})
end)
cs.on_window("vote", function(p, ev)
if ev.kind == "click" then
cs.chat(nil, p.name .. " votes for " .. ev.id)
cs.window_close(p, "vote")
end
end)
(docs/plugin_windows.md has every element. cs_plugin new shop --template shop makes a whole shop to start from.)
Pictures on the loading screen
The pictures go in the plugin's content/ folder (PNG or JPG, at most 1920x1080):
cs.loading_screen({ images = { "myserver/welcome.jpg", "myserver/rules.jpg" }, seconds = 8 })
Texts in the players' languages
lang/en.toml:
welcome = "Welcome, {name}!"
lang/es.toml:
welcome = "¡Bienvenido, {name}!"
cs.on("player_join", function(ev)
cs.chat(ev.player, ev.player:t("welcome", { name = ev.player.name }))
end)
Effects and sounds
An explosion that hurts
local function blast(at: vector, by: Player?)
cs.explosion(nil, at, { scale = 3 })
cs.decal(nil, at - vector.create(0, 0, 8), "{scorch1")
cs.radius_damage(at, 120, 300, { attacker = by and by.entity })
for _, p in cs.players() do
if p.alive and vector.magnitude(p.origin - at) < 600 then
p:shake({ amplitude = 8, duration = 1 })
end
end
end
A beam between two players
cs.beam(nil, alice.entity, bob.entity, { color = "#00aaff", width = 20, life = 2 })
Music when a round starts
cs.on("map_start", function()
cs.precache("media/round.mp3")
end)
cs.on("round_start", function()
for _, p in cs.players() do
p:play_music("media/round.mp3")
end
end)
Put media/round.mp3 in the plugin's content/ folder: players download it.
Rounds and rules
Headshots only
cs.on("player_trace_attack", function(ev)
if ev.hit_group ~= 1 then
ev:block()
end
end, { before = true })
Double damage with knives
cs.on("player_damage", function(ev)
local attacker = ev.attacker and ev.attacker.player
if attacker and attacker.weapon == "weapon_knife" then
ev.damage *= 2
end
end, { before = true })
Change who wins a round
-- When time runs out on a bomb map, call it a draw instead of a CT win.
cs.on("round_end", function(ev)
if ev.reason == "target_saved" then
ev.reason = "draw"
end
end, { before = true })
Change the buy menu
Items go by the id players type to buy them (awp, hegren, vesthelm; cs.buy_items() lists them).
cs.set_buy_item("awp", { enabled = false })
cs.set_buy_item("hegren", { price = 150 })
cs.register_buy_item("medkit", {
name = "Medkit", price = 800, group = "equipment",
buy = function(p) p.health = math.min(100, p.health + 50) end,
})
A shop window instead of the buy menu
cs.on("buy_menu", function(ev)
if ev.menu ~= "buy" then return end
ev:block()
cs.window(ev.player, "shop", {
title = "Shop",
body = { kind = "grid", columns = 2, children = {
{ kind = "slot", id = "weapon_ak47", name = "AK-47", price = 2700, key = 1 },
{ kind = "slot", id = "weapon_m4a1", name = "M4A1", price = 3100, key = 2 },
} },
})
end, { before = true })
cs.on_window("shop", function(p, ev)
local prices = { weapon_ak47 = 2700, weapon_m4a1 = 3100 }
local price = prices[ev.id]
if ev.kind == "click" and price and p.can_buy and p.money >= price then
p.money -= price
p:give(ev.id)
cs.window_close(p, "shop")
end
end)
A game mode
cs.register_mode("arena", {
title = "Knife arena",
off = { "buying" },
respawn = 1,
objectives = false,
start = function() cs.chat(nil, "{green}Knife arena!{default} Knives only.") end,
})
cs.on("player_equip", function(ev)
if cs.game.mode == "arena" then
ev:block()
ev.player:give("weapon_knife")
end
end, { before = true })
cs.on("plugin_start", function()
cs.set_mode("arena")
end)
The tutorial builds a full mode step by step.
A map vote
cs.command("rtv", function()
if cs.vote_running() then return end
local maps = { "de_dust2", "de_inferno", "de_nuke" }
cs.vote("Next map", maps, function(results)
if results.option then
cs.chat(nil, "Next map: {green}" .. results.option)
cs.change_map(results.option, 5)
end
end)
end)
Bots
Fill the server with the game's bots
cs.on("map_start", function()
cs.after(5, function()
for _ = 1, 3 do
cs.add_game_bot({ team = "t", difficulty = "hard" })
cs.add_game_bot({ team = "ct", difficulty = "hard" })
end
end)
end)
cs.add_bot makes a different kind of bot: one your plugin moves itself (replays, dummies), with no AI.
The world
A pickup that heals
cs.register_entity("health_pack", {
model = "models/health_pack.mdl", -- in the plugin's content/ folder
mins = vector.create(-8, -8, 0), maxs = vector.create(8, 8, 16),
solid = "trigger",
touch = function(self: Entity, other: Entity)
local p = other.player
if p and p.alive and p.health < 100 then
p.health = math.min(100, p.health + 25)
self:remove()
end
end,
})
-- Maps may place it (classname "health_pack"); code too:
-- cs.create_entity("health_pack", { origin = somewhere })
Find entities
cs.command("doors", function(player)
for _, door in cs.find_entities({ class = "func_door" }) do
door:use() -- toggles it
end
if player then
local near = cs.find_entities({ near = player.origin, radius = 200 })
cs.reply(player, #near .. " entities within 200 units of you")
end
end, { admin = true })
Change a map's entities when it loads
-- No weapons lying on the floor, on every map.
cs.patch_map(function(map: string, entities: { { [string]: string } })
for i = #entities, 2, -1 do -- (the first is the world)
if entities[i].classname == "armoury_entity" then
table.remove(entities, i)
end
end
end)
Data and services
Statistics in SQLite
local db = cs.database("kills")
db:query_now("CREATE TABLE IF NOT EXISTS kills (id TEXT PRIMARY KEY, name TEXT, n INTEGER NOT NULL DEFAULT 0)")
cs.on("player_killed", function(ev)
local k = ev.attacker and ev.attacker.player
if k and not k.bot then
db:query("INSERT INTO kills (id, name, n) VALUES (?, ?, 1) ON CONFLICT(id) DO UPDATE SET n = n + 1, name = excluded.name",
{ k.id, k.name })
end
end)
cs.command("top", function(player)
db:query("SELECT name, n FROM kills ORDER BY n DESC LIMIT 5", nil, function(r)
if not r.ok then return end
for i, row in r.rows do
cs.reply(player, i .. ". " .. row.name .. " " .. row.n)
end
end)
end)
The queries run on a background thread, so a slow disk never stalls the game.
Post to a web hook
In plugin.toml: hosts = ["discord.com"].
local url = cs.cvar("report_webhook", "", { help = "The web hook URL for reports" })
cs.command("report", function(player, args)
if not player or url.value == "" then return end
cs.http(url.value, {
method = "POST",
headers = { ["content-type"] = "application/json" },
body = cs.json_encode({ content = player.name .. " reports: " .. args.line }),
}, function(res)
cs.reply(player, if res.ok then "Report sent" else "Could not send the report")
end)
end)
Plugins working together
Offer a function, use it elsewhere
economy/main.luau:
local balance: { [string]: number } = {}
cs.export("add", function(id: string, amount: number): number
balance[id] = (balance[id] or 0) + amount
return balance[id]
end)
shop/plugin.toml: depends = ["economy"]. shop/main.luau:
local add = cs.import("economy", "add")
cs.command("daily", function(player)
if player then
cs.reply(player, "You now have " .. add(player.id, 100) .. " coins")
end
end)
Events of your own
-- in "races": tell everyone who listens
cs.emit("finished", player.id, seconds)
-- in any other plugin:
cs.on("races:finished", function(id: string, seconds: number)
cs.log(id .. " finished in " .. seconds)
end)
Testing
A test with players and bots
local test = require("test")
test.case("a kill is announced to the killer", function(t)
local alice = t:client("Alice", { team = "t" })
local bot = t:bots(1, "ct")[1]
bot.entity:damage(500, { attacker = alice.player.entity })
alice:expect_text("for killing " .. bot.name)
end)
Run it with cs_plugin test <folder>; Tools lists everything the test context offers.