Skip to content

Lua API

github-actions[bot] edited this page Dec 6, 2026 · 1 revision

GridLock Lua 5.1 / LuaJIT gl.* API Reference

GridLock ships an optional Tier-2 scripting host (plugins/gridlock_lua/libgridlock_lua.so, configured via -Dlua=auto|enabled|disabled) compiled strictly against the pure-C99 v2.0 ABI. Core gridlock has zero liblua dependency, and every gl.* symbol below is verified continuously against the live Lua runtime by test_lua_api_doc_coverage.

See also: Plugin API v2.0 Hub · C99 ABI Reference · C++23 Plugin Guide · Using Plugins


1. Startup, package.path, Watchdog & Sandboxing

  • Init Scripts: Loads <config-dir>/init.lua (default ~/.config/gridlock/init.lua, overridden by --config-dir or GRIDLOCK_CONFIG_DIR), installed <config-dir>/plugins/<name>/init.lua, and optional <workspace>/.gridlock/init.lua / <workspace>/.gridlock/plugins/<name>/init.lua.
  • Offline LuaRocks (Zero Networking): Prepends <config-dir>/lua/?.lua, <config-dir>/data/luarocks/share/lua/<abi>/?.lua, and <config-dir>/data/luarocks/lib/lua/<abi>/?.so (matching 5.1 for LuaJIT or 5.4 for PUC Lua) and runs pcall(require, "luarocks.loader").
  • Instruction-Count Watchdog: Every lua_pcall runs under a 1,000,000-instruction lua_sethook timeout guard so infinite loops never freeze the IDE.
  • Untrusted Workspace Sandbox: Workspace .gridlock/init.lua scripts execute in a restricted environment stripping os.execute, os.remove, os.rename, io.popen, and package.loadlib unless the workspace is explicitly trusted.
  • Hot Reload: Run Reload Lua Configuration (lua.reload_init) from the Command Palette (Ctrl+Shift+P), or iterate live in the PLAYGROUND sidebar (Ctrl+Shift+R).

2. gl.api & gl.core (Core Host Paths, Logging & Deferred Timers)

gl.core points to the exact same table as gl.api, so every entry below is exposed under both namespaces:

gl.api Symbol gl.core Alias Signature / Parameters Return / Behavior
gl.api.abi_version gl.core.abi_version Constant string "5.1" (LuaJIT / Lua 5.1 ABI) or "5.4" (PUC Lua 5.4 ABI).
gl.api.log gl.core.log ([level], msg) where level is "trace" | "debug" | "info" | "warn" | "error" (defaults to "info" when called as log(msg)) Emits ANSI/OSC-sanitized workstation log. Returns nothing.
gl.api.config_dir gl.core.config_dir () Returns active config directory string (--config-dir aware).
gl.api.data_dir gl.core.data_dir () Returns plugin data directory string.
gl.api.workspace_root gl.core.workspace_root () Returns active workspace root directory string.
gl.api.is_workspace_trusted gl.core.is_workspace_trusted () Returns boolean workspace SHA-256 trust state.
gl.api.defer_fn gl.core.defer_fn (delay_ms, fn) or (fn, [delay_ms]) (delay_ms >= 0) Schedules one-shot fn() on the Qt GUI thread after delay_ms ms under the watchdog; cancelled automatically on unload/reload. Returns boolean.
gl.api.defer gl.core.defer (delay_ms, fn) or (fn, [delay_ms]) Shorthand alias for gl.api.defer_fn / gl.core.defer_fn. Returns boolean.

3. gl.buf (Direct BufferEngine & AnchorStore Bridge)

All gl.buf operations read and mutate BufferEngine (PieceTable + AnchorStore) directly—with zero shadow text copies.

Symbol Signature / Parameters Return / Behavior
gl.buf.open_buffer (uri, [title], [opts]) (title defaults to uri; opts = { readonly = bool, scratch = bool, focus = bool } or numeric GRIDLOCK_BUF_FLAG_*) Opens or focuses a virtual buffer (gridlock://...) and returns integer buf_id (or nil).
gl.buf.open_virtual (uri, [title], [opts]) Alias for gl.buf.open_buffer. Returns integer buf_id (or nil).
gl.buf.close_buffer (buf_id) Closes virtual buffer buf_id. Returns boolean.
gl.buf.active () Returns active editor buf_id (0 when none).
gl.buf.line_count (buf_id) Returns total line count of buf_id.
gl.buf.get_lines (buf_id, [start_0], [end_0]) Returns 1-indexed Lua array of lines in 0-based half-open slice [start_0, end_0) (end_0 = -1 reads through EOF).
gl.buf.set_lines (buf_id, start_0, end_0, lines) Replaces 0-based line slice [start_0, end_0) in BufferEngine (PieceTable) with lines array and repaints attached EditorViewport panes immediately. Returns boolean.
gl.buf.get_cursor (buf_id) Returns line_1, col_0 (1-based line, 0-based UTF-8 byte column).
gl.buf.set_cursor (buf_id, line_1, [col_0]) Moves cursor to 1-based line_1 and 0-based col_0 (default 0). Returns boolean.
gl.buf.create_namespace (name) Creates or retrieves extmark namespace ID ns_id (or nil).
gl.buf.set_extmark (buf_id, ns_id, desc) where desc = { id, line, col, sign_text, sign_hl, virt_text, virt_text_hl, virt_lines, line_hl, virt_text_pos = "eol" | "overlay" } (line is 1-based; virt_lines is an array of virtual lines of { { text, hl_group }, ... } chunks rendered below line without mutating PieceTable) Adds or updates an AnchorStore extmark (and optional multi-line virt_lines block) and returns integer extmark_id (or nil).
gl.buf.clear_namespace (buf_id, ns_id) Clears all extmarks in ns_id on buf_id. Returns boolean.

4. gl.keymap & gl.autocmd

Symbol Signature / Parameters Return / Behavior
gl.keymap.register_command (id, title, fn, [desc]) Registers a command in Command Palette (Ctrl+Shift+P) and Tools -> Plugins. Returns boolean.
gl.keymap.set (mode, lhs, rhs, [opts]) (mode: "global" | "normal" | "insert" | "visual" | "debug"; rhs: command ID string or function(); opts: { buffer, args, desc, silent, nowait }) Binds single key or multi-key chord ("<leader>mr", "C-c m r"). Returns boolean.
gl.keymap.del (mode, lhs, [buffer_id]) Removes a keymap binding. Returns boolean.
gl.autocmd.create (event, fn_or_opts) (function(ev) or { pattern = "*", group = "...", priority = 0, once = false, callback = function(ev) }) Subscribes to event and returns integer handle (or nil).
gl.autocmd.delete (handle) Unsubscribes handle. Returns boolean.
gl.editor.vim_mode ([enabled]) (omit enabled to query; pass boolean true or false to update editor.vim_mode and synchronize open source editors) Queries or toggles Vim Modal Editing. Returns current boolean state.

Supported autocmd events: "BufReadPost", "BufWritePre" (vetoable: return true or set ev.veto = true to cancel), "BufWritePost", "CursorMoved", "ModeChanged", "BuildFinished", "ThemeChanged", "DebugLaunchPre" (vetoable: return true or set ev.veto = true), "DebugSessionStart", "RankStopped", "BreakpointHit", "FinalizeDetected".

Callback event table ev fields: { event, buffer_id, file, line, col, old_mode, new_mode, exit_code, theme_id, is_dark_theme, rank_id, rank_count, reason, veto }.


5. gl.dbg & gl.mpi (Debugger, Expressions, Tracepoints & Async GDB/MI)

gl.mpi points to the exact same table as gl.dbg, so every debugger and multi-rank symbol below is available under both gl.dbg.* and gl.mpi.*:

gl.dbg Symbol gl.mpi Alias Signature / Parameters Callback / Return
gl.dbg.active_rank gl.mpi.active_rank () Integer focused MPI rank ID (0-based).
gl.dbg.rank_count gl.mpi.rank_count () Integer total rank count (0 when idle).
gl.dbg.rank_state gl.mpi.rank_state (rank) (rank: integer) State string ("stopped", "running", "idle", etc.) or nil.
gl.dbg.eval gl.mpi.eval (expr, [rank]) (expr: C/C++/Fortran expression string; rank defaults to active_rank()) Evaluates expr on rank and returns { value = string, number = number|nil, error = string|nil }. number is populated when value parses as a finite scalar; error is nil on GRIDLOCK_OK.
gl.dbg.add_breakpoint gl.mpi.add_breakpoint (target, [opts]) (target: "file.cpp:42" or symbol "MPI_Allreduce"; opts = { condition, log_expr, rank, auto_continue, on_hit = function(rank, ctx) }) Installs a line, symbolic (-break-insert -f), or non-stopping tracepoint/logpoint and returns integer bp_id (or nil). auto_continue defaults to true when log_expr is non-empty; ctx = { file, line, reason, log_value }.
gl.dbg.event_points gl.mpi.event_points () Returns a 1-indexed array of all registered EventPointRegistry items { id = int, code = string, type = string, target = string, scope = string, condition = string, enabled = bool, hits = int } across breakpoints, watchpoints, catchpoints, tracepoints, and MPI events.
gl.dbg.add_event_point gl.mpi.add_event_point (spec) ({ type = "source"|"symbolic"|"watchpoint"|"catchpoint"|"tracepoint"|"mpi"|"timepoint", target = string, condition = string, scope = string, log = string, suspend = bool, checkpoint = bool, capture_stack = bool }) Registers a unified event point in EventPointRegistry (supporting non-stopping tracepoints, timepoints, and event-triggered CoW checkpoints) and returns the assigned integer event-point ID.
gl.dbg.timepoints gl.mpi.timepoints () Returns a 1-indexed array of registered EventPointType::Timepoint metrics { id = int, code = string, start_target = string, end_target = string, samples = int, min_ms = number, avg_ms = number, max_ms = number, skew_pct = number, per_rank = { { rank = int, last_ms = number, min_ms = number, avg_ms = number, max_ms = number, samples = int }, ... } } computed by TimepointTracker.
gl.dbg.send_mi_async gl.mpi.send_mi_async (rank, mi_cmd, [cb]) Dispatches tokenized async MI command; invokes cb(res) on GUI thread with res = { ok, status, status_code, rank, raw, value, memory, begin, contents } (leading numeric MI token stripped). Returns boolean.
gl.dbg.read_register gl.mpi.read_register (rank, reg_name, [cb]) (e.g. "rsp", "$rsp", "rip", "rdi") Evaluates -data-evaluate-expression "(unsigned long long)$<reg>"; res.value holds the numeric register value string when res.ok == true. Returns boolean.
gl.dbg.read_memory gl.mpi.read_memory (rank, addr, byte_len, [cb]) (addr: hex string or integer; byte_len <= 1 MiB) Issues -data-read-memory-bytes <addr> <byte_len>; res.begin holds start address, res.contents holds lowercase hex byte string (2 * byte_len chars), and res.memory holds raw MI memory block. Returns boolean.
gl.dbg.register_type_visualizer gl.mpi.register_type_visualizer (opts) ({ id = string, type_regex = string, priority = int, format = function(v) }) Registers custom formatter in VariablesDockWidget. v = { rank, name, expression, type, value, address }; format(v) returns summary string or { summary = "...", children = { { name, value, type }, ... } }. Returns boolean.
gl.dbg.set_rank_badge gl.mpi.set_rank_badge (rank, text, [severity, tooltip]) (severity: "info" | "success" | "warning" | "error") Overlays custom per-rank status pill on ServerRackView. Returns boolean.
gl.dbg.clear_rank_badge gl.mpi.clear_rank_badge (rank) (rank: integer) Clears custom plugin badge from rank on ServerRackView. Returns boolean.
gl.dbg.collectives gl.mpi.collectives () Returns a 1-indexed array of per-rank collective alignment tables { rank = int, in_mpi_wait = bool, collective = string, caller_file = string, caller_line = int, caller_func = string, mismatch = bool } computed by MpiCollectiveAnalyzer.
gl.dbg.queues gl.mpi.queues ([rank]) (rank: optional 0-based integer rank filter; omit or nil for all ranks) Returns { posted_recvs = {...}, unexpected = {...}, active_sends = {...}, open_requests = {...}, diagnostics = {...} } from MpiQueueAnalyzer (libgridlock_pmpi.so POSIX SHM sidecar + MPIR queue tables), flagging tag/partner mismatches and overwritten or orphaned MPI_Request handles.

Event-Point Hit Actions: You can trigger external .lua script files (Script File + Browse...) or Inline Code snippets directly on breakpoint, watchpoint, catchpoint, tracepoint, or MPI event hits via the Create Event Point dialog or the Execution Control Center (Ctrl+Shift+B) Actions tab (see User Manual: UI and Debugging).


6. gl.ui (Declarative Panels & 2D Retained-Mode Canvas), gl.marks, gl.regs, gl.diag

2D Canvas API (gl.ui.*)

Symbol Signature / Parameters Behavior & Event Payload
gl.ui.create_canvas (title_or_opts, [location, key]) (title_or_opts: string title or { key, title, dock, location }; location: "bottom" default, "right", "dock", or "popup" / "floating" Qt::Tool window) Creates a retained-mode 2D canvas panel and returns cid (panel_id, or nil). Floating "popup" dialogs automatically take keyboard focus on open.
gl.ui.canvas_draw (cid, cmds) (cmds: array of draw command tables) Submits retained draw ops (op or type): "clear", "line", "polyline", "rect", "circle", "text". Supports { x, y, w, h } or { x0, y0, x1, y1 }, radius/r, stroke_width/width, color/rgba/stroke/fill (0xRRGGBBAA or "#RRGGBB"), filled = true, points = {{x, y}, ...}, text, font_pt. Returns boolean.
gl.ui.canvas_heatmap (cid, grid2d, [opts]) (grid2d: 2D grid[row][col] array or flat array with opts.rows/opts.cols; opts = { vmin, vmax, colormap = "viridis" | "plasma" | "coolwarm" | "grayscale" }) Blits scalar matrix onto canvas with automatic zoom/pan and live hover (row, col, value) readout. Returns boolean.
gl.ui.canvas_blit (cid, rgba_bytes, w, h) (rgba_bytes: raw w * h * 4 byte string or byte array; 1 <= w, h <= 4096) Blits RGBA8888 image buffer directly to canvas. Returns boolean.
gl.ui.canvas_on_click (cid, fn) (fn: function(ev) or nil to clear) Fires on stationary left-click (< 4 px drag) with ev = { x, y, row, col, button, panel_id }. Returns boolean.
gl.ui.canvas_on_key (cid, fn) (fn: function(ev) or nil to clear) Fires on focused canvas key press with ev = { key, code, modifiers, shift, ctrl, alt, panel_id }. Returns boolean.

Declarative Panels, Popups, Status Bar & Prompts (gl.ui.*)

Symbol Signature / Parameters Return / Behavior
gl.ui.create_panel (title_or_opts, [dock, kind]) ((title, [dock, kind]) or { key, title, kind = "table" | "tree" | "text" | "custom_buffer" | "canvas", dock = "bottom" | "right" | "popup", columns = { ... }, custom_buffer_id }) Creates declarative panel and returns integer panel_id (or nil).
gl.ui.update_panel_rows (panel_id, rows) (rows = { { id = "r0", parent_id = nil, color = "accent", tooltip = "...", cells = { "0", "3.2e-9" } }, ... }) Replaces rows in "table" or "tree" panel panel_id. Returns boolean.
gl.ui.close_panel (panel_id) Closes panel_id and releases its UI surface. Returns boolean.
gl.ui.open_popup (opts) (opts = { title, body, buffer_id, line, col, width, height, border, focusable }) Opens anchored editor popup and returns integer popup_id (or nil).
gl.ui.close_popup (popup_id) Closes anchored popup popup_id. Returns boolean.
gl.ui.set_status_segment (segment_id, text, [opts]) (opts = { tooltip, color, priority, on_click = function(id) }) Adds or updates clickable status-bar segment segment_id. Returns boolean.
gl.ui.remove_status_segment (segment_id) Removes status-bar segment segment_id. Returns boolean.
gl.ui.prompt_input (opts, cb) (opts = { title, label, default, placeholder }; cb = function(accepted, value)) Opens non-blocking input dialog and invokes cb(accepted, value) on completion. Returns boolean.

Buffer Marks (gl.marks.*), Named Registers (gl.regs.*) & Diagnostics (gl.diag.*)

Symbol Signature / Parameters Return / Behavior
gl.marks.set (mark, buf_id, line_1, [col_0], [opts]) or (buf_id, line_1, [col_0], opts) (opts = { id, virt_text, virt_text_hl, virt_lines = { { { text, hl_group }, ... }, ... } }) Sets a named buffer mark or gl.marks extmark with optional EOL virt_text and multi-line virt_lines ghost-code blocks rendered below line_1 without mutating PieceTable or shifting real gutter line numbers. Returns boolean (named mark) or integer extmark_id (buffer extmark).
gl.marks.get (mark) or (buf_id, extmark_id) Returns { buffer_id, line, col, file } for a named mark, or { id, virt_lines } for an extmark (or nil if unset).
gl.marks.del (mark) or (buf_id, extmark_id) Deletes a named buffer mark or a gl.marks extmark (and its virt_lines). Returns boolean.
gl.marks.clear ([buf_id]) Clears all gl.marks extmarks and virt_lines in buf_id (or across all open buffers when buf_id is omitted or 0). Returns boolean.
gl.regs.get (reg) (reg: single-char register name) Returns string contents of named plugin register reg (or nil if unset).
gl.regs.set (reg, value) (reg: single-char register name; value: string) Stores value in named plugin register reg. Returns boolean.
gl.diag.set (buf_id, ns_id, items) (items = { { line, col, end_col, severity = "error" | "warning" | "info" | "hint", code, message }, ... }) Publishes namespaced editor diagnostics on buf_id (line is 1-based). Returns boolean.
gl.diag.clear ([buf_id, ns_id]) Clears diagnostics for (buf_id, ns_id) (defaults to 0, 0). Returns boolean.

7. Complete Runnable Examples

Example 1: Zero-Recompile MPI Tracepoint Streaming to a Declarative Panel (add_breakpoint + eval)

local pid = gl.ui.create_panel({
  key = "lua.residual_trace",
  title = "MPI Residual Trace",
  kind = "table",
  dock = "bottom",
  columns = { "Rank", "Location", "Residual Norm" },
})
local rows = {}

gl.dbg.add_breakpoint("solver.cpp:84", {
  log_expr = "residual_norm",
  auto_continue = true,
  on_hit = function(rank, ctx)
    rows[#rows + 1] = {
      id = tostring(#rows + 1),
      cells = { tostring(rank), ctx.file .. ":" .. tostring(ctx.line), ctx.log_value or "?" },
    }
    gl.ui.update_panel_rows(pid, rows)
  end,
})

Example 2: Live GDB Stack & Memory Inspector (read_register + read_memory)

local cid = gl.ui.create_canvas("Live Stack & Memory Inspector", "popup")

local function render_lines(lines)
  local cmds = { { op = "clear", color = 0x1E1E2EFF } }
  for i, line in ipairs(lines) do
    cmds[#cmds + 1] = {
      op = "text",
      x = 16,
      y = 24 + (i - 1) * 20,
      text = line,
      rgba = (i == 1) and 0x89B4FAFF or 0xA6E3A1FF,
      font_pt = 10,
    }
  end
  gl.ui.canvas_draw(cid, cmds)
end

local function refresh_stack()
  local rank = gl.dbg.active_rank()
  gl.dbg.read_register(rank, "rsp", function(reg)
    if not reg.ok then
      render_lines({ "Rank " .. rank .. ": waiting (" .. reg.status .. ")" })
      return
    end
    local rsp_hex = string.format("0x%x", tonumber(reg.value) or 0)
    gl.dbg.read_memory(rank, rsp_hex, 32, function(mem)
      local hex = (mem.ok and mem.contents) or "(memory unreadable)"
      render_lines({
        string.format("Rank %d  RSP = %s", rank, rsp_hex),
        "Top 16B: " .. string.sub(hex, 1, 32),
        "Next 16B: " .. string.sub(hex, 33, 64),
      })
    end)
  end)
end

gl.autocmd.create("RankStopped", { pattern = "*", callback = refresh_stack })
refresh_stack()

Example 3: 2D Scalar Heatmap Visualizer (canvas_heatmap + canvas_on_click)

local cid = gl.ui.create_canvas("2D Thermal Field (Viridis)", "bottom")
local rows, cols = 32, 32
local grid = {}
for r = 1, rows do
  grid[r] = {}
  for c = 1, cols do
    local dx, dy = (c - cols / 2) / 8.0, (r - rows / 2) / 8.0
    grid[r][c] = math.exp(-(dx * dx + dy * dy))
  end
end

gl.ui.canvas_heatmap(cid, grid, { vmin = 0.0, vmax = 1.0, colormap = "viridis" })
gl.ui.canvas_on_click(cid, function(ev)
  local val = (grid[ev.row + 1] and grid[ev.row + 1][ev.col + 1]) or 0.0
  gl.api.log("info", string.format("Cell (%d, %d) = %.4f", ev.row, ev.col, val))
end)

Clone this wiki locally