← Back

Lua API Reference

Complete reference for the gamesense.cloud Lua scripting API. All modules follow the Starline convention — global tables with PascalCase function names. Entity functions transparently resolve controllers to pawns for CS2 compatibility.

globals

Timing and frame information from the Source 2 engine global variables.

globals.RealTime()number
Seconds since engine start (wall-clock time). Falls back to platform timer when not in-game.
globals.CurTime()number
Current server time in seconds. Pauses during loading screens.
globals.FrameTime()number
Time elapsed since the previous frame (delta time). Useful for frame-rate-independent logic.
globals.FrameCount()integer
Frame counter since engine start.
globals.TickCount()integer
Current server tick number.
globals.TickInterval()number
Seconds per tick (e.g. 1/64 for 64-tick). Returns 1/64 as fallback.
globals.MaxPlayers()integer
Maximum player slots (typically 64).
globals.MapName()string
Current map name (e.g. "de_dust2"). Empty string when not connected.
globals.IsConnected()boolean
Whether the client is connected to a server.

engine

Engine queries, view control, and console commands.

engine.GetLocalPlayer()userdata | 0
Returns the local player pawn as a lightuserdata pointer. Returns 0 if unavailable.
engine.GetMaxPlayers()integer
Maximum player count (64).
engine.GetMapName()string
Current map name.
engine.GetViewAngles()pitch, yaw, roll
Returns the local player's current view angles as three floats.
engine.SetViewAngles(pitch, yaw, roll)
Sets the local player's view angles.
engine.IsConnected()boolean
Whether connected to a server.
engine.IsInGame()boolean
Whether in an active game.
engine.ExecuteCommand(cmd: string)
Executes a console command (e.g. "say hello").
engine.GetScreenSize()width, height
Display resolution in pixels.
engine.WorldToScreen(x, y, z){x, y} | nil
Projects 3D world coordinates to 2D screen position. Returns a table or nil if behind camera.
engine.GetCurTime()number
Current server time.
engine.GetRealTime()number
Real wall-clock time.
engine.GetFrameTime()number
Frame delta time.
engine.GetTickRate()number
Server tick rate (e.g. 64.0).
engine.GetTickCount()integer
Current tick count.
engine.GetRoundPhase()string
Current round phase: "live", "freezetime", or "over". Updated automatically from game events (round_start, round_freeze_end, round_end).

entity

Entity access and queries. Indices 1–64 are player controllers in CS2 — this module transparently resolves them to pawns so scripts get position, health, and team data from the correct entity.

entity.GetLocalPlayer()userdata | nil
Local player pawn pointer.
entity.GetByIndex(index: integer)userdata | nil
Get entity by index. For indices 1–64, automatically resolves controller → pawn.
entity.GetPlayers()table
Returns a sequential table of all alive player pawns. Rebuilds the pawn↔controller map.
entity.GetHealth(ent)integer
Health points (0–100).
entity.GetArmor(ent)integer
Armor value.
entity.GetTeam(ent)integer
Team number: 2 = Terrorist, 3 = Counter-Terrorist.
entity.GetName(ent)string
Sanitized player name. Reads from the controller via reverse pawn→controller lookup.
entity.GetPosition(ent)x, y, z
World position (reads m_vOldOrigin from the pawn).
entity.GetEyePosition(ent)x, y, z
Eye position = origin + view offset.
entity.GetViewAngles(ent)pitch, yaw, roll
Eye angles (m_angEyeAngles).
entity.IsAlive(ent)boolean
True when m_lifeState == 0.
entity.IsDormant(ent)boolean
True if the entity is dormant (not being networked). Reads CGameSceneNode::m_bDormant. Also returns true for nil entities.
entity.GetBoundingBox(ent)x, y, w, h, alpha | nil
Screen-space bounding box. Accounts for crouching. Returns nil if off-screen.
entity.GetHitboxPosition(ent, hitbox: integer)x, y, z
Bone position for the given hitbox index (0–128). Reads from the scene node bone array.
entity.GetWeapon(ent)userdata | nil
Active weapon entity pointer (m_pClippingWeapon).
entity.GetWeaponName(ent)string
Designer name of the active weapon, with the weapon_ prefix stripped.
entity.GetController(pawn: userdata)userdata | nil
Reverse lookup: pawn → controller.
entity.GetPawn(controller)userdata | nil
Forward lookup: controller → pawn.
entity.IsEnemy(ent)boolean
True if the entity is on a different team than the local player.
entity.GetFlags(ent)integer
Entity flags (m_fFlags). Bit 1 = crouching.
entity.IsScoped(ent)boolean
Whether the player is scoped in.
entity.HasHelmet(ent)boolean
Whether the player has a helmet.
entity.HasDefuser(ent)boolean
Whether the player has a defuse kit.
entity.GetFlashDuration(ent)number
Flash duration in seconds.
entity.GetMoney(ent)integer
Current money via m_pInGameMoneyServices.
entity.GetColor(ent)integer
Competitive teammate color index: 0=blue, 1=green, 2=yellow, 3=orange, 4=purple. Returns -1 if unavailable.
entity.GetVelocity(ent)x, y, z
Current velocity vector (m_vecVelocity).
entity.GetSteamID(ent)integer
64-bit Steam ID from the controller. Returns 0 if unavailable.
entity.GetIndex(ent: userdata)integer
Entity slot index (1–64). Returns 0 if not found.
entity.GetPropInt(ent, class: string, field: string)integer
Read any integer schema field. Example: entity.GetPropInt(ent, "C_BaseEntity", "m_iHealth")
entity.GetPropFloat(ent, class: string, field: string)number
Read any float schema field.
entity.GetPropBool(ent, class: string, field: string)boolean
Read any boolean schema field.
entity.GetPropVec3(ent, class: string, field: string)x, y, z
Read any Vector schema field. Returns three floats.
entity.GetPropString(ent, class: string, field: string)string
Read any string (pointer-to-char) schema field. Returns empty string on failure.
entity.GetEntityFromHandle(handle: integer)entity | nil
Resolve an entity handle (e.g. from GetPropInt on m_hActiveWeapon or m_hOwnerEntity) to an entity pointer. Returns nil if the handle is invalid.

Example — iterate enemies

local players = entity.GetPlayers()
for _, ply in ipairs(players) do
  if entity.IsEnemy(ply) and entity.IsAlive(ply) then
    local name = entity.GetName(ply)
    local hp   = entity.GetHealth(ply)
    local x, y, z = entity.GetPosition(ply)
    print(name .. " has " .. hp .. "hp at " .. x .. ", " .. y)
  end
end

Example — read custom netvar

local ent = entity.GetByIndex(1)
if ent then
  local kills = entity.GetPropInt(ent, "CCSPlayerController", "m_iKills")
  local ping  = entity.GetPropInt(ent, "CCSPlayerController", "m_iPing")
  print("Kills: " .. kills .. "  Ping: " .. ping)
end

renderer

2D rendering API. All drawing functions must be called inside a paint event handler. Colors can be Color() objects, {r, g, b, a} tables, or packed integers.

renderer.Line(x1, y1, x2, y2 [, color, thickness])
Draw a line between two points.
renderer.Rect(x, y, w, h [, color, rounding])
Draw a rectangle outline.
renderer.RectFilled(x, y, w, h [, color, rounding])
Draw a filled rectangle.
renderer.GradientRect(x, y, w, h [, colorA, colorB])
Draw a gradient-filled rectangle.
renderer.Circle(x, y, radius [, color, segments])
Draw a circle outline.
renderer.CircleFilled(x, y, radius [, color, segments])
Draw a filled circle.
renderer.Triangle(x1, y1, x2, y2, x3, y3 [, color])
Draw a triangle outline.
renderer.TriangleFilled(x1, y1, x2, y2, x3, y3 [, color])
Draw a filled triangle.
renderer.Polyline(points [, color, thickness])
Draw an open polyline. points is an array of {x, y} tables (minimum 3).
renderer.Polygon(points [, color, thickness])
Draw a closed polygon outline. points is an array of {x, y} tables (minimum 3).
renderer.PolygonFilled(points [, color])
Draw a filled convex polygon.
renderer.RoundedRect(x, y, w, h, rounding [, color])
Draw a rounded rectangle outline.
renderer.RoundedRectFilled(x, y, w, h, rounding [, color])
Draw a filled rounded rectangle.
renderer.Arc(cx, cy, radius, startAngle, endAngle [, color, segments, thickness])
Draw an arc outline. Angles are in radians.
renderer.ArcFilled(cx, cy, radius, startAngle, endAngle [, color, segments])
Draw a filled arc (pie shape).
renderer.Text(x, y, text [, color, size, font])
Draw text. Font can be "interface", "strong", "mono", or "display".
renderer.TextEx(x, y, text [, color, size, font, alignX, alignY])
Draw text with alignment. alignX is "left", "center", or "right". alignY is "top", "center", or "bottom".
renderer.MeasureText(text [, size, font])width, height
Measure text dimensions without drawing.
renderer.ScreenSize()width, height
Canvas dimensions.
renderer.WorldToScreen(x, y, z)sx, sy | nil
Project world position to screen. Returns two numbers or nil if behind camera.

Example — draw crosshair + info

events.On("paint", function()
  local w, h = renderer.ScreenSize()
  local cx, cy = w / 2, h / 2

  -- crosshair
  renderer.Line(cx - 8, cy, cx + 8, cy, Color(0, 255, 0, 200))
  renderer.Line(cx, cy - 8, cx, cy + 8, Color(0, 255, 0, 200))

  -- velocity display
  local me = entity.GetLocalPlayer()
  if me then
    local vx, vy, vz = entity.GetVelocity(me)
    local speed = math.floor(math.sqrt(vx*vx + vy*vy))
    renderer.Text(cx, cy + 20, speed .. " u/s",
      Color(255, 255, 255, 180), 14, "mono")
  end
end)

input

Keyboard and mouse state. Key codes are exposed as constants on the input table (e.g. input.KEY_A, input.MOUSE_LEFT, input.F1input.F12).

input.IsKeyDown(key: integer)boolean
True while the key is held.
input.IsKeyPressed(key: integer)boolean
True on the frame the key was first pressed.
input.IsKeyReleased(key: integer)boolean
True on the frame the key was released.
input.GetMousePos()x, y
Current mouse position in pixels.
input.GetMouseWheel()number
Mouse wheel delta this frame.
input.GetKeyName(key: integer)string
Human-readable key name.
input.IsMouseDown(button: integer)boolean
0 = left, 1 = right, 2 = middle. True while held.
input.IsMousePressed(button: integer)boolean
True on first press frame.
input.IsMouseReleased(button: integer)boolean
True on release frame.
input.GetMouseDelta()dx, dy
Mouse movement since last frame.

Key Constants

MOUSE_LEFT, MOUSE_RIGHT, MOUSE_MIDDLE, MOUSE_4, MOUSE_5, BACKSPACE, TAB, ENTER, SHIFT, CTRL, ALT, ESCAPE, SPACE, LEFT/RIGHT/UP/DOWN, KEY_0KEY_9, KEY_AKEY_Z, F1F12, INSERT, DELETE, HOME, END, PAGE_UP, PAGE_DOWN, CAPS_LOCK

ui

Tab / Group / Widget hierarchy for building script configuration UIs. Values persist automatically across script reloads.

ui.Tab(name: string)tab
Create a named tab. Returns a tab handle.
ui.GetValue(id: string)value
Get a control's current value by its ID.
ui.SetValue(id: string, value)
Set a control's value by its ID.

tab:Group(name) → group

Create a named group within a tab.

Group Widgets

group:Checkbox(label, default: boolean)control
Toggle switch.
group:SliderInt(label, min, max [, default])control
Integer slider.
group:SliderFloat(label, min, max [, default])control
Float slider.
group:Combo(label, options: table [, default_index])control
Dropdown selector. Index is 1-based.
group:Multiselect(label, options: table [, defaults: table])control
Multi-select dropdown. Returns a table of selected indices.
group:Button(label [, callback])control
Clickable button.
group:ColorPicker(label [, default: {r,g,b,a}])control
RGBA color picker (0–1 range).
group:Textbox(label [, default: string])control
Text input field.
group:Keybind(label [, default_key])control
Key binding selector.
group:Label(text)control
Static text label.
group:Separator([text])control
Visual divider. Optional text becomes a section heading.

Control Handle Methods

control:Get()value
Read current value.
control:Set(value)
Write a new value.
control:OnChange(callback)self
Register a value-change callback. Returns self for chaining.

Properties: .id, .kind, .label

Example — full UI setup

local tab = ui.Tab("Aim Helper")
local g = tab:Group("Settings")

local enabled = g:Checkbox("Enabled", true)
local fov     = g:SliderFloat("FOV", 1.0, 30.0, 5.0)
local style   = g:Combo("Style", {"Circle", "Cross", "Dot"}, 1)
local hotkey  = g:Keybind("Toggle Key", input.KEY_X)
local color   = g:ColorPicker("Color", {1, 0, 0, 1})

g:Separator("Info")
local status = g:Label("Status: idle")

enabled:OnChange(function(val)
  status:Set(val and "Status: active" or "Status: idle")
end)

g:Button("Reset Defaults", function()
  fov:Set(5.0)
  style:Set(1)
  color:Set({1, 0, 0, 1})
end)

events

Event subscription system with typed event names.

events.On(name: string, callback: function)handle: integer
Subscribe to an event. Returns a handle for unsubscription.
events.Off(handle: integer)boolean
Unsubscribe by handle. Returns true if the subscription was found.
events.List()table
List all declared events with name, summary, arguments, and listener count.

Constants

events.BUTTON_FORCE_OFF (0), events.BUTTON_TOGGLE (1), events.BUTTON_FORCE_ON (2)

Event Reference

Platform and engine events pass individual arguments to callbacks. CS2 game events pass a single table with the listed fields — e.g. function(e) print(e.userid) end.

Platform(individual args)
framedt: number
paint(none — draw here)
keykey: number, down: boolean
resizewidth: number, height: number
focusfocused: boolean
unload(none)
Engine(individual args)
createmovecmd: CUserCmd
movementcmd: CUserCmd
frame_stagestage: number
vote_setup(none)
edgebug(none)
jumpbug(none)
pixelsurf(none)
Round(table fields)
round_starte.timelimit: number
round_ende.winner, e.reason, e.message
round_freeze_end(none)
round_mvpe.userid, e.reason
begin_new_match(none)
announce_phase_end(none)
Player(table fields)
player_deathe.userid, e.attacker, e.headshot, e.distance, e.weapon, e.assistedflash, e.noscope, e.thrusmoke, e.penetrated, e.dominated, e.revenge, e.assister
player_hurte.userid, e.attacker, e.health, e.armor, e.dmg_health, e.dmg_armor, e.hitgroup, e.weapon
player_spawne.userid, e.team
player_disconnecte.userid, e.reason
item_purchasee.userid, e.team, e.weapon
Weapon(table fields)
weapon_firee.userid, e.weapon
bullet_impacte.userid, e.x, e.y, e.z
Bomb(table fields)
bomb_plantede.userid
bomb_defusede.userid
bomb_exploded(none)
Grenades(table fields)
flashbang_detonatee.userid, e.entityid, e.x, e.y, e.z
smokegrenade_detonatee.userid, e.entityid, e.x, e.y, e.z
hegrenade_detonatee.userid, e.x, e.y, e.z
inferno_startburne.entityid, e.x, e.y, e.z
inferno_expiree.entityid, e.x, e.y, e.z
decoy_startede.userid, e.entityid, e.x, e.y, e.z

Example — track kills

local myKills = 0

-- CS2 game events pass a single table with named fields
events.On("player_death", function(e)
  local me = entity.GetLocalPlayer()
  if me and e.attacker == entity.GetIndex(me) then
    myKills = myKills + 1
    cheat.Notify("Kill #" .. myKills .. " with " .. e.weapon .. "!")
    system.PlaySound("scripts/ding.wav")
  end
end)

events.On("round_start", function(e)
  myKills = 0
end)

-- Platform events pass individual arguments
events.On("key", function(key, down)
  if key == input.KEY_H and down then
    cheat.Notify("Kills this round: " .. myKills)
  end
end)

hooks

Named hook management — bridges hook names to the event system. Supports both PascalCase and snake_case hook names.

hooks.Add(hookName, uniqueId, callback)
Register a callback for a hook. Re-registering with the same hookName + uniqueId replaces the previous callback.
hooks.Remove(hookName, uniqueId)
Remove a previously registered hook callback.

Supported Hooks

CreateMoveMovementFrameStageNotifyPaint / DrawFrameKeyResizeFocusUnloadRoundStartRoundEndFreezeTimeEndRoundMVPBeginNewMatchAnnouncePhaseEndPlayerDeathPlayerHurtPlayerSpawnPlayerDisconnectItemPurchaseWeaponFireBulletImpactBombPlantedBombDefusedBombExplodedFlashbangDetonateSmokegrenadeDetonateHEGrenadeDetonateInfernoStartBurnInfernoExpireDecoyStartedVoteSetupEdgeBugJumpBugPixelSurf

Example — hooks.Add vs events.On

-- hooks.Add uses named IDs (can replace/remove by name)
hooks.Add("Paint", "my_watermark", function()
  renderer.Text(10, 10, "gamesense.cloud", Color(100, 200, 255), 16)
end)

-- remove later by name
hooks.Remove("Paint", "my_watermark")

-- events.On uses numeric handles
local h = events.On("paint", function()
  renderer.Text(10, 10, "hello", Color(255,255,255))
end)
events.Off(h)  -- remove by handle

esp

ESP override and custom element system. Store per-entity overrides, custom text, and custom bars that a renderer can consume.

esp.Override(entity_index, property, value)
Set a per-entity property override. Pass nil as value to clear. Supports string, number, color, and boolean values.
esp.CustomText(entity_index, position, text [, color])
Add custom text to an entity. Position is a string like "top" or "bottom". Cleared every frame — re-add in your paint handler.
esp.CustomBar(entity_index, position, value [, color])
Add a custom bar (0.0–1.0) to an entity. Cleared every frame — re-add in your paint handler.
esp.GetOverride(entity_index, property)value | nil
Read a previously set override.
esp.Clear()
Clear all stored ESP data for all entities.
esp.ClearEntity(entity_index)
Clear ESP data for one entity.

http

HTTP client via WinHTTP. Supports HTTPS. Requests are synchronous — use timer.After(0, fn) to avoid blocking paint. 10-second timeout.

http.Get(url [, callback])body | nil, error
GET request. With callback: callback(body, error). Without: returns body directly, or nil + error string.
http.Post(url, body [, callback [, content_type]])body | nil, error
POST request. Default content type is application/json.
http.Request({url, method, body, content_type}){status, body, ok, error}
Full-featured request. Returns a result table with status code, body, ok boolean, and optional error.

Example — fetch & post JSON

-- simple GET
local body, err = http.Get("https://api.example.com/data")
if body then
  local data = json.Decode(body)
  print("Got " .. #data .. " items")
end

-- POST JSON (non-blocking via timer)
timer.After(0, function()
  local payload = json.Encode({ name = cheat.GetUsername() })
  local res = http.Request({
    url = "https://api.example.com/submit",
    method = "POST",
    body = payload,
  })
  if res.ok then print("Submitted!") end
end)

cheat

Cheat identity, control, and utility functions.

cheat.GetCheatName()string
Returns "gamesense.cloud".
cheat.GetVersion()string
Build version string.
cheat.GetUsername()string
Current username.
cheat.IsLoaded()boolean
Always returns true.
cheat.Unload()
Queue the calling script for unload.
cheat.Reload()
Queue the calling script for reload.
cheat.Log(text: string)
Write to the internal journal.
cheat.SetClantag(tag: string)
Set the player's clan tag via console command.
cheat.Notify(text: string)
Show a notification message.
cheat.GetTimestamp()string
Local time as "YYYY-MM-DD HH:MM:SS".
cheat.FindExport(module: string, export: string)userdata | nil
Find a DLL export by module and name. Returns a lightuserdata pointer.
cheat.IsRadarActive()boolean
Whether the web radar is currently streaming data.
cheat.GetRadarURL()string | nil
The active web radar URL, or nil if radar is not running.
cheat.GetRadarStats()table
Returns { active, pushCount, failCount, avgLatency, playerCount, uptime } with live radar statistics. Works whether radar is active or not.

system

OS-level utilities — clipboard, timing, audio.

system.GetClipboard()string
Read clipboard text (UTF-8).
system.SetClipboard(text: string)
Write text to the clipboard.
system.GetTimestamp()integer
Unix timestamp (seconds since epoch).
system.GetTickCount()integer
Milliseconds since system boot (via GetTickCount64).
system.PlaySound(path: string)
Play a WAV file asynchronously.

math

Extended math utilities for angle and vector operations. Augments the standard Lua math table — all functions are accessed via math.AngleNormalize() etc.

math.AngleNormalize(angle: number)number
Normalize an angle to the range [-180, 180].
math.AngleDifference(a: number, b: number)number
Shortest angular difference between two angles.
math.VectorAngles(x, y, z)pitch, yaw
Convert a direction vector to Euler angles.
math.AngleVectors(pitch, yaw)fx, fy, fz
Convert Euler angles to a forward direction vector.
math.VectorLength(x, y, z)number
3D vector length.
math.VectorDistance(x1, y1, z1, x2, y2, z2)number
Distance between two 3D points.
math.Lerp(t, a, b)number
Linear interpolation: a + t * (b - a).
math.Clamp(value, min, max)number
Clamp value to [min, max].

json

JSON encoding and decoding. Both PascalCase and lowercase names are supported.

json.Decode(str: string)table | nil
Parse a JSON string into a Lua table. Returns nil on invalid input.
json.Encode(value: any [, pretty: boolean])string
Serialize a Lua value to JSON. Pass true as second arg for indented output.
json.Valid(str: string)boolean
Check whether a string is valid JSON without parsing it.

Aliases: json.decode, json.encode, json.valid

store

Per-script persistent key-value storage. Data is saved as JSON and survives script reloads.

store.get(key: string)value | nil
Read a stored value.
store.set(key: string, value: any)
Write a value. Pass nil to delete.
store.has(key: string)boolean
Check if a key exists.
store.remove(key: string)
Delete a key.
store.clear()
Delete all keys for this script.
store.keys()table
Return all stored keys as a sequential table.
store.save()
Force an immediate write to disk.

Example — persistent settings

-- load saved config or use defaults
local config = store.get("config") or {
  enabled = true,
  color = {255, 0, 0, 255},
  key = input.KEY_H,
}

-- update and save on change
events.On("key", function(key, down)
  if key == input.F2 and down then
    config.enabled = not config.enabled
    store.set("config", config)
    cheat.Notify("Toggled: " .. tostring(config.enabled))
  end
end)

file

Filesystem access sandboxed to the scripts root directory. All paths are relative to the root; attempts to escape via .. are rejected.

file.Read(path: string)string | nil
Read file contents as a string. Returns nil if the file doesn't exist.
file.Write(path: string, content: string)
Write a string to a file (creates or overwrites).
file.Append(path: string, content: string)
Append content to a file.
file.Exists(path: string)boolean
Check whether a path exists.
file.IsDirectory(path: string)boolean
True if the path is a directory.
file.Size(path: string)integer
File size in bytes (0 on error).
file.List(path: string)table
List filenames in a directory.
file.MakeDirectory(path: string)boolean
Create a directory (recursive). Returns success.
file.Remove(path: string)boolean
Delete a file. Returns success.
file.Root()string
Returns the scripts root directory path.

timer

Deferred execution and periodic tasks.

timer.After(delay: number, callback: function)handle: integer
Run a function once after delay seconds.
timer.Every(interval: number, callback: function)handle: integer
Run a function every interval seconds. Return false from the callback to stop.
timer.NextFrame(callback: function)handle: integer
Run a function on the next frame. Shortcut for timer.After(0, fn).
timer.Cancel(handle: integer)boolean
Cancel a timer by handle.
timer.Count()integer
Number of active timers for this script.

Example — periodic & one-shot

-- auto-save config every 30 seconds
timer.Every(30, function()
  store.save()
  return true  -- keep running (return false to stop)
end)

-- delayed notification
timer.After(3, function()
  cheat.Notify("Script loaded!")
end)

-- do something next frame (avoids blocking paint)
timer.NextFrame(function()
  http.Get("https://example.com/check")
end)

log

Logging API. print() is redirected to log.info, so standard Lua prints appear in the console.

log.debug(...)
Log at debug level. Arguments are joined with tabs.
log.info(...)
Log at info level.
log.warn(...)
Log at warning level.
log.error(...)
Log at error level.
log.write(level: string, ...)
Log at a runtime-selected level. Level must be "debug", "info", "warn", or "error".

ffi

LuaJIT-compatible FFI subset for calling Windows API functions directly from Lua. Works on x64 Windows — all calling conventions collapse to Microsoft x64 ABI.

ffi.cdef(declaration: string)
Compatibility stub — accepts C declarations but does not parse them.
ffi.new(ctype: string [, size])cdata
Allocate a typed buffer. Supports array syntax: "char[4096]", "int[?]" (VLA — pass size as second arg).
ffi.cast(ctype: string, value)integer
Cast a value to a raw integer (pointer-sized).
ffi.string(cdata [, len])string
Read a C string from a cdata buffer or pointer.
ffi.sizeof(ctype | cdata)integer
Size in bytes of a type or cdata object.
ffi.copy(dst, src [, len])
Copy bytes between cdata buffers or from a Lua string.
ffi.fill(dst, len [, byte])
Fill a cdata buffer with a byte value (default 0).
ffi.load(library: string)table
Load a DLL and return a table whose fields resolve to exports on access.
ffi.typeof(cdata)string
Returns the C type name of a cdata object as a string.
ffi.gc(cdata, finalizer)cdata
Associates a finalizer function with a cdata object. The finalizer is called when the cdata is garbage-collected. Pass nil to remove the finalizer.
ffi.abi(param: string)boolean
Query ABI info. Returns true for "win", "64bit", and "le".

ffi.C

Auto-resolving table of system library exports. Access any function from kernel32, user32, advapi32, ntdll, ws2_32, shell32, gdi32, ole32, msvcrt, winhttp, or crypt32 directly:

local result = ffi.C.MessageBoxA(0, "Hello", "Title", 0)

CData Object

Indexable buffer with bounds checking. Supports [index] read/write (0-based), #cdata for total size in bytes, and tostring().

Example — Windows API via ffi

-- allocate a buffer and call GetModuleFileNameA
local buf = ffi.new("char[260]")
ffi.C.GetModuleFileNameA(0, buf, 260)
print("Exe: " .. ffi.string(buf))

-- load a DLL and call an export
local ntdll = ffi.load("ntdll")
local ticks = ntdll.NtGetTickCount()
print("Ticks: " .. ticks)

-- MessageBox popup
ffi.C.MessageBoxA(0, "Hello from Lua!", "gscloud", 0)

cvar

Console variable access — read and write cvars directly.

cvar.GetInt(name: string)integer
Read cvar as integer.
cvar.GetFloat(name: string)number
Read cvar as float.
cvar.GetString(name: string)string
Read cvar as string.
cvar.SetInt(name: string, value: integer)
Write integer value.
cvar.SetFloat(name: string, value: number)
Write float value.
cvar.SetString(name: string, value: string)
Write string value via console command buffer.
cvar.Find(name: string)userdata | nil
Get raw ConVar pointer for advanced use.

tracestub

Ray tracing queries. Currently returns default results (no hit, fraction 1.0). The API signature is stable — implementations will be added when the engine trace interface is hooked.

trace.Line(from_x, from_y, from_z, to_x, to_y, to_z [, skip_ent, mask])TraceResult
Cast a ray between two points.
trace.Hull(from_x, from_y, from_z, to_x, to_y, to_z [, mins, maxs, skip_ent, mask])TraceResult
Cast a swept box between two points.
trace.Bullet(from_ent, to_ent){damage, hit}
Simulate a bullet trace between two entities.

TraceResult

{ fraction, hit, entity, hitpos = {x,y,z}, normal = {x,y,z} }

panoramastub

Panorama UI scripting bridge. Currently a no-op — requires hooking the Panorama JS engine.

panorama.Execute(code: string)
Execute Panorama JavaScript code.
panorama.Listen(event: string, callback: function)handle: integer
Listen for a Panorama event. Currently returns 0.

Types

Global constructors for common value types. These are available without a module prefix.

Color(r, g, b [, a])

RGBA color (0–255). Default alpha is 255.

Methods: :r(), :g(), :b(), :a() — getters

Methods: :SetR(v), :SetG(v), :SetB(v), :SetA(v) — setters

Supports tostring(): "Color(255, 0, 0, 255)"

Vector(x, y, z)

3D vector with full arithmetic.

Methods: :x(), :y(), :z()

:Length(), :Length2D(), :Dot(other), :Cross(other), :Normalized()

Operators: +, -, * (scalar), ==

QAngle(pitch, yaw, roll)

Euler angle triplet.

Methods: :pitch(), :yaw(), :roll()

Supports tostring().

Pointer(address)

Raw memory pointer with SEH-safe read/write operations.

:GetAddress() — returns the raw address as an integer

:IsValid() — true if address ≠ 0

Read: :ReadByte(off), :ReadShort(off), :ReadInt(off), :ReadInt64(off), :ReadFloat(off), :ReadDouble(off), :ReadPointer(off)

Write: :WriteByte(off, val), :WriteInt(off, val), :WriteFloat(off, val)

:Add(offset) — returns a new Pointer at address + offset

Quick Start Examples

ESP Script

-- Create a UI tab with controls
local tab = ui.Tab("My Script")
local grp = tab:Group("Settings")
local enabled = grp:Checkbox("Enable ESP", true)
local color = grp:ColorPicker("Box Color", {1, 0, 0, 1})

-- Draw ESP boxes on paint
hooks.Add("Paint", "my_esp", function()
  if not enabled:Get() then return end

  local players = entity.GetPlayers()
  for _, ply in ipairs(players) do
    if entity.IsEnemy(ply) and entity.IsAlive(ply) then
      local x, y, w, h = entity.GetBoundingBox(ply)
      if x then
        renderer.Rect(x, y, w, h, color:Get())
        local name = entity.GetName(ply)
        renderer.Text(x, y - 12, name, {255,255,255,255}, 11)
      end
    end
  end
end)

HUD Overlay with Stats

local tab = ui.Tab("HUD")
local g   = tab:Group("Display")
local showSpeed = g:Checkbox("Show Speed", true)
local showClock = g:Checkbox("Show Clock", true)

local kills = 0

events.On("player_death", function(e)
  local me = entity.GetLocalPlayer()
  if me and e.attacker == entity.GetIndex(me) then
    kills = kills + 1
  end
end)

events.On("round_start", function(e)
  kills = 0
end)

events.On("paint", function()
  local w, h = renderer.ScreenSize()
  local y = 60

  -- kill counter
  renderer.RectFilled(w - 140, y, 130, 28, Color(0, 0, 0, 150), 4)
  renderer.Text(w - 130, y + 6, "Kills: " .. kills,
    Color(255, 80, 80), 14, "strong")
  y = y + 34

  -- speedometer
  if showSpeed:Get() then
    local me = entity.GetLocalPlayer()
    if me then
      local vx, vy = entity.GetVelocity(me)
      local speed = math.floor(math.sqrt(vx*vx + vy*vy))
      renderer.RectFilled(w - 140, y, 130, 28, Color(0, 0, 0, 150), 4)
      renderer.Text(w - 130, y + 6, speed .. " u/s",
        Color(200, 220, 255), 14, "mono")
      y = y + 34
    end
  end

  -- clock
  if showClock:Get() then
    renderer.RectFilled(w - 140, y, 130, 28, Color(0, 0, 0, 150), 4)
    renderer.Text(w - 130, y + 6, cheat.GetTimestamp(),
      Color(180, 180, 180), 11, "mono")
  end
end)