Documentation Menu

LOLang Technical Specification

LOLang is an embeddable, high-performance scripting language built for making games. It features low-overhead game logic, native windowing, 2D canvas drawing, 3D mesh and PBR rendering, procedural terrain, audio synthesis, and real-time networking.

Installation & PATH Configuration

Once the engine executable (lolang.exe or lolang) is placed on your machine, registering its folder in your path environment variable allows it to be invoked from any terminal or working directory.

Windows Configuration

  1. Locate the directory containing lolang.exe (e.g., C:\LOLang\).
  2. Press Win, search for Environment Variables, and open Edit the system environment variables.
  3. Click Environment Variables...
  4. Under User Variables (or System Variables), select Path and click Edit...
  5. Click New and paste the containing folder path (e.g., C:\LOLang\ — exclude the binary filename).
  6. Click OK on all open dialogs to commit the changes.

Alternatively, update the registry variable directly via Command Prompt:

setx PATH "%PATH%;C:\LOLang"
💡
Terminal Scope Notice: Environment variable changes require a new terminal window to take effect in active sessions.

macOS & Linux Configuration

Append the binary directory to your active shell configuration file (~/.zshrc for default macOS shell, ~/.bashrc for standard Linux distros):

export PATH="$PATH:/path/to/lolang/folder"

Reload your shell configuration file to apply updates immediately:

source ~/.zshrc   // or source ~/.bashrc
⚠️
Case Sensitivity: Ensure your PATH points to the exact case-sensitive folder containing the lolang or LOLang executable binary.

Running Scripts & CLI Commands

With lolang added to your global PATH, executing scripts or launching interactive sessions can be performed via standard flags.

Command Flag Operation Mode Description
lolang script.lol Script Execution Executes the specified source file directly through the runtime VM.
lolang --repl Interactive REPL Launches an interactive prompt for line-by-line statement evaluation.
lolang --help Utility Reference Prints system version details and available command-line flags.
💡
Path Resolution: Assets requested within scripts (e.g., load_model("plane.glb")) are resolved relative to the directory where the .lol script resides, rather than the terminal's working directory.

Native Binary Compilation

LOLang scripts can be linked together and compiled into standalone native executables that run independently without external runtime binaries.

lolang --compile game.lol -o game.exe

Multiple script files can be linked together into a single unified output binary:

lolang --compile main.lol levels.lol enemies.lol -o mygame.exe
⚠️
Compilation Requirement: Native compilation using --compile currently requires a Visual Studio C++ toolchain present on the host environment. Compiled output executables require no runtime dependencies on target machines.

Syntax & Core Conventions

LOLang scripts execute sequentially top-to-bottom. Semicolons at the end of statements are optional; one statement per line is standard.

Comments

// Single-line comments run to the end of the line
let speed = 120 // Trailing line comments are supported

Console Output & Input

print("System Initialization")
input(username)
print("Operator Registered: " + username)

Variables & Type System

Variables are declared using the let or local keyword. Dynamic typing is used throughout the environment.

let score = 0            // Number (64-bit float)
let entityName = "Unit_01" // String
let active = true          // Boolean
let target = nil          // Nil (Null)
let inventory = {}         // Table / Object
Type Memory Structure Description
number 64-bit IEEE 754 Represents all integer and floating-point numeric quantities internally.
string UTF-8 Byte Sequence Double-quoted character sequences. Concatenated using the + operator.
bool 1-byte Boolean Literals evaluating to true or false.
nil Null Pointer State Represents the complete absence of a value.
table Dynamic Hash-Map / Array Primary composite container for arrays, dictionaries, and structures.
i8 / u8 / i16 / u16 / i32 / u32 / i64 / u64 Fixed-Width Two's-Complement Exact hardware-width integers with wraparound overflow. See Fixed-Width Integers & Raw Memory.
buffer Raw Byte Array (Reference) Mutable, shared-reference block of raw memory read/written via peekN/pokeN.
💡
String Interpolation: Double-quoted strings support embedded expressions with ${...}, e.g. "HP: ${hp}/100", which is expanded into a concatenation chain at parse time.

Operator Mechanics

Category Operators Description
Arithmetic + - * / % ^ Standard operations (% is modulo, ^ is exponentiation).
Comparison == != < > <= >= Evaluates relational primitive boolean results.
Logical and or not Evaluates logical expressions with standard boolean short-circuiting.
Concatenation .. (and + on strings) Dedicated string concatenation operator. + also concatenates when either operand is a string.
Ternary cond ? thenExpr : elseExpr Right-associative inline conditional expression, e.g. hp > 0 ? "alive" : "dead".
Bitwise band bor bxor bnot shl shr Bitwise functions operating on 64-bit integer values (see Fixed-Width Integers & Raw Memory).
Assignment = Binds target variable identifiers to evaluated expressions.
let hp = 100
let critical = hp < 20 and not shielded
print("Current Health: " + hp + "/100")

Control Flow Logic

Conditional Logic

if hp <= 0 then
    print("Status: Terminated")
elseif hp < 20 then
    print("Status: Critical")
else
    print("Status: Operational")
end

Iteration Structures

// Conditional Iteration Loop
let counter = 0
while counter < 5 do
    print(counter)
    counter = counter + 1
end

// Numeric Range For Loop
for i = 1 to 5 do
    print("Step: " + tostring(i))
end

// Range Loop with Explicit Step
for i = 10 to 0 step -2 do
    print(i) // Outputs: 10, 8, 6, 4, 2, 0
end

Function Declarations

Functions are declared using the func keyword and return values via the return statement. Omitting an expression from a return statement yields nil.

func calculateDistance(x1, y1, x2, y2)
    let dx = x2 - x1
    let dy = y2 - y1
    return sqrt(dx * dx + dy * dy)
end

let dist = calculateDistance(0, 0, 3, 4)
print(dist) // Outputs: 5

Anonymous Functions & Closures

Functions are first-class values: func(...) ... end used as an expression produces an anonymous function, which can be stored, passed around, and closes over variables from its enclosing scope.

func makeCounter(start)
    let count = start
    return func()
        count = count + 1
        return count
    end
end

let nextId = makeCounter(100)
print(nextId()) // 101
print(nextId()) // 102

Variadic Parameters & Multi-Return

A trailing ... in a parameter list collects any extra positional arguments into a table bound to args. A function can return several values at once, which are only unpacked when consumed by a matching let a, b = ... destructuring assignment — anywhere else the result behaves as a single opaque value.

func sum(...)
    let total = 0
    for n in args do total = total + n end
    return total
end

print(sum(1, 2, 3, 4)) // 10

func minMax(t)
    // ... compute lo/hi ...
    return lo, hi
end

let lowest, highest = minMax(scores)

Tables & Array Containers

Tables represent LOLang's single unified data structure, serving as key-value dictionaries, structs, and 1-indexed arrays.

Named Struct Usage

let entity = { x = 10, y = 5, hp = 30 }
print(entity.hp)
entity.hp = entity.hp - 5

1-Indexed Array Usage

let coins = {}
push(coins, { x = 3, z = -2 })
push(coins, { x = 8, z = 4 })

let index = 1
while index <= table_size(coins) do
    let coin = coins[index]
    print(coin.x + ", " + coin.z)
    index = index + 1
end
push(table, value)

Appends a value to the sequential array portion of a target table.

pop(table)

Removes and returns the last element of the array portion, or nil if empty.

insert(table, index, value)

Inserts value at the given 1-indexed position, shifting later elements up.

remove(table, index)

Removes the element at the given 1-indexed position, shifting later elements down.

find(table, value) / find(str, needle)

Returns the 1-based index of the first match in a table, or the 1-based substring position in a string (0 if not found).

sort(table)

Sorts the array portion in place — numerically if all elements are numbers, lexically otherwise.

copy(table, deep?)

Clones a table. Shallow by default (nested tables stay shared); pass true to recursively clone nested tables too.

get(table, keyOrIndex) / set(table, keyOrIndex, value)

Generic accessor pair for reading or writing a table field or 1-indexed array slot dynamically.

make_table()

Constructs and returns a new, empty table.

table_size(table)

Returns the total element count stored within the table's array index buffer.

Events System (on / emit)

Provides a signal architecture for decoupling logic components across scripts.

on "enemy_died" do
    score = score + 10
    print("Updated Score: " + score)
end

emit "enemy_died"
Syntax Construct Behavioral Scope
on "event" do ... end Registers an event handler bound specifically to the current lexical scope.
on_global "event" do ... end Registers an event handler in global scope, accessible from any emitting call site.
emit "event" Triggers execution of all handlers registered under the event key.
emit "event", payload Triggers execution for listeners with an optional data parameter.
emit_to(event, payload?) Function form of emit — queues an event (with optional payload) to be dispatched to handlers on the next update().

Module Imports

External source files are imported directly using the import statement, resolved relative to the calling script's location.

import "utils.lol"

Windowing & Engine Game Loop

Graphical execution follows a structured sequence: initialize window resources, enter the main process loop, poll input, clear render buffers, draw scene elements, and present the finished frame buffer.

window("LOLang Engine", 960, 600)

while true do
    update()
    clear_screen()

    // Scene drawing calls executed here

    frame_end(true)
end
window(title, width, height)

Initializes native OS window context with specified pixel dimensions.

update()

Polls operating system events, processes window events, and updates input buffers.

clear_screen(skip2D?)

Clears background frame. Pass true to preserve CPU 2D pixel buffer data.

frame_end(is3D)

Swaps hardware frame buffers. Pass true for 3D execution, false for 2D mode.

dt()

Returns delta time elapsed since the preceding frame in seconds.

Returns: Number (Seconds)
fps()

Returns the calculated runtime execution performance in frames per second.

Returns: Number
fullscreen(state?)

Toggles or explicitly sets window fullscreen status. Default hotkey is F11.

Returns: Boolean (Resulting State)
resizable(enable)

Configures user edge-drag window resizing capabilities.

resize(width, height)

Resizes native frame window programmatically.

screenshot(path)

Saves active screen buffer contents to a PNG file relative to current script directory.

Returns: Boolean (Success State)

2D Canvas Drawing API

CPU-side pixel canvas that renders elements directly over 3D scenes. Ideal for heads-up displays, text layers, and 2D games.

set_color(r, g, b)

Sets active 2D draw channel colors (0–255 integer scale per channel).

set_clear_color(r, g, b)

Configures background clearing color used by clear_screen().

draw_pixel(x, y)

Plots a single pixel on the canvas using active color parameters.

draw_rect(x, y, w, h)

Draws a solid filled rectangle on the canvas.

draw_line(x1, y1, x2, y2)

Draws a 1-pixel line segment between two target points.

draw_circle(x, y, radius)

Renders an outlined circle on the active canvas layer.

draw_text(text, x, y)

Renders text strings on screen using current draw color properties.

gl_rect(x, y, w, h, r?, g?, b?, a?)

Draws a hardware-accelerated overlay rectangle directly via GL, independent of the CPU pixel canvas — useful for HUDs layered over 3D scenes. Color/alpha channels are 0–255 and default to opaque white.

set_color(255, 255, 255)
draw_text("Current Score: " + score, 20, 20)

Native 2D Drawing Statements

An alternative keyword syntax available for 2D canvas operations, supporting rapid scripting and REPL usage.

Native Statement Syntax Functional API Mapping
color(r, g, b) set_color(r, g, b)
clear / clear(r, g, b) clears canvas, optionally setting custom background color
rect(x, y, w, h) draw_rect(x, y, w, h)
circle(x, y, r) draw_circle(x, y, r)
line(x1, y1, x2, y2) draw_line(x1, y1, x2, y2)
draw text(str, x, y) draw_text(str, x, y)
draw rect / circle / line (...) identical to bare statement alternatives listed above
sleep(ms) pauses runtime processing execution for target milliseconds

Meshes & Procedural Primitives

Functions to load Wavefront .obj files or generate procedural geometries, returning integer mesh handles.

load_mesh(path)

Loads a 3D Wavefront .obj file along with its associated .mtl materials.

Returns: Mesh Handle ID
create_cube(size) / create_cube(sx, sy, sz)

Generates a procedural uniform cube or scaled box mesh.

Returns: Mesh Handle ID
create_plane(width, depth, tileSize)

Generates a flat horizontal plane mesh. tileSize configures texture UV repetition.

Returns: Mesh Handle ID
draw_mesh(mesh, x, y, z, rx, ry, rz, sx, sy, sz, r, g, b, a, useTexture)

Renders target mesh with position, rotation (in degrees), scale, color tinting, and optional texture toggle.

let cubeHandle = create_cube(1.5)

// Params: mesh, pos(x,y,z), rot(rx,ry,rz in degrees), scale(sx,sy,sz), color(r,g,b,a), useTexture
draw_mesh(cubeHandle, 0, 0, 0,  0, 45, 0,  1, 1, 1,  200, 100, 80, 255, false)
💡
Rotation Standard: Rotations throughout the 3D graphics system (rx, ry, rz) are calculated in degrees (0° to 360°) rather than radians.

Rendering State

load_texture(path)

Loads a BMP image file from disk as a GL texture, relative to the script directory.

Returns: Texture Handle ID (0 on failure)
set_wireframe(enabled)

Toggles wireframe polygon rendering mode for all subsequently drawn 3D geometry.

set_cull(enabled)

Enables or disables back-face culling (GL_BACK) for subsequently drawn 3D geometry.

PBR Models Subsystem (glTF)

Supports physically-based rendering models with base color, normal maps, and metallic-roughness textures loaded from binary glTF (.glb) containers.

load_model(path)

Loads binary .glb models and maps PBR material pipelines. Returns -1 on error.

Returns: Model Handle ID
draw_model(model, x, y, z, rx, ry, rz, sx, sy, sz)

Renders PBR model using degree-based rotations and scale vectors.

set_texture_animation(model, framesX, framesY, fps)

Executes sprite-sheet frame sequence animation across model base textures.

let biplane = load_model("biplane.glb")
draw_model(biplane, px, py, pz,  pitch, yaw, roll,  1, 1, 1)

Procedural Terrain Generation

Generates height-banded terrain dynamically using deterministic seed routines without requiring external mesh geometry files.

create_terrain(w, d, resX, resZ, seed, maxH)

Generates terrain of size w × d world units with mesh resolution and max height control.

Returns: Terrain Handle ID
draw_terrain(terrain, x, y, z)

Renders terrain mesh centered at target world location parameters.

terrain_height_at(terrain, wX, wZ, offX, offY, offZ)

Calculates procedural surface elevation height at world coordinates for physics alignment.

Returns: Number (World Y Height)
let terrain = create_terrain(2000, 2000, 100, 100, 7, 150)
draw_terrain(terrain, 0, -60, 0)

let floorHeight = terrain_height_at(terrain, playerX, playerZ, 0, -60, 0)
if playerY <= floorHeight then
    print("Surface Contact Detected")
end

Skybox Rendering Subsystem

Manages cubemap background environments via six orthogonal face textures.

load_skybox(px, nx, py, ny, pz, nz)

Loads cubemap texture assets ordered: +X, -X, +Y, -Y, +Z, -Z.

Returns: Boolean (Success State)
draw_skybox()

Renders active loaded skybox environment. Call prior to rendering 3D scene meshes.

Camera Subsystem Controls

Supports dual projection tracking modes: Orbit Mode (revolves around a target origin point) and FPS Mode (free-flying direction matrix).

Orbit Camera Controls (Default)

camera(yaw, pitch, distance, tX?, tY?, tZ?)

Positions orbit camera using spherical angle degree vectors and distance radii around target coordinates.

camera_target(x, y, z)

Updates focal target coordinates centered within camera orbit field.

camera_yaw(deg?) / camera_pitch(deg?)

Sets or queries current spherical orientation camera angles in degrees.

camera_dist(distance?)

Sets or queries the orbit camera's distance from its target point.

First-Person (FPS) Controls

camera_mode(mode?)

Configures active camera mode: "orbit" or "fps". Query current mode by omitting parameter.

camera_pos(x, y, z)

Sets absolute free-fly world coordinates. Returns position table {x,y,z} if parameter omitted.

camera_move(forward, right, up)

Translates FPS camera relative to its current directional look vectors.

camera_look(deltaYaw, deltaPitch)

Adjusts viewing angles via relative mouse-look deltas in degrees. Pitch is clamped vertically.

camera_mode("fps")
if keydown("W") then camera_move(5 * dt(), 0, 0) end
camera_look(mouse_x() * 0.1, 0)

Lighting & Distance Fog

set_light(dX, dY, dZ, r, g, b, ambR, ambG, ambB)

Configures global directional light vector and channel intensities (0–255) along with ambient lighting levels.

set_fog(r, g, b, distance)

Configures distance fog blending color and depth thresholds to seamlessly match environment horizons.

set_light(-0.3, -0.7, -0.4,  255, 250, 235,  110, 110, 120)
set_fog(120, 180, 240, 900)

Keyboard & Mouse Input Handling

Functions to query input device states, supporting character keys, control keys, functional keys (F1–F24), and mouse clicks.

keydown(key)

Returns true continuously while specified key parameter is depressed.

keypressed(key)

Returns true strictly during the initial frame key transition state.

mouse_x() / mouse_y()

Returns active mouse cursor position coordinates in pixel space.

mouse_down(button?)

Returns true while mouse button is held down ("left" or "right").

mouse_clicked(button?)

Returns true on initial frame of mouse button click event.

if keydown("LEFT") then playerX = playerX - speed * dt() end
if keypressed("SPACE") then triggerJump() end

Audio Synthesis & Playback

Features a built-in multi-track synthesizer engine for dynamic audio generation alongside sample file playback systems.

Synthesizer Interface

synth_note(track, freq, wave, duration, volume)

Triggers synthesized tone using wave mode: "sine", "square", "saw", "triangle", or "noise".

synth_track_volume(track, volume)

Configures target audio track output volume levels (0 to 2 scale range).

synth_track_mute(track, state)

Mutes or unmutes specific audio synthesis track indexing channels.

synth_track_pan(track, pan)

Configures stereo channel panning ranging from -1 (Left) to +1 (Right).

synth_master_volume(volume)

Sets overall global output volume scaling across all tracks (0 to 2 scale range).

synth_stop_all()

Immediately halts processing for all active playing sound frequencies.

sample_load(path)

Loads an uncompressed .wav audio file into a reusable sample slot.

Returns: Sample Handle ID
synth_sample(track, sampleId, rate?, volume?)

Triggers playback of a previously sample_load-ed sample on a synth track, with optional pitch/rate and volume.

Simple Sound Playback

play_sound(path)

Plays target external audio file asynchronously (non-blocking call execution).

stop_sound()

Halts playback initiated through prior play_sound function calls.

synth_note(0, 440, "square", 0.15, 0.6) // Synthesizes a short test beep

UDP Networking Engine

Socket interface built for peer-to-peer communication and LAN multiplayer architectures.

net_open(port)

Binds UDP socket to port parameter (pass 0 for dynamic automatic assignment).

Returns: Socket Handle (-1 on Error)
net_close(socket)

Closes target bound networking socket reference instance.

net_send(socket, ip, port, data)

Transmits raw string packet payloads to target destination host addresses.

net_broadcast(socket, port, data)

Transmits string data packets across local subnet broadcast destinations.

net_enable_broadcast(socket)

Grants socket permission flags required to send subnet broadcast packets.

net_recv(socket)

Non-blocking receive call. Returns {ip, port, data} table or nil.

Returns: Table or Nil
net_local_ip()

Resolves and returns local network adapter IPv4 address string representation.

Returns: String
let socket = net_open(9931)
net_send(socket, "192.168.1.10", 9932, "Ping Payload")

let packet = net_recv(socket)
if packet != nil then
    print(packet.ip + ": " + packet.data)
end

HTTP Protocol Subsystem

Synchronous HTTP communication API designed for simple web interactions.

http_get(url)

Executes GET request for plain http:// endpoints. HTTPS URLs are unsupported.

Returns: Table {ok, status, body, error}
let response = http_get("http://api.example.com/status")
if response.ok then
    print(response.body)
else
    print("Request failed: " + response.error)
end
⚠️
Blocking Call Notice: http_get has a 10-second timeout. Execute calls during loading sequences rather than per-frame game loops to prevent rendering hitches.

Native Files & GUI Dialogs

Access native OS file selection and color picker dialog windows.

open_file_dialog()

Opens system native file selection dialog modal. Returns selected path or empty string.

Returns: String
choose_color(r, g, b)

Displays native color selection dialog initialized with RGB values. Returns {r,g,b} table.

Returns: Table or Empty

System Execution & Path Integration

system(pathOrUrl)

Hands target path or web URL to OS default application handler (e.g., opens default browser).

Math Standard Library

Function Signature Description
abs(x) Returns the absolute value of numeric input.
sqrt(x) Computes square root of target value.
sin(x) / cos(x) / tan(x) Standard trigonometric operations (expects input values in radians).
floor(x) Rounds numeric inputs down to nearest integer representation.
min(a, b, ...) / max(a, b, ...) Returns smallest or largest value from provided arguments.
clamp(x, lo, hi) Constrains target value x strictly within bounds [lo, hi].
rand(lo, hi) Generates pseudorandom integer within inclusive range parameters.
💡
Angle Standard Notice: Math library functions (sin, cos, tan) process values in radians. Transform degrees to radians using: rad = deg × (π / 180).

Strings & Type Conversion

Function Signature Description
tostring(value) Converts any primitive or container reference into a string representation.
tonumber(string) Parses numerical strings into 64-bit numbers. Returns nil on parse failure.
type(value) Returns internal evaluation type name string (e.g., "number", "table").

Miscellaneous Utilities

sleep(ms)

Pauses current thread execution for requested duration in milliseconds.

Interactive Compiler Workstation

Test statement compilation and evaluate system response states within the live execution environment interface.

// Waiting for compiler input action...
System Diagnostics Allocation