Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Ling is a programming language you can write in your own language. Its keywords and builtins have names in more than 16 human languages, including Chinese, Japanese, Korean, Thai, English, Arabic, Hebrew and Russian, and you can mix them in the same file. These docs cover five of them: English, 中文, 日本語, 한국어 and ไทย. Pick yours from the language selector at the top of the page.

This guide covers Ling 2030.1.53.

A first look

Here is a small program. bind start = do { ... } is where every program begins.

# Greet a few friends
bind start = do {
    bind friends = ["Ada", "Lin", "Sora"]
    for name in friends {
        print("Hello, " + name + "!")
    }
    print(len(friends))
}
Hello, Ada!
Hello, Lin!
Hello, Sora!
3

The same program works with Chinese, Japanese, Korean or Thai keywords. Switch the page language to see it, or read Writing in Five Languages.

What you get

One ling binary includes:

  • A JIT compiler and an interpreter. Programs compile to native code through Cranelift, with an interpreter for everything else.
  • Graphics and 3D. A window, 2D drawing, images, fonts, a software 3D renderer with cameras, lights, cel shading and vector geometry (vtex_*).
  • Audio and music. Tones, spatial sound, WAV playback, music decoding, BPM and key analysis, a GM-style synth and MIDI.
  • Physics. Rigid bodies, soft bodies and a liquid simulation.
  • UI. HUDs, meters, buttons and other widgets.
  • A web server. Routes, static files and SQLite through the http_* and db_* builtins.
  • Cryptography. Hashes, encryption, signatures and post-quantum key exchange.
  • AI. Neural networks, behaviour trees and optional language-model support.

lingfu, the project manager, creates, runs and tests projects, and lingfu normalize rewrites a whole project into one language.

Install

On macOS or Linux:

curl --proto '=https' --tlsv1.2 -sSf https://ling-lang.org/install.sh | sh

On Windows (PowerShell):

irm https://ling-lang.org/install.ps1 | iex

The script installs Rust if you don’t have it, then builds ling and lingfu. See Installation for other options and install profiles.

Where to go next

  • Getting Started: install Ling, run Hello World and build your first 3D room.
  • Tutorials: learn the language step by step, from values to games, music and a web service.
  • Language Guide: syntax, keywords, types, errors, modules and known limits.
  • Builtins Reference: every builtin, grouped by topic.
  • The Ling Book: four free PDF books, from beginner to complete reference.
  • Showcase: apps and demos built with Ling.

The Ling Book (PDF)

The Ling Book is a series of four books written against Ling 2030.1.53. Each one is a free PDF download. The books are in English.

VolumeLevelPagesDownload
Learn LingBeginner321ling-beginner.pdf (13 MB)
Build with LingIntermediate716ling-intermediate.pdf (27 MB)
Mastering LingAdvanced452ling-advanced.pdf (16 MB)
The Ling ReferenceComplete reference650ling-reference.pdf (26 MB)

What each book covers

Learn Ling (Beginner)

Values and bindings, decisions and loops, functions, lists and text, your first 3D room, drawing and games, sound and music. It ends with a finished project.

Build with Ling (Intermediate)

Forms, errors and results, modules and project structure, data and files, UI apps, animation and input, games and physics, music tools, testing and debugging, and packaging and shipping.

Mastering Ling (Advanced)

How Ling runs, concurrency and isolates, network services, web apps with the Rust crates, cryptography, peer-to-peer protocols, AI and tensors, using the crates from Rust, extending Ling, Ling OS and embedded targets, and designing large apps.

The Ling Reference

Every keyword and builtin with its parameters, return value, aliases and examples. The last chapter lists known limits and gotchas.

Which one to read

  • New to programming, or new to Ling: start with Learn Ling.
  • Building real programs: read Build with Ling.
  • Going deep: read Mastering Ling.
  • Looking something up: keep The Ling Reference open.

These docs are the short online companion. The books go further and stay on one Ling version. For quick lookups, the Builtins Reference and the Known Limits page are often faster.

Showcase

These apps and demos are written in Ling and run on the Ling runtime. Screenshots of the apps are on the website: ling-lang.org/#apps.

Apps

AppWhat it is
LingStationXA digital audio workstation: arranger, piano roll, tracker, session view, a node-graph patcher, a mixer and the Nova, Prism and Growl synths. It imports MIDI and has a slicer, time-warp and a mastering chain.
LingDevA 3D game editor with a node tree, a timeline and cutscene tracks for camera, dialog and effects. Games made with it include Dance Ling, Ling Hazard, Ling Breaker, Moko, Ling Agent and the Soul Symphony series.
LingModelerModelling, rigging, weight painting, posing and animation, plus vector illustration, 2D animation with onion skin and procedural textures. It also runs inside LingOS on x86-64 and Raspberry Pi.
LingForFunAn online action RPG with an overworld, towns, dungeons, flight, combat and quests. It has a desktop client, a WASM browser client and a server cluster, all in Ling. Written with Chinese keywords. In development.
Ling ArcadeA console-game library with an NES emulator written in Ling: the 6502 CPU, PPU, mappers and APU are plain .ling code on Ling’s JIT. It passes the full nestest log (8,991 instructions, cycle-exact).
Ling WalletA post-quantum privacy wallet, full node and miner for LNG: ML-DSA-87 identities and hybrid ML-KEM-1024 + X25519 key exchange. Experimental and unaudited.

Community projects

ProjectWhat it is
Soul SymphonyAn RPG arcade physics game. Roll an orb across 9 procedural levels with a boss fight after each one. Arcade versus, networking and co-op, in 5 languages.
LingSoulAn atmospheric soul-balance sim in Ling’s wireframe style, with a constructed glyph alphabet for its in-world HUD.

Demos in the repository

The Ling repository has many runnable examples. A few to start with:

DemoWhat it shows
examples/music/hallway_runner.lingAn infinite runner that reacts to the music; coins ring the melody as spatial sound
examples/music/karaoke_hero.lingKaraoke pitch bars from a vocal MIDI, with a live microphone tuner
examples/music/synth_jam.lingGM instruments synthesized from .ling patches
examples/physics/bouncy_ball.lingA spring-mass soft body that squashes as it bounces
examples/physics/tumbling.lingRigid bodies tumbling and rolling
examples/physics/liquid_marble.lingA water and oil simulation on a spinning sphere, cone and dome
examples/ui/hud_showcase.lingThe UI toolkit: HUD, meters, controls and game widgets
examples/crypto/crypto_donut_physics.lingA SHA3 hash shapes a bouncing torus knot, with reactive audio

Run one from the repository root:

ling run examples/physics/liquid_marble.ling

The Examples section of these docs walks through four 3D scenes in more detail.

Installation

You can install Ling with one command. You get two programs: ling, which runs and builds Ling programs, and lingfu, the project manager.

One-line install

# macOS / Linux
curl --proto '=https' --tlsv1.2 -sSf https://ling-lang.org/install.sh | sh
# Windows (PowerShell)
irm https://ling-lang.org/install.ps1 | iex

The script installs a Rust toolchain first if you don’t have one (the same way rustup does). Then it builds ling and lingfu from crates.io.

With Cargo

If you already have Rust, install both programs from crates.io:

cargo install ling-lang lingfu

Both end up in the same folder (~/.cargo/bin). lingfu looks for ling next to itself first, then on your PATH.

From source

git clone https://github.com/taellinglin/ling
cd ling
cargo build --release
# the binaries are in target/release/ (ling, plus lingc, lx and ling-repl)

To build lingfu from the same checkout, run cargo build --release -p lingfu.

Check that it works

Run ling with no arguments. The first line of the usage text shows the version:

ling
# ling 2030.1.53 — The Omniglot Systems Language
# Usage:
#   ling run <file.ling>   ...
lingfu --version
# lingfu v2030.1.19

ling has no --version flag; the usage text is the way to see it.

Install profiles

cargo install ling-lang installs everything (the full profile). To build less, turn the default off and choose the profiles you need:

cargo install ling-lang --no-default-features --features core        # compiler + interpreter only
cargo install ling-lang --no-default-features --features web         # + HTTP server/client, SQLite
cargo install ling-lang --no-default-features --features game,audio  # a game kit with sound
ProfileWhat it adds
coreLexer, parser, Cranelift JIT and AOT, the interpreter, the software window and drawing (draw_*, fonts, images, meshes). Every profile includes it.
webhttp_* server and client (Web Server and HTTP), db_* SQLite (Database), static files, TOTP, zip/tar, video playback, processes, hashes and password_hash.
privacyPost-quantum identities, lingtp://, peer-to-peer p2p_*, Ling Wallet lw_*, ssh_*, plus web and the ui_* widgets.
gamePhysics (soft, rigid, liquid, glTF), GPU raster, animation, dialogs, gamepads, acoustic bodies, ui_* widgets.
aiNeural networks (nn_*), behaviour trees (bt_*), learned dialog and speech-to-text (stt_*).
audioSound engine, music decoding, synthesis and MIDI, microphone, the LingStationX DAW.
osling build --platform kernel, rpi, lingos, lingos-rpi (LingOS images).
fullAll of the above (the default). It also includes art, the LingAnime paint engine (art_*).

If a program calls a builtin from a profile your build leaves out, it stops with an error that names the profile to reinstall with. Some heavy extras are opt-in on top of any profile: llm, llm-cuda, vision, cuda, gpu-cuda, gpu, llvm, emu.

Requirements

  • Rust 1.85 or newer (the install script sets it up for you).
  • On Linux: libasound2-dev for audio.
  • On macOS and Windows: nothing extra.
  • ling build for desktop targets compiles a small Rust project, so it also needs the Rust toolchain. See The ling Command.

Next steps

  • Write your first program: Hello World.
  • Learn the commands: Running Programs.
  • Read the Ling Book, a free four-volume PDF series: Beginner, Intermediate, Advanced and a complete Reference.

Hello World

Every Ling program starts at a binding named start whose value is a do block. Here is the smallest program that prints something.

Your first program

Save this as hello.ling:

bind start = do {
    print("Hello, World!")
}
Hello, World!

Run it:

ling run hello.ling
  • bind start = ... gives the name start to a value. Ling looks for this name to know where your program begins.
  • do { ... } is a block of steps that run in order.
  • print(...) writes a line to the terminal. println does the same thing.

A little more

Bindings can live outside start too. This program greets a name and then loops over a list:

# Say hello to a few friends
bind name = "Ling"
bind start = do {
    print("Hello, " + name + "!")
    for friend in ["Ada", "Bo", "Chen"] {
        print("Hi, " + friend)
    }
}
Hello, Ling!
Hi, Ada
Hi, Bo
Hi, Chen

+ joins text, and for ... in runs its block once for each item of the list.

Mixing languages

Every keyword and builtin has a name in English, Chinese, Japanese, Korean and Thai, and you can mix them freely in one file. This program uses all five:

令 名字 = "Ling"
bind start = do {
    พิมพ์("สวัสดี " + 名字)
    만약 참 {
        印刷("こんにちは")
    }
}
สวัสดี Ling
こんにちは

When a file is mostly in another language, ling notes the language it detected on standard error, for example [detected language: Chinese (中文)]. It doesn’t change how the program runs.

To learn how the five languages fit together, read Writing in Five Languages.

Next steps

Running Programs

You run a single file with ling run, and a whole project with lingfu run. This page shows both, explains the two ways Ling can execute your code, and how to turn a program into something you can ship.

Run a file

ling run hello.ling
ling hello.ling          # shorthand for the same thing

ling run parses the file, finds the entry point (bind start = do { ... }) and runs it. A source file can end in .ling, .灵, .霊, .령 or .ลิง.

Anything after the file name stays on the command line for your program to read: get_args() returns the whole command line, and cli_arg("port", "8080") reads a --port 99 option, falling back to "8080".

JIT or interpreter

Ling has two backends:

CommandBackendUse it for
ling run file.lingCranelift JIT (the default)Speed. Compiles your program to native code first.
ling run --interp file.lingTree-walking interpreterDiagnostics. It is the reference for how Ling behaves.

If the JIT can’t compile a program, ling run falls back to the interpreter for the whole program. You can also lower the JIT’s optimisation level with --O0, --O1, --O2 or --O3 (the default is --O3) if a very large program takes too long to compile.

When a program “does nothing”, try --interp

On the JIT, calling a function that doesn’t exist returns nothing and the program carries on. This program has a typo in draw_rectt:

bind start = do {
    print("before")
    draw_rectt(1, 2)
    print("after")
}
before
after

The interpreter stops and tells you what went wrong:

$ ling run --interp typo.ling
before
error[runtime]: unknown function 'draw_rectt'
 --> typo.ling
  traceback (deepest call last):
    0: start
  hint: check the spelling, or `use` the module that defines it

Make --interp part of your routine whenever something seems to be ignored. Known Limits lists the other differences between the backends.

Servers run on the interpreter

A program that calls http_serve or lingtp_serve always runs on the interpreter, even without --interp. Request handlers are closures passed to a builtin, and the JIT doesn’t support those yet. A web service waits on the network most of the time, so you don’t lose anything noticeable. See A Small Web Service.

Run in the browser

ling run --wasm file.ling (or --web) builds the program to WebAssembly, serves it on a local web server and opens your browser. The first build compiles the runtime and can take about a minute. It needs the lingc binary next to ling.

Projects with lingfu

For anything bigger than one file, let lingfu create a project:

lingfu new demo
cd demo
lingfu run
Running ...\demo\src\start.ling...
🌊 Welcome to demo Spirit Realm 🌊
Spirit Level: 铁

lingfu new creates this layout:

demo/
├── Ling.toml          the manifest
├── README.md
├── .gitignore
├── ling.ignore        files to leave out when publishing
├── lexicons/en.ling
├── src/start.ling     the entry program
└── tests/test.ling
CommandWhat it does
lingfu runRuns the entry program with ling run. Extra arguments are passed on.
lingfu testRuns every .ling file under tests/, one by one.
lingfu buildBuilds a native executable with ling build --aot.
lingfu cleanDeletes the build output.

lingfu new --lang zh (or ja, ko, th) creates the project in that language, including the folder and file names. lingfu covers every command.

Ling.toml

The manifest that lingfu new writes looks like this:

[spirit]
name = "demo"
kind = "bin"
version = "2030.0.0"

[author]
ling-lin = { email = "you@example.com" }

[realm]
language = "en"
level    = "铁"
source   = "src"

[root]
core = { version = "2030.0", language = "en" }

[depends]
# Add dependencies: spirit-name = { version = "x.y.z" }
  • [spirit] names the project. You can add entry = "src/start.ling" here.
  • [realm] sets the project’s language and its source folder.
  • [root] and [depends] list the core dependency and your packages.

lingfu run and lingfu test find src/start.ling on their own. ling build (and therefore lingfu build) looks for main.ling unless the manifest says otherwise, so add entry = "src/start.ling" under [spirit] before you build.

Build a program

ling build turns a file or a project folder into something you can distribute:

ling build game.ling                      # host platform + web, into dist/
ling build . --platform win,web --out dist
ling build . --platform all --pack --icon logo.svg
OptionMeaning
--out <dir>Output folder (default dist). Each platform gets a sub-folder.
--platform <list>Comma-separated: web, win, lin, mac, macarm, pios, kernel, rpi, lingos, lingos-rpi. all means win,lin,mac,web.
--icon <file>App icon (.svg, .png, .ico, …).
--packEmbed the manifest’s [includes] files in the executable.
--aotCompile to native code ahead of time instead of embedding the interpreter.

Without --platform, the build uses the manifest’s targets list, or your host platform plus web if there is none. Desktop targets generate and compile a small Rust project, so you need a Rust toolchain installed, and the first build can take a few minutes. The web target uses the lingc binary.

The ling Command has the full list of options and manifest keys.

Your First 3D Room

Time to leave the terminal. On this page you open a window, learn the frame loop that drives every Ling picture, and build a small 3D room you can walk around with the arrow keys. Ling draws everything with its built-in software renderer, so you don’t need a game engine or a GPU.

Programs that open a window can’t be checked in the terminal, so their code blocks have no output. Press Escape or close the window to stop any of them.

The frame loop

A window shows one still picture (a frame) at a time. Your program draws a frame, shows it, and starts the next one. Every graphical program has the same rhythm:

  1. Open the window, once.
  2. Clear it with fill, so the last frame doesn’t linger.
  3. Draw your shapes.
  4. Show the frame with present().

The loop runs while window_is_open(). That becomes false when the window is closed or Escape is pressed, so you don’t need to write your own exit.

bind start = do {
    open_window(640, 400, "My first window")
    bind angle = 0
    while window_is_open() {
        fill(15, 18, 40)
        set_color(255, 120, 60)
        cube(0, 0, 3, 1, 1, 1, angle, angle * 0.7, 0, 0)
        present()
        bind angle = angle + 0.02
    }
}
  • open_window(640, 400, "My first window") opens a 640 x 400 window. Size first, title last.
  • fill(15, 18, 40) paints the whole window. Colours are red, green and blue from 0 to 255.
  • set_color(...) picks the colour for the shapes that follow.
  • cube(...) draws a cube. The arguments come in groups of three: centre x, y, z, size, rotation in radians, and a final mode (0 solid, 1 wireframe, 2 both).
  • present() shows the frame. Nothing appears without it.
  • Rebinding angle each frame is what makes the cube turn.

Where things are

In Ling’s 3D world, x points right, y points down, and z points away from you into the screen. So “up” is negative y: in the room below, the floor is at y = 3 and the ceiling at y = -3.

The camera sits at the origin and looks along z. Three calls change what it sees:

CallWhat it does
set_camera_pos(x, y, z)Moves the camera.
set_camera(cos_yaw, sin_yaw, cos_pitch, sin_pitch)Turns it. You pass the cosine and sine of each angle, so to turn by a, call set_camera(cos(a), sin(a), 1, 0).
set_zdist(d)How far your eye sits behind the picture. A small value such as 0.5 suits a first-person view.

Call the camera functions every frame, before you draw.

A room you can walk around

This program puts it all together: a floor and ceiling made of grids, four walls, four pillars, a light, a spinning centrepiece, and keyboard control. Save it as room.ling.

# A room you can walk around in.
# Left/right arrows turn, up/down arrows walk. Escape quits.

fn pillar(x, z) {
    set_color(200, 190, 170)
    cylinder(x, 0, z, 0.5, 3, 0.5, 0, 0, 0, 0)
}

fn walls(t) {
    # floor and ceiling (y points down, so the floor is at y = 3)
    vtex_grid(0, 3, 0,   1, 0, 0,  0, 0, 1,   16, 16, 1, 1,  t, 0)
    vtex_grid(0, -3, 0,  1, 0, 0,  0, 0, 1,   16, 16, 1, 1,  t, 2)
    # four upright walls
    vtex_grid(0, 0, 8,   1, 0, 0,  0, -1, 0,  16, 6, 1, 1,  t, 1)
    vtex_grid(0, 0, -8,  1, 0, 0,  0, -1, 0,  16, 6, 1, 1,  t, 1)
    vtex_grid(-8, 0, 0,  0, 0, 1,  0, -1, 0,  16, 6, 1, 1,  t, 3)
    vtex_grid(8, 0, 0,   0, 0, 1,  0, -1, 0,  16, 6, 1, 1,  t, 3)
    # a flower on the far wall
    vtex_flower(0, 0, 7.9,  1, 0, 0,  0, -1, 0,  1.6, 24,  t, 0)
}

bind start = do {
    open_window(960, 600, "My 3D room")
    set_shade_mode(1)
    set_rim(0, 0, 0, 0)
    set_shadow_color(30, 30, 50)
    set_ambient(0.3)

    bind px = 0
    bind pz = -5
    bind yaw = 0
    bind t = 0

    while window_is_open() {
        # input: turn and walk
        if key_down("left") {
            bind yaw = yaw - 0.03
        }
        if key_down("right") {
            bind yaw = yaw + 0.03
        }
        if key_down("up") {
            bind px = px + sin(yaw) * 0.1
            bind pz = pz + cos(yaw) * 0.1
        }
        if key_down("down") {
            bind px = px - sin(yaw) * 0.1
            bind pz = pz - cos(yaw) * 0.1
        }

        # draw
        fill(8, 8, 20)
        set_camera(cos(yaw), sin(yaw), 1, 0)
        set_camera_pos(px, 0, pz)
        set_zdist(0.5)
        clear_lights()
        add_light(0, -2.5, 0, 1.0, 0.85, 0.6, 1.0, 14)

        walls(t * 0.3)
        pillar(-6, -6)
        pillar(6, -6)
        pillar(-6, 6)
        pillar(6, 6)

        set_color(240, 200, 80)
        torus(0, 1.5, 0, 0.7, 0.7, 0.7, 1.2, t * 0.03, 0)

        present()
        bind t = t + 1
    }
}

Run it:

ling run room.ling

How it works:

  • pillar and walls are functions that draw parts of the room. They are called inside the loop, so they draw again every frame. walls gets t as a parameter because functions only see their parameters and top-level names.
  • The four lines after open_window switch to calm, faithful colours. Without them, Ling’s default look tints shadows indigo and adds a glowing rim.
  • px, pz and yaw hold the camera’s position and heading. key_down("left") is true while the key is held. Walking moves by sin(yaw) along x and cos(yaw) along z, the direction you are facing.
  • clear_lights() and add_light(x, y, z, r, g, b, intensity, radius) run every frame, because lights add up otherwise. The lamp is at y = -2.5, near the ceiling.
  • vtex_grid and vtex_flower draw line patterns on a flat sheet. The first three numbers are the centre, the next six are the sheet’s “right” and “up” directions. For upright walls, “up” is 0, -1, 0, because y points down.

The walls are only drawn, not solid: you can walk straight through them.

Try it

  • Change the last number of each vtex_grid call (the hue) to get other colours.
  • Add a fifth pillar, or a second add_light in a different colour.
  • Add if key_pressed("p") { screenshot("room") } after present(). Pressing P saves a PNG in a screenshots folder.

Next steps

Values and Bindings

Every program works with information: a score, a name, a yes-or-no answer. In this lesson you will meet the basic kinds of values in Ling, give them names with bind, “change” them by rebinding, and print them. Each step has a small program you can copy into a file and run with ling run.

Values

A single piece of information is called a value. These are the kinds you will use most:

KindWhat it holdsExamples
numberany number, whole or with a fraction42, 3.14, -7
textletters, words, sentences (also called a string)"hello", "Room 101"
booleanone of two answers: yes or notrue, false
listseveral values in a row[1, 2, 3], ["red", "blue"]

Print one of each:

bind start = do {
  println(42)
  println(3.14)
  println("a piece of text")
  println(true)
  println([1, 2, 3])
}
42
3.14
a piece of text
true
[1, 2, 3]

Numbers are written bare. Text goes between double quotes. true and false have no quotes, because they are not text. A list is written between square brackets, with commas between the items.

A few rules for writing values:

  • Write numbers with ordinary digits and at most one decimal point. Write 0.5, not .5. There is no 1e3 or 0xff.
  • Text uses double quotes only. Inside text, \n starts a new line and \" is a quote mark.

Bindings: giving values a name

You give a value a name with bind. From then on, the name stands for the value:

bind start = do {
  bind name = "Mina"
  bind age = 12
  println("Hello, " + name)
  println(name, " is ", age)
  println("Next year: ", age + 1)
}
Hello, Mina
Mina is 12
Next year: 13

Read bind age = 12 as “bind the name age to the value 12”. Names can contain letters, digits and underscores, and must not start with a digit. Pick names that say what the value means: age is better than a.

Every program you write starts the same way: bind start = do { ... }. The instructions inside the braces run from top to bottom.

Rebinding: how Ling “changes” things

Ling has no assignment statement. You can’t write score = score + 5; that is a parse error. To give a name a new value, bind it again:

bind start = do {
  bind score = 10
  println("score is ", score)
  bind score = score + 5
  println("score is ", score)
  bind score = score * 2
  println("score is ", score)
}
score is 10
score is 15
score is 30

bind score = score + 5 works out the right-hand side first, using the current value of score, and then puts the label score on the result. Make it a habit: whenever you want to change something, type bind.

Printing

println prints its arguments and ends the line. print does the same: in Ling both finish with a new line. When you pass several arguments, they are printed one after the other with nothing in between, not even a space:

bind start = do {
  println("sum", 1 + 2)
  println("sum: ", 1 + 2)
  println("a", "b", "c")
  println("line one\nline two")
  println("She said \"hi\"")
}
sum3
sum: 3
abc
line one
line two
She said "hi"

If you want a space, put it inside your text, as in "sum: ".

Arithmetic

Ling uses the usual symbols: +, -, *, /, and % for the remainder.

bind start = do {
  println(7 + 3)
  println(7 / 2)
  println(7 % 2)
  println(2 + 3 * 4)
  println((2 + 3) * 4)
  println(round(3.7))
  println(sqrt(81))
}
10
3.5
1
14
20
4
9

Division gives an exact answer (3.5), not a rounded one. Multiplication happens before addition, so 2 + 3 * 4 is 14. Use parentheses when you mean something else. round and sqrt are builtins: functions that come with Ling.

Converting between text and numbers

You can join two pieces of text with +. To join a number to text, turn it into text first with str (to_str is the same function). To go the other way, to_number turns text into a number:

bind start = do {
  bind apples = 3
  println("I have " + str(apples) + " apples")
  bind typed = "12"
  println(to_number(typed) + 1)
  println(format("{} + {} = {}", 2, 3, 2 + 3))
  println(format("about {:.2}", 3.14159))
}
I have 3 apples
13
2 + 3 = 5
about 3.14

format fills each {} in a template with the next argument. {:.2} shows a number with two decimal places.

Comparisons and booleans

A comparison asks a yes-or-no question and gives back true or false:

bind start = do {
  println(5 > 3)
  println(5 == 5)
  println(5 != 5)
  println("cat" == "cat")
  bind big = 100 > 50
  println("big is ", big)
  println(true && false)
  println(true || false)
  println(!true)
}
true
true
false
true
big is true
false
true
false

The comparisons are ==, !=, <, >, <= and >=. A single = is never a comparison; it only appears in bind. Combine answers with && (and: both must be true), || (or: at least one must be true) and ! (not). Don’t chain comparisons as in maths: write x > 1 && x < 10, not 1 < x < 10.

Comments

Everything after # or // on a line is a comment. Ling ignores it; it is a note for people.

# A tiny bill splitter
bind start = do {
  bind bill = 84.50
  bind people = 4      // friends at the table
  bind each = bill / people
  println("Each pays ", round(each * 100) / 100)
}
Each pays 21.13

round(x * 100) / 100 rounds a number to two decimal places for display.

Try it

  1. Bind your age and print In 10 years I will be ... with the right number.
  2. A rectangle is 12.5 wide and 8 tall. Print its area and its perimeter, each with a label.
  3. Bind n to 10. Using only bind, make it 11, then 22, then 4. Print n after each step.
  4. Convert 98.6 degrees Fahrenheit to Celsius with (f - 32) * 5 / 9 and print it rounded to one decimal place.
  5. Print "7" + "3" and then to_number("7") + to_number("3"). Why are they different?

Next: Decisions and Loops. For the builtins used here, see Output, Math and Logic and Text and Lists.

Decisions and Loops

Programs get interesting when they can choose between actions and repeat them. In this lesson you will use if and else to make decisions, while and for to repeat work, and match to pick between many cases. You will also learn the one scope rule that surprises nearly every Ling beginner.

Making a decision with if

bind start = do {
  bind temperature = 31
  if temperature > 30 {
    println("It is hot. Drink water.")
  }
  println("Done checking.")
}
It is hot. Drink water.
Done checking.

The pattern is if condition { ... }. The condition is anything that gives true or false, usually a comparison. If it is true, the block runs; if not, Ling skips it. There are no parentheses around the condition, and the braces are required.

Change temperature to 20 and run it again: only Done checking. is printed.

else and else if

else gives the other road. Chain more tests with else if. Ling checks them from top to bottom and runs the first block whose condition is true:

bind start = do {
  bind score = 83
  if score >= 90 {
    println("Grade A")
  } else if score >= 80 {
    println("Grade B")
  } else if score >= 70 {
    println("Grade C")
  } else {
    println("Keep practising")
  }
}
Grade B

83 is also at least 70, but the score >= 80 branch came first and won. Put the largest threshold first.

Combine conditions with && (and), || (or) and ! (not):

bind start = do {
  bind hour = 14
  bind raining = true
  bind have_umbrella = false
  if hour >= 9 && hour < 17 {
    println("The shop is open")
  }
  if raining && !have_umbrella {
    println("You will get wet")
  }
  if hour < 6 || hour > 22 {
    println("Go to sleep")
  } else {
    println("Stay awake")
  }
}
The shop is open
You will get wet
Stay awake

Repeating with while

A while loop repeats its block as long as the condition stays true:

bind start = do {
  bind i = 1
  while i <= 5 {
    println("Count: ", i)
    bind i = i + 1
  }
  println("Liftoff!")
}
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Liftoff!

Every while loop has three parts:

  1. Set a counter before the loop (bind i = 1).
  2. A condition that keeps the loop going (i <= 5).
  3. Inside the loop, do the work and move the counter (bind i = i + 1).

If you forget step 3, the condition stays true forever. Press Ctrl+C to stop a program that never ends.

Collecting a result

A bind inside a while (or an if) block changes the name outside it. That makes while the right tool for running totals:

bind start = do {
  bind total = 0
  bind n = 1
  while n <= 100 {
    bind total = total + n
    bind n = n + 1
  }
  println("1 + 2 + ... + 100 = ", total)
}
1 + 2 + ... + 100 = 5050

Counting with for

When you know how many times to repeat, for is shorter. It walks through a range of numbers, or through the items of a list:

bind start = do {
  for i in 0..4 {
    println("i is ", i)
  }
  for k in 1..4 {
    println(k, " x 7 = ", k * 7)
  }
  for color in ["red", "green", "blue"] {
    println("I like ", color)
  }
}
i is 0
i is 1
i is 2
i is 3
1 x 7 = 7
2 x 7 = 14
3 x 7 = 21
I like red
I like green
I like blue

0..4 means 0, 1, 2 and 3: the range stops just before the second number. So for i in 0..4 runs four times.

The end of a range must be a number, a name, or something in parentheses. Write 0..(n + 1) and 0..(len(xs)), never 0..len(xs): that version silently runs zero times.

The for scope rule

This is the rule that surprises everyone. Each pass of a for loop gets its own fresh copy of the names around it. A bind inside a for body does not change the name outside:

bind start = do {
  bind total = 0
  for i in 1..5 {
    bind total = total + i
  }
  println("after for: ", total)

  bind total = 0
  bind i = 1
  while i < 5 {
    bind total = total + i
    bind i = i + 1
  }
  println("after while: ", total)
}
after for: 0
after while: 10

The rule of thumb: use for for loops that only do something (print, draw, play a note). When a loop must leave a result behind (a total, a count, a growing list), use while.

Ling has no working break or continue. To leave a while loop early, make its condition false, for example with a flag such as bind searching = false.

Loops inside loops

A loop can sit inside another. Here the outer for only prints, and the inner while builds up the text of each row:

bind start = do {
  for row in 1..5 {
    bind line = ""
    bind col = 0
    while col < row {
      bind line = line + "*"
      bind col = col + 1
    }
    println(line)
  }
}
*
**
***
****

Choosing with match

When you compare one value against many possibilities, match is tidier than a long else if chain. Each arm is written pattern => action. Ling runs the first arm that fits, and _ fits anything:

bind start = do {
  bind day = 3
  match day {
    1 => println("Monday")
    2 => println("Tuesday")
    3 => println("Wednesday")
    _ => println("Some other day")
  }
  bind word = match "green" {
    "red" => "stop"
    "green" => "go"
    _ => "wait"
  }
  println(word)
}
Wednesday
go

match works with numbers and text, and it can produce a value that you bind. Always end with a _ arm: if nothing matches, match quietly gives (), the “nothing” value.

Try it

  1. Bind a number n and print positive, negative or zero.
  2. Print the 6 times table from 6 x 1 to 6 x 10 with a for loop.
  3. Use a while loop to add up the even numbers from 2 to 50. (The answer is 650.)
  4. Start with 1 and double it until it is larger than 1000. Print how many doublings it took.
  5. Rewrite the grade example with the tests in the opposite order (score >= 70 first). What goes wrong?

Next: Functions. For the full rules, see Syntax and Known Limits.

Functions

A function is a named recipe: you write the steps once and use them as often as you like. You have already used builtin functions such as println, round and str. In this lesson you will write your own with fn, give them parameters, get answers back with return, and let a function call itself.

Defining and calling a function

fn greet(name) {
  println("Hello, " + name + "!")
}

bind start = do {
  greet("Ada")
  greet("Grace")
  greet("Mina")
}
Hello, Ada!
Hello, Grace!
Hello, Mina!
  • fn says “I am defining a function”.
  • greet is the function’s name.
  • name in parentheses is a parameter: a blank that is filled in each time you call the function.
  • The braces hold the body, the steps the function carries out.

Defining a function doesn’t run it. The body runs only when you call the function, as in greet("Ada"). The value in the parentheses is the argument; it becomes the value of name for that call.

Functions live at the top level of the file, outside bind start. The instructions that actually do things live inside start.

Getting answers back with return

Often you want a function to compute something and hand the answer back. That is what return does. A function can take several parameters, separated by commas:

fn square(n) {
  return n * n
}

fn average(a, b) {
  return (a + b) / 2
}

bind start = do {
  println(square(7))
  println(average(10, 25))
  println(square(average(2, 4)))
}
49
17.5
9

Because square(7) has a value, you can use it anywhere a value fits: inside println, inside a bigger expression, or as the argument of another call. square(average(2, 4)) is worked out from the inside: average(2, 4) is 3, and square(3) is 9.

Early returns

The first return that runs ends the function. Use that to handle special cases first:

fn describe(n) {
  if n < 0 {
    return "negative"
  }
  if n == 0 {
    return "zero"
  }
  return "positive"
}

fn cube(n) { n * n * n }

bind start = do {
  println(describe(-5))
  println(describe(0))
  println(describe(12))
  println(cube(3))
}
negative
zero
positive
27

No else is needed in describe, because a return already leaves the function. cube shows a shortcut: without return, a function gives back the value of its last expression. A function that computes nothing, like greet, gives back (), the “nothing” value.

What a function can see

Each call gets its own private names: its parameters and anything it binds. They can’t clash with names in the code that called it:

bind tax_rate = 0.2

fn with_tax(price) {
  bind total = price + price * tax_rate
  return total
}

bind start = do {
  bind total = 99
  println(with_tax(50))
  println("my total is still ", total)
}
60
my total is still 99

A function can see bindings at the top level of the file, such as tax_rate. That is a good place for constants. It can’t see the local names of the function that called it, so pass what it needs as arguments.

Functions that call themselves

A function may call itself. This is recursion. It needs two parts:

  1. A base case, so simple that the answer is known directly.
  2. A recursive case, which solves a smaller version of the problem by calling itself.

The factorial of 5 is 5 * 4 * 3 * 2 * 1, which is the same as 5 * factorial(4):

fn factorial(n) {
  if n <= 1 {
    return 1
  }
  return n * factorial(n - 1)
}

fn fib(n) {
  if n < 2 {
    return n
  }
  return fib(n - 1) + fib(n - 2)
}

bind start = do {
  println("5! = ", factorial(5))
  println("10! = ", factorial(10))
  for i in 0..10 {
    println("fib(", i, ") = ", fib(i))
  }
}
5! = 120
10! = 3628800
fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
fib(8) = 21
fib(9) = 34

Follow factorial(3) by hand: it returns 3 * factorial(2), which needs 2 * factorial(1), and factorial(1) is the base case, 1. The answers climb back up: 2 * 1 = 2, then 3 * 2 = 6. Without a base case, the function would call itself until it runs out of room.

Putting it together: FizzBuzz

Count from 1 to 15. For multiples of 3 print Fizz, for multiples of 5 print Buzz, for multiples of both print FizzBuzz, otherwise print the number:

fn fizzbuzz(n) {
  if n % 15 == 0 {
    return "FizzBuzz"
  }
  if n % 3 == 0 {
    return "Fizz"
  }
  if n % 5 == 0 {
    return "Buzz"
  }
  return str(n)
}

bind start = do {
  for n in 1..16 {
    println(fizzbuzz(n))
  }
}
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

The test for 15 comes first; otherwise 15 would stop at the test for 3 and print Fizz. The function turns a number into a word, and start only loops and prints. A good function does one thing, takes what it needs as parameters, and has a name that says what it does.

Functions as values

In some languages you store a function in a binding or pass it to another function. Ling has a short closure syntax for this, |x| x * 2, but in the current version function values are the least reliable part of the language: a closure stored in a binding, or a function passed as an argument, may give () or report unknown function. The one form that always works is calling a closure right where you write it:

bind start = do {
  println((|x| x + 1)(5))
}
6

For now, write a named fn and call it by name. See Known Limits for the details.

Tip: If you misspell a function name, the default engine prints () instead of an error. When a function seems to “do nothing”, run the program with ling run --interp yourfile.ling, which reports unknown function.

Try it

  1. Write is_even(n) that returns true or false. Print is_even(10) and is_even(7).
  2. Write max3(a, b, c) that returns the largest of three numbers. (The builtin max takes two; you can nest it.)
  3. Write sum_to(n) with a while loop, then sum_to_r(n) with recursion. Both should give 5050 for 100.
  4. Write power(base, exp) recursively, using only multiplication. power(2, 10) is 1024.
  5. Write grade(score) returning "A", "B", "C" or "F", and print the grades for 95, 85, 75 and 40.

Next: Lists and Text. For the full rules, see Syntax.

Lists and Text

Until now each name held one value. In this lesson you will keep many values together in a list, walk through them with loops, and take text apart and put it back together. You will finish with a small word counter.

Making a list

Write a list between square brackets, with commas between the items:

bind start = do {
  bind fruits = ["apple", "banana", "cherry"]
  println(fruits)
  println(len(fruits))
  println(list_get(fruits, 0))
  println(fruits[2])
}
[apple, banana, cherry]
3
apple
cherry
  • Printing a list shows its items in square brackets.
  • len(fruits) is the number of items.
  • list_get(fruits, 0) reads the item at position 0. fruits[2] is a shorter way to write list_get(fruits, 2).

Positions start at 0. The first item is at position 0, and the last of three items is at position 2. Think of the position as “how many items do I skip?”. Keep positions between 0 and len(xs) - 1: asking for a position that doesn’t exist gives an empty value on the default engine and an error on the interpreter.

Changing a list: always rebind

list_push adds an item at the end, and list_set replaces the item at a position. Both give you a new list. Bind the name again to keep it:

bind start = do {
  bind fruits = ["apple", "banana", "cherry"]
  bind fruits = list_push(fruits, "date")
  println(fruits)
  bind fruits = list_set(fruits, 1, "blueberry")
  println(fruits)
  println("now ", len(fruits), " fruits")
}
[apple, banana, cherry, date]
[apple, blueberry, cherry, date]
now 4 fruits

Always write bind fruits = list_push(fruits, "date"), never just list_push(fruits, "date") on its own. This is the same rebinding habit you learned in Values and Bindings.

Building a list in a loop

Start with an empty list from list_new() and push items into it. Remember the scope rule from Decisions and Loops: a for body can’t leave results behind, so build lists with while:

bind start = do {
  bind squares = list_new()
  bind i = 1
  while i < 8 {
    bind squares = list_push(squares, i * i)
    bind i = i + 1
  }
  println(squares)
}
[1, 4, 9, 16, 25, 36, 49]

Walking through a list

For reading a list, for is fine. When you also need a running result, use while with a position:

bind start = do {
  bind scores = [72, 95, 88, 61, 79]
  for s in scores {
    println("score: ", s)
  }
  bind total = 0
  bind best = scores[0]
  bind i = 0
  while i < len(scores) {
    bind s = scores[i]
    bind total = total + s
    if s > best {
      bind best = s
    }
    bind i = i + 1
  }
  println("total: ", total)
  println("average: ", total / len(scores))
  println("best: ", best)
  println("list_max says ", list_max(scores, 0))
}
score: 72
score: 95
score: 88
score: 61
score: 79
total: 395
average: 79
best: 95
list_max says 95

best starts as the first item, and every bigger item takes its place. The builtins list_max and list_min do the same job; their second argument is the answer for an empty list.

Text tools

Ling has a set of builtins for working with text:

bind start = do {
  bind s = "  Hello, Ling World  "
  println(len(s))
  bind s = trim(s)
  println("[" + s + "]")
  println(str_upper(s))
  println(str_lower(s))
  println(substr(s, 0, 5))
  println(str_find(s, "Ling"))
  println(str_find(s, "Python"))
  println(str_replace(s, "World", "Friend"))
  println(starts_with(s, "Hello"))
  println(str_repeat("ab", 3))
}
21
[Hello, Ling World]
HELLO, LING WORLD
hello, ling world
Hello
7
-1
Hello, Ling Friend
true
ababab
BuiltinPurpose
len(s)number of characters
trim(s)remove spaces from both ends
str_upper(s), str_lower(s)change case
substr(s, start, count)count characters starting at position start (from 0)
str_find(s, part)position of the first match, or -1 if there is none
str_replace(s, from, to)replace every from with to
starts_with(s, part), ends_with(s, part)true or false
str_repeat(s, n)the text repeated n times

Like the list builtins, these never change the original text. They return a new text, so bind the result: bind s = trim(s).

Splitting and joining

split cuts a text into a list wherever a separator appears. list_join glues a list back into one text (join is the same builtin):

bind start = do {
  bind line = "red,green,blue"
  bind parts = split(line, ",")
  println(parts)
  println(len(parts))
  println(list_join(parts, " | "))
  bind numbers = split("3 8 15", " ")
  println(to_number(numbers[1]) + 1)
}
[red, green, blue]
3
red | green | blue
9

The pieces from split are text. Use to_number before doing arithmetic with them.

Letter by letter

substr(s, i, 1) gives the single character at position i. Here it reverses a word:

fn reverse_text(s) {
  bind out = ""
  bind i = len(s) - 1
  while i >= 0 {
    bind out = out + substr(s, i, 1)
    bind i = i - 1
  }
  return out
}

bind start = do {
  println(reverse_text("Ling"))
  println(reverse_text("level") == "level")
}
gniL
true

A word counter

Ling has no dictionary type yet, so keep two lists side by side: words holds each distinct word and counts holds how often it appeared. A helper finds a word’s position:

fn index_of(items, target) {
  bind i = 0
  while i < len(items) {
    if items[i] == target {
      return i
    }
    bind i = i + 1
  }
  return -1
}

bind start = do {
  bind all = split("the cat saw the dog and the dog ran", " ")
  bind words = list_new()
  bind counts = list_new()
  bind i = 0
  while i < len(all) {
    bind w = all[i]
    bind pos = index_of(words, w)
    if pos == -1 {
      bind words = list_push(words, w)
      bind counts = list_push(counts, 1)
    } else {
      bind counts = list_set(counts, pos, counts[pos] + 1)
    }
    bind i = i + 1
  }
  bind k = 0
  while k < len(words) {
    println(words[k], ": ", counts[k])
    bind k = k + 1
  }
}
the: 3
cat: 1
saw: 1
dog: 2
and: 1
ran: 1

Note: == compares numbers, text and booleans. Comparing two lists with == is always false, even when they hold the same items. Compare them item by item.

Try it

  1. Make a list of five numbers and print their total with a while loop.
  2. Split "3,8,15,4" on commas, convert each piece with to_number, and print the biggest.
  3. Write count_vowels(s) that counts the letters a, e, i, o, u. (Hint: lower-case the text, then test each character with str_find("aeiou", ch) != -1.)
  4. Use str_replace and str_lower to make a palindrome test that ignores spaces, and try it on "never odd or even".
  5. Extend the word counter so that it also prints the most common word.

Next: Drawing and Games. For every list and text builtin, see Text and Lists.

Drawing and Games

On this page you draw flat 2D pictures with circles, triangles, lines and gradients, make them react to the keyboard and the mouse, and put it all together into a small game you can play and change. Everything here uses builtins that come with Ling, so you don’t need any image files or a game engine.

These programs open a window, so their code blocks have no output. Press Escape or close the window to stop any of them.

Open a window and run the frame loop

Every graphical program has the same shape: open a window once, then repeat clear, draw, present until the window closes.

bind start = do {
    open_window(640, 400, "Frame loop")
    bind t = 0
    while window_is_open() {
        fill(10, 12, 30)                         # 1. clear
        set_color(255, 200, 80)                  # 2. draw
        draw_disc(320 + 200 * sin(t * 0.05), 200, 30)
        present()                                # 3. show the frame
        bind t = t + 1
    }
}
  • open_window(w, h, title) opens the window. Size first, title last.
  • window_is_open() becomes false when the window is closed or Escape is pressed.
  • fill(r, g, b) paints the whole window. Colours are red, green and blue from 0 to 255.
  • present() puts the finished frame on screen. A frame without present() is invisible.
  • t counts frames. sin(t * 0.05) swings smoothly between -1 and 1, which moves the disc back and forth.

There is no delta-time builtin. If you need real seconds, use time_now() (seconds since the program started) or frame_count().

The 2D canvas

The window is a grid of pixels. Two things differ from maths class:

  • The origin (0, 0) is the top-left corner.
  • y grows downward. y = 300 is lower on the screen than y = 100.

You draw with a pen. set_color(r, g, b) picks the pen colour, and every shape after it uses that colour until you change it.

BuiltinDraws
fill(r, g, b)the whole window in one colour
draw_disc(cx, cy, r)a filled circle
draw_circle(cx, cy, r)a circle outline
triangle(x0, y0, x1, y1, x2, y2)a filled triangle
draw_line(x0, y0, x1, y1)a thin line
draw_arc(cx, cy, r, a0, a1, segments)part of a circle outline; angles in radians, clockwise
draw_poly([x0, y0, x1, y1, ...])a filled polygon from a flat list of points
grad_rect(x, y, w, h, r0, g0, b0, r1, g1, b1, dir)a rectangle fading between two colours; dir 1 is top to bottom, 0 is left to right
set_color_hsl(h, s, l)pen colour by hue 0-360, saturation 0-100, lightness 0-100

There is no plain filled-rectangle builtin. A gradient from a colour to the same colour is a flat rectangle, so write your own helper:

fn rect(x, y, w, h, r, g, b) {
    grad_rect(x, y, w, h, r, g, b, r, g, b, 1)
}

Tip: If a drawing call seems to do nothing, check its spelling. An unknown name such as draw_rect is silently ignored.

A landscape

Draw in layers, from back to front. Later shapes paint over earlier ones.

fn rect(x, y, w, h, r, g, b) {
    grad_rect(x, y, w, h, r, g, b, r, g, b, 1)
}

fn tree(x, ground) {
    rect(x - 6, ground - 50, 12, 50, 110, 70, 40)
    set_color(40, 150, 70)
    draw_disc(x, ground - 70, 32)
    draw_disc(x - 20, ground - 50, 24)
    draw_disc(x + 20, ground - 50, 24)
}

bind start = do {
    open_window(800, 500, "Landscape")
    bind t = 0
    while window_is_open() {
        grad_rect(0, 0, 800, 380, 30, 40, 110, 250, 150, 140, 1)   # sky
        set_color(255, 220, 120)
        draw_disc(600, 300, 60)                                     # sun
        set_color(70, 60, 110)
        triangle(0, 380, 150, 190, 300, 380)                        # mountains
        triangle(200, 380, 380, 150, 560, 380)
        rect(0, 380, 800, 120, 50, 110, 60)                         # ground
        tree(120, 440)
        tree(330, 460)
        tree(690, 450)
        set_color(20, 20, 30)                                       # a bird
        bind flap = sin(t * 0.15) * 6
        draw_arc(150, 120 - flap, 18, 3.4, 6.0, 16)
        draw_arc(186, 120 - flap, 18, 3.4, 6.0, 16)
        present()
        bind t = t + 1
    }
}

tree(x, ground) places the trunk and leaves relative to its arguments, so you can plant as many trees as you like. The bird’s wings are two arcs. Because y points down, angles run clockwise: 0 points right and 3.14 points left.

Read the keyboard

Ling has no event handlers. Once per frame you ask whether a key is down:

  • key_down("left") is true for as long as the key is held.
  • key_pressed("space") is true only on the one frame when the key goes down. Use it for things that happen once per press, such as jumping or restarting.

Keys are named in lower case: "a" to "z", digits, "left", "right", "up", "down", "space", "enter", "escape", "lshift" and more. An unknown name is just false.

bind start = do {
    open_window(640, 400, "Move the ball")
    bind x = 320
    bind y = 200
    while window_is_open() {
        bind speed = 3
        if key_down("lshift") {
            bind speed = 8
        }
        if key_down("left") {
            bind x = x - speed
        }
        if key_down("right") {
            bind x = x + speed
        }
        if key_down("up") {
            bind y = y - speed
        }
        if key_down("down") {
            bind y = y + speed
        }
        bind x = clamp(x, 20, 620)
        bind y = clamp(y, 20, 380)

        fill(10, 10, 30)
        set_color(255, 180, 60)
        draw_disc(x, y, 20)
        present()
    }
}

Nearly every game has these three parts:

  1. State: x and y live outside the loop, so they survive from frame to frame.
  2. Input and update: the key_down checks change the state, and clamp keeps the ball inside the window.
  3. Draw: the picture is made from the state.

Keep that order each frame: input, update, draw.

Read the mouse

mouse_x() and mouse_y() give the pointer position in pixels. mouse_down() is true while the left button is held, mouse_down_right() while the right one is.

bind start = do {
    open_window(640, 400, "Mouse paint")
    fill(245, 240, 225)
    bind hue = 0
    while window_is_open() {
        if mouse_down() {
            set_color_hsl(hue, 80, 50)
            draw_disc(mouse_x(), mouse_y(), 10)
            bind hue = (hue + 3) % 360
        }
        if mouse_down_right() {
            fill(245, 240, 225)
        }
        present()
    }
}

This program doesn’t call fill every frame, so the paint stays on the canvas. A right click calls fill once to wipe it.

A tiny game: Star Catcher

Stars fall from the sky and you slide a basket to catch them. Each catch scores a point and makes the next star faster. Miss three and the game is over; press Space to play again.

Before writing a game, list its state (the basket’s x, the star’s position, the fall speed, the score, the lives), its rules (how the state changes each frame) and its picture (how the state is drawn).

fn rect(x, y, w, h, r, g, b) {
    grad_rect(x, y, w, h, r, g, b, r, g, b, 1)
}

# A five-pointed star: a polygon with ten corners.
fn star(cx, cy, size, spin) {
    bind pts = []
    bind i = 0
    while i < 10 {
        bind a = spin + i * 0.6283185
        bind r = size
        if i % 2 == 1 {
            bind r = size * 0.45
        }
        bind pts = list_push(pts, cx + cos(a) * r)
        bind pts = list_push(pts, cy + sin(a) * r)
        bind i = i + 1
    }
    draw_poly(pts)
}

bind start = do {
    open_window(640, 480, "Star Catcher")
    bind basket_x = 320
    bind star_x = 100 + rand() * 440
    bind star_y = 0
    bind fall = 3
    bind score = 0
    bind lives = 3
    bind t = 0

    while window_is_open() {
        if lives > 0 {
            # input
            if key_down("left") || key_down("a") {
                bind basket_x = basket_x - 7
            }
            if key_down("right") || key_down("d") {
                bind basket_x = basket_x + 7
            }
            bind basket_x = clamp(basket_x, 50, 590)
            # update
            bind star_y = star_y + fall
            if star_y > 440 {
                if abs(star_x - basket_x) < 55 {
                    bind score = score + 1
                    bind fall = fall + 0.25
                } else {
                    bind lives = lives - 1
                }
                bind star_x = 50 + rand() * 540
                bind star_y = 0
            }
        } else {
            if key_pressed("space") {
                bind lives = 3
                bind score = 0
                bind fall = 3
                bind star_y = 0
            }
        }

        # draw
        grad_rect(0, 0, 640, 480, 15, 15, 50, 40, 25, 80, 1)
        set_color(255, 220, 80)
        star(star_x, star_y, 24, t * 0.05)
        rect(basket_x - 50, 445, 100, 14, 90, 190, 255)
        set_color(255, 255, 255)
        ui_text(16, 14, 22, "SCORE " + to_str(score))
        ui_text(500, 14, 22, "LIVES " + to_str(lives))
        if lives <= 0 {
            set_color(255, 110, 110)
            ui_text(170, 200, 36, "GAME OVER")
        }
        present()
        bind t = t + 1
    }
    print("Final score: ", score)
}

How it works:

  • The star. star builds a flat list of ten corner coordinates with cos and sin, alternating a long and a short radius, and hands it to draw_poly. The spin angle makes it turn as it falls.
  • Game state. if lives > 0 { ... } else { ... } switches between “playing” and “game over”. In the game-over branch only the restart key is checked.
  • Catching. When the star reaches the basket’s height, abs(star_x - basket_x) < 55 decides whether it was caught. rand() returns a number from 0 up to 1, so 50 + rand() * 540 is a random x between 50 and 590.
  • Difficulty. bind fall = fall + 0.25 makes every next star a little faster.
  • Text. ui_text(x, y, size, text) draws text with a built-in line font in the pen colour. It needs no font file and draws Latin capital letters and digits.
  • The end. When you close the window, the loop ends and the last line prints your score in the terminal.

Try it

  1. Draw a face: a big yellow disc, two small dark discs for eyes, and an arc for the mouth (try draw_arc(200, 210, 60, 0.4, 2.74, 24) under a face centred at (200, 200)).
  2. Make the ball bounce: keep speeds vx and vy, add them to x and y each frame, and flip the sign (bind vx = 0 - vx) when the ball reaches a wall.
  3. In the paint program, make the colour follow the pointer’s x position: bind hue = mouse_x() / 640 * 360.
  4. Add a best score to Star Catcher and show it under the score with ui_text.
  5. Add a bomb: a second falling object drawn as a dark disc that costs a life if you catch it.

Next: Sound and Music. For every drawing and input builtin, see Window and Camera and 2D Drawing and Images.

Sound and Music

Ling can make sound from nothing but numbers. On this page you turn notes into frequencies, play short tones from the keyboard, hold a tone that follows the mouse, play sound files, write a melody as two lists, and render a song to a WAV file.

Programs that play sound need speakers or headphones. Most of them also open a small window so they keep running while you listen, which is why their code blocks have no output. The ones that only compute and print are checked like any other example.

Notes are numbers

The pitch of a sound is its frequency, in hertz (Hz). Concert A is 440 Hz, and doubling a frequency raises the note by one octave.

Musicians name notes (“C4”, “A#3”); computers often number them with MIDI numbers: middle C is 60, each step up is one piano key, and A4 is 69. Two builtins convert between the two:

  • music_hz(pitch) turns a MIDI number, or a name such as "A4", into hertz.
  • music_note_name(hz) gives the name of the nearest note.
bind start = do {
    print("A4 is ", music_hz("A4"), " Hz")
    print("middle C (60) is ", round(music_hz(60) * 100) / 100, " Hz")
    print("440 Hz is ", music_note_name(440))
    print("300 Hz is nearest to ", music_note_name(300))
    bind scale = [60, 62, 64, 65, 67, 69, 71, 72]
    for m in scale {
        print(m, "  ", music_note_name(music_hz(m)), "  ", round(music_hz(m)), " Hz")
    }
}
A4 is 440 Hz
middle C (60) is 261.63 Hz
440 Hz is A4
300 Hz is nearest to D4
60  C4  262 Hz
62  D4  294 Hz
64  E4  330 Hz
65  F4  349 Hz
67  G4  392 Hz
69  A4  440 Hz
71  B4  494 Hz
72  C5  523 Hz

Those eight numbers are the white keys from middle C to the next C: a C major scale.

Play a tone

audio_blip(freq, seconds, wave, volume) plays one short sound and returns at once.

audio_blip(440, 0.5, "triangle", 0.3)     # A4 for half a second, softly

The waveform sets the character of the sound:

WaveSounds like
"sine"pure and smooth, like a whistle
"triangle"soft and hollow
"square"buzzy, like an old video game
"saw"bright and harsh
"noise"hiss, good for drums and wind

An unknown name falls back to sine. For ready-made interface sounds there is also ui_sound(name) with "click", "hover", "confirm", "error", "toggle" and "tick".

A keyboard piano

Combine audio_blip with keyboard input. The keys A to K play a scale:

bind start = do {
    open_window(640, 200, "Keyboard piano")
    bind keys = ["a", "s", "d", "f", "g", "h", "j", "k"]
    bind notes = [60, 62, 64, 65, 67, 69, 71, 72]
    bind lit = -1
    while window_is_open() {
        bind i = 0
        while i < len(keys) {
            if key_pressed(keys[i]) {
                audio_blip(music_hz(notes[i]), 0.5, "triangle", 0.3)
                bind lit = i
            }
            bind i = i + 1
        }
        fill(20, 20, 35)
        bind i = 0
        while i < len(keys) {
            if i == lit {
                set_color(255, 200, 80)
            } else {
                set_color(240, 240, 240)
            }
            triangle(20 + i * 75, 40, 90 + i * 75, 40, 55 + i * 75, 170)
            bind i = i + 1
        }
        present()
    }
}

key_pressed is true for exactly one frame per press, so each press plays exactly one note.

A tone that follows the mouse

audio_tone makes a continuous sound that keeps playing until you silence it:

audio_tone(slot, x, y, z, w, freq, amp, lfo_rate, lfo_depth)
  • slot numbers the tone. Calling again with the same slot retunes that tone instead of starting a new one, so you can call it every frame.
  • x, y, z place the sound relative to the camera; z = 3 is straight ahead. w is an extra timbre parameter; 0 turns it off.
  • freq is the pitch in hertz and amp the loudness.
  • lfo_rate and lfo_depth add vibrato.
bind start = do {
    open_window(640, 400, "Theremin")
    audio_volume(0.5)
    while window_is_open() {
        bind freq = 110 * pow(2, mouse_x() / 640 * 3)
        bind loud = (1 - mouse_y() / 400) * 0.25
        audio_tone(0, 0, 0, 3, 0, freq, loud, 5, 0.01)
        fill(10, 10, 30)
        set_color(120, 220, 255)
        draw_disc(mouse_x(), mouse_y(), 12 + loud * 80)
        present()
    }
    audio_tone(0, 0, 0, 3, 0, 220, 0, 5, 0.01)
}

From the left edge to the right edge the pitch climbs three octaves, from 110 Hz to 880 Hz. A tone can’t be deleted, so the last line sets its loudness to 0. audio_volume(level) sets the master volume; keep it low while you experiment.

Play sound files

Ling reads WAV, MP3, OGG, FLAC and AAC files. There are three ways to play one:

BuiltinUse it for
music_load(path) then music_play(track)a song: one track at a time, with music_pause(), music_stop() and music_pos()
audio_bgm(path, volume)looping background music (WAV only)
audio_sample_load(path) then audio_sample_play_flat(id, volume, loop, pitch)short sound effects you play many times
bind start = do {
    bind song = music_load("song.ogg")
    bind hit = audio_sample_load("hit.wav")
    music_play(song)
    open_window(400, 200, "Player")
    while window_is_open() {
        if key_pressed("space") {
            audio_sample_play_flat(hit, 1.0, 0, 1.0)
        }
        fill(15, 25, 40)
        set_color(120, 255, 190)
        ui_text(20, 80, 20, "TIME " + to_str(round(music_pos())))
        present()
    }
}

music_load returns -1 if the file can’t be read. music_play always starts the track from the beginning, so don’t call it every frame. To resume after music_pause(), call music_play(-1).

A melody as two lists

A melody is a list of pitches and a matching list of durations. Durations are in beats, so the same tune plays faster or slower when you change the tempo. This player uses time_now() to start each note on time; 0 in the pitch list is a rest.

bind start = do {
    bind pitches = [64, 64, 65, 67, 67, 65, 64, 62, 60, 60, 62, 64, 64, 62, 62, 0]
    bind beats = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.5, 0.5, 2, 1]
    bind tempo = 132
    bind spb = 60 / tempo              # seconds per beat
    open_window(400, 200, "Ode to Joy")
    bind begun = time_now()
    bind next_at = 0
    bind index = 0
    while window_is_open() {
        bind now = time_now() - begun
        if index < len(pitches) && now >= next_at {
            bind d = beats[index] * spb
            if pitches[index] > 0 {
                audio_blip(music_hz(pitches[index]), d * 0.9, "triangle", 0.3)
            }
            bind next_at = next_at + d
            bind index = index + 1
        }
        if index >= len(pitches) && now > next_at + 0.5 {
            quit()
        }
        fill(25, 15, 45)
        present()
    }
    print("Played ", index, " notes")
}

Whenever the clock reaches next_at, the player plays the next note and moves next_at forward by that note’s length. The rhythm comes from the clock, not from the frame rate. quit() closes the window half a second after the last note.

Render a song to a file

Ling includes a small music studio (a DAW) that you script with daw_* builtins. You build a project with tracks, put clips on the tracks and notes in the clips, then bounce it to an ordinary WAV file. It all happens in memory, so it works without a sound card.

bind start = do {
    daw_new()
    daw_set_bpm(120)
    bind lead = daw_track_add("synth")
    bind clip = daw_clip_add_midi(lead, 0, 16)

    bind pitches = [60, 60, 67, 67, 69, 69, 67, 65, 65, 64, 64, 62, 62, 60]
    bind beats = [1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2]
    bind when = 0
    bind i = 0
    while i < len(pitches) {
        daw_note_add(lead, clip, when, beats[i] * 0.9, pitches[i], 0.8)
        bind when = when + beats[i]
        bind i = i + 1
    }
    print("song length: ", when, " beats")

    bind ok = daw_bounce("twinkle.wav", 0, when, 0.5, 16, "wav", 0.5)
    print("rendered: ", ok)
    bind song = music_load("twinkle.wav")
    print("about ", round(music_duration(song)), " seconds")
}
song length: 16 beats
rendered: 1
about 9 seconds
  1. daw_new() starts an empty project and daw_set_bpm(120) sets the tempo.
  2. daw_track_add("synth") adds a synthesizer track. "drums" is another kind: on a drum track, note 36 is the kick, 38 the snare and 42 the closed hi-hat.
  3. daw_clip_add_midi(track, start, length) adds an empty clip, measured in beats.
  4. daw_note_add(track, clip, start, length, pitch, velocity) adds one note. Velocity is how hard the key is hit, from 0 to 1.
  5. daw_bounce(path, from, to, tail, bits, format, quality) renders the beats from to to plus a tail in seconds, and returns 1 on success.

The file twinkle.wav appears in the folder where you ran the program. Play it with music_load and music_play.

Try it

  1. Print the frequency of every MIDI note from 60 to 72. What is the ratio between the first and the last?
  2. In the keyboard piano, make the key "z" play a drum-like hit: audio_blip(120, 0.15, "noise", 0.4).
  3. Change the piano’s notes to an A minor pentatonic scale: [57, 60, 62, 64, 67, 69, 72, 74].
  4. Put your own tune in the melody player. “Happy Birthday” starts with 60, 60, 62, 60, 65, 64.
  5. Render a drum loop: a "drums" track with a kick (36) on every beat and a snare (38) on beats 2 and 4, bounced to drums.wav.

Next: A Small Web Service. For every sound builtin, see Audio and Music.

A Small Web Service

Ling has a web server built in. On this page you serve a page, read what the browser sent, answer with JSON, keep notes in a SQLite database, and run the result as a small notes API. No framework and no extra installs are needed.

Code that starts a server can’t be checked in the terminal, so those blocks have no output. The helpers and handlers are ordinary functions, and you can test them without a server, as you will see below.

Hello, web

fn hello(req) {
    return "<h1>Hello from Ling!</h1>"
}

bind start = do {
    http_route("GET", "/", hello)
    http_serve("127.0.0.1", 8080)
}

Save it as hello.ling, run it, and open http://127.0.0.1:8080/ in a browser:

ling run hello.ling
  • http_route(method, path, handler) registers a handler for one method and one exact path. Register every route before you start the server.
  • http_serve(host, port) starts the server and keeps answering requests until you press Ctrl+C. Use "127.0.0.1" for your own machine only, "0.0.0.0" to accept connections from the network.
  • A handler takes the request and returns a string. A string answers 200 with an HTML page.
  • Any path you didn’t register answers 404 not found.

To serve files such as CSS, images or a whole folder, add http_static(prefix, dir): http_static("/css", "css") maps /css/site.css to the file css/site.css. Static files are sent byte for byte and never pass through your handlers.

What the browser sent

The handler’s argument is a Request with these text fields:

FieldContent
method"GET", "POST", … in upper case
paththe path without the query string
querythe raw query string after ?, such as name=Ada&page=2
bodythe request body as text
cookiethe raw Cookie header
authorizationthe raw Authorization header
client_ipthe client address from proxy headers, or ""

Routes match the path exactly, so there are no path parameters like /note/2. Pass values in the query string instead (/note?id=2) and read them with query_param(text, name, default). It percent-decodes the value, and it works on form bodies too, since they use the same a=1&b=2 format.

bind start = do {
    bind qs = "name=Ada%20Lovelace&lang=en"
    print(query_param(qs, "name", "nobody"))
    print(query_param(qs, "page", "1"))
}
Ada Lovelace
1

Never put user text straight into HTML. html_escape turns & < > " ' into entities:

bind start = do {
    print(html_escape("<b>Tom & Jerry</b>"))
}
&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;

So a greeting page looks like this:

fn greet(req) {
    bind name = html_escape(query_param(req.query, "name", "world"))
    return "<h1>Hello, " + name + "!</h1>"
}

Answering with JSON

To set a status code or a content type, return a record instead of a string. Declare a form whose field names are any of status, content_type, body, set_cookie and location. Records are built by position, and the server reads the fields by name:

form Response { status, content_type, body }

fn json(status, body) {
    return Response(status, "application/json", body)
}

Ling builds JSON by joining strings. Pass every piece of text through json_escape, which escapes quotes, backslashes and control characters:

bind start = do {
    bind title = "Say \"hi\""
    print("{\"title\":\"" + json_escape(title) + "\"}")
}
{"title":"Say \"hi\""}

For a redirect, return status 302 with a location, for example Response(302, "text/plain", "", "", "/new") with a form that declares all five fields.

A notes API with SQLite

Now store notes in a database. Three builtins cover SQLite:

BuiltinPurpose
db_open(path)open (or create) a database file, or ":memory:"
db_exec(sql, params...)run a statement that changes data; returns the number of rows changed
db_query(sql, params...)run a query; returns a list of rows, read as row.column

Parameters bind by position as ?1, ?2 and so on. Always pass user input as a parameter, never by joining it into the SQL text.

Handlers are just functions, so you can try them without a server by building a request yourself. Here Request is a small form with the fields the handlers use:

form Response { status, content_type, body }
form Request { method, path, query, body }

fn json(status, body) {
    return Response(status, "application/json", body)
}

fn note_json(row) {
    return "{\"id\":" + row.id + ",\"text\":\"" + json_escape(row.text) + "\"}"
}

fn list_notes(req) {
    bind rows = db_query("SELECT id, text FROM notes ORDER BY id")
    bind out = "["
    bind i = 0
    while i < len(rows) {
        if i > 0 {
            bind out = out + ","
        }
        bind out = out + note_json(rows[i])
        bind i = i + 1
    }
    return json(200, out + "]")
}

fn add_note(req) {
    bind text = query_param(req.body, "text", "")
    if text == "" {
        return json(400, "{\"error\":\"text is required\"}")
    }
    db_exec("INSERT INTO notes(text) VALUES (?1)", text)
    bind rows = db_query("SELECT id, text FROM notes ORDER BY id DESC LIMIT 1")
    return json(201, note_json(rows[0]))
}

fn setup() {
    db_open(":memory:")
    db_exec("CREATE TABLE notes(id INTEGER PRIMARY KEY AUTOINCREMENT, text TEXT NOT NULL)")
}

bind start = do {
    setup()
    bind r1 = add_note(Request("POST", "/notes", "", "text=Buy%20milk"))
    print(r1.status, " ", r1.body)
    bind r2 = add_note(Request("POST", "/notes", "", "text=Say+%22hi%22"))
    print(r2.status, " ", r2.body)
    bind r3 = add_note(Request("POST", "/notes", "", ""))
    print(r3.status, " ", r3.body)
    bind r4 = list_notes(Request("GET", "/notes", "", ""))
    print(r4.status, " ", r4.body)
}
201 {"id":1,"text":"Buy milk"}
201 {"id":2,"text":"Say \"hi\""}
400 {"error":"text is required"}
200 [{"id":1,"text":"Buy milk"},{"id":2,"text":"Say \"hi\""}]

The list is built with a while loop and an index, because a for body can’t update a binding outside the loop.

Serve it

Keep the handlers and setup exactly as above, drop the test Request form, and replace the start block with routes:

form Response { status, content_type, body }

fn json(status, body) {
    return Response(status, "application/json", body)
}

fn note_json(row) {
    return "{\"id\":" + row.id + ",\"text\":\"" + json_escape(row.text) + "\"}"
}

fn list_notes(req) {
    bind rows = db_query("SELECT id, text FROM notes ORDER BY id")
    bind out = "["
    bind i = 0
    while i < len(rows) {
        if i > 0 {
            bind out = out + ","
        }
        bind out = out + note_json(rows[i])
        bind i = i + 1
    }
    return json(200, out + "]")
}

fn add_note(req) {
    bind text = query_param(req.body, "text", "")
    if text == "" {
        return json(400, "{\"error\":\"text is required\"}")
    }
    db_exec("INSERT INTO notes(text) VALUES (?1)", text)
    bind rows = db_query("SELECT id, text FROM notes ORDER BY id DESC LIMIT 1")
    return json(201, note_json(rows[0]))
}

fn setup() {
    db_open("notes.db")
    db_exec("CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY AUTOINCREMENT, text TEXT NOT NULL)")
}

fn greet(req) {
    bind name = html_escape(query_param(req.query, "name", "world"))
    return "<h1>Hello, " + name + "!</h1>"
}

bind start = do {
    setup()
    http_route("GET", "/", greet)
    http_route("GET", "/notes", list_notes)
    http_route("POST", "/notes", add_note)
    http_serve("127.0.0.1", to_number(cli_arg("port", "8080")))
}

This version opens notes.db, a file next to the program, so the notes survive a restart. cli_arg("port", "8080") reads --port from the command line as text, and to_number turns it into a number.

ling run notes.ling --port 8080

Try it from another terminal:

$ curl -X POST -d "text=Buy milk" http://127.0.0.1:8080/notes
{"id":1,"text":"Buy milk"}
$ curl http://127.0.0.1:8080/notes
[{"id":1,"text":"Buy milk"}]
$ curl "http://127.0.0.1:8080/?name=%3Cb%3EAda"
<h1>Hello, &lt;b&gt;Ada!</h1>

More visitors at once: workers

By default one interpreter answers requests one at a time, so a slow handler makes the others wait. Static files from http_static don’t count: they are served separately and stream in parallel. To run handlers in parallel, pass a number of workers as the third argument to http_serve. Here it comes from the command line:

fn hello(req) {
    return "<h1>Hello from Ling!</h1>"
}

fn workers() {
    return to_number(cli_arg("workers", "1"))
}

bind start = do {
    http_route("GET", "/", hello)
    http_serve("127.0.0.1", 8080, workers())
}
ling run hello.ling --workers 4

With more than one worker, each extra interpreter loads your program fresh, and the start block runs only once, on the main one. So:

  • Handlers must be named top-level functions, like every handler on this page.
  • Keep settings in functions (like workers() above), not in top-level binds.
  • Each worker reopens the database you opened with db_open. Use a file, not ":memory:", or every worker gets its own empty database. SQLite makes a write wait its turn when two workers write at the same moment.

ling-lang.org runs on this

The website ling-lang.org is served by one Ling program, site.ling, built from the same builtins. It registers static folders for CSS, images, videos, the Ling Book PDFs and these docs with http_static, answers the landing page and a few JSON endpoints with http_route, and starts with workers:

ling run site.ling --host 0.0.0.0 --port 80 --workers 4

It also uses http_vhost(host, dir), which serves a folder at the root of another host name, matched against the request’s Host header. When dir is an http:// or https:// address instead of a folder, that host answers with a redirect to it. That is how the old docs.ling-lang.org sends visitors to ling-lang.org/docs:

fn register_docs_hosts() {
    http_vhost("docs.ling-lang.org", "https://ling-lang.org/docs")
    return true
}

Try it

  1. Add GET /note?id=2 that returns one note, or status 404 with {"error":"not found"} when db_query returns an empty list.
  2. Add POST /delete?id=2 with db_exec("DELETE FROM notes WHERE id = ?1", id). Use the number db_exec returns to answer 404 when nothing was deleted.
  3. Serve a folder public/ with an index.html at /app using http_static.
  4. Make the greeting page count visits in a visits table and show the total.

For every server builtin, see Web Server and HTTP and Database (SQLite).

Syntax

This page describes how a Ling program is written: its layout, literals, operators, bindings, functions and control flow. Every example was run with the current ling binary. Ling has two engines, the default JIT (ling run) and the interpreter (ling run --interp). Where they behave differently, this page says so, and Known Limits collects all the differences in one place.

Program structure

A Ling file is a list of top-level items:

ItemFormSee
bindingbind name = expressionBindings
functionfn name(a, b) { ... }Functions
record typeform Name { field, field }Records and enums
enum typechoose Name { Variant, Variant(a) }Records and enums
modulemod name { fn ... }Modules and Projects
importuse "file.ling"Modules and Projects

Statements such as println(...) are not allowed at top level. They live inside a function or inside the entry point.

The entry point

A program starts at a top-level binding whose value is a do block:

bind start = do {
  println("Hello, Ling!")
}
Hello, Ling!

The runtime looks for a binding with one of these names, in this order: start, main, 启, เริ่ม, 시작, and the same word in several other languages. If none exists, it runs the first top-level binding whose value is a do block. A file with no such binding is a library, and ling run stops with no entry point.

bind main = do {
  println("main works too")
}
main works too

fn main() { ... } is not an entry point. Write bind main = do { ... }.

Comments and statements

A comment runs from # or // to the end of the line. There are no block comments. Statements are separated by newlines. A ; may end a statement, which lets you put two on one line.

# a hash comment
// a slash comment
bind start = do {
  println("a") // a trailing comment
  println("b"); println("c")
}
a
b
c

Identifiers

A name starts with a letter or _ and continues with letters, digits and _. Any Unicode letter counts, so Chinese, Japanese, Korean and Thai names work. Names are case-sensitive.

bind start = do {
  bind 名前 = "Ling"
  bind ชื่อ = 3
  println(名前)
  println(ชื่อ + 1)
}
Ling
4

Keywords that do nothing yet (such as change, stop or maybe, see Keywords) are ordinary names to the parser, so bind stop = 2 works. Don’t use an active keyword such as for or if as a name.

Literals

LiteralFormNotes
number42, 3.14Decimal digits with at most one fractional part. All numbers are 64-bit floats.
text"hello"Double quotes only. May span lines. Escapes: \n \t \r \" \\ \0.
booleantrue, false
unit()The “nothing” value.
list[1, "two", 3.5]Items of any type, indexed from 0.
range0..5Half-open: 0, 1, 2, 3, 4. Used with for.
closure|x| x + 1See Closures.

There is no 1e3, 0xff, 1_000, .5 or 3.. There is no character literal ('a' is a parse error), no map literal and no tuple. Text has no interpolation: "{x}" is just those three characters. Build text with + and str(). An unknown escape such as \q is kept as written, backslash included.

bind start = do {
  println("line1\nline2")
  println("quote: \"q\" backslash: \\")
  println(1.5 + 1)
  println([1, "two", 3.5, true])
  println(())
}
line1
line2
quote: "q" backslash: \
2.5
[1, two, 3.5, true]
()

Operators and precedence

From tightest to loosest:

LevelOperatorsNotes
1. () [] :: ..field or method, call, index, module path, range
2-x !xprefix minus and not
3* / %% works on fractions: 7.5 % 2 is 1.5
4+ -+ joins text; a number on either side is turned into text
5== != < > <= >=
6&&
7||

All binary operators group to the left: 10 - 3 - 2 is 5.

bind start = do {
  println(2 + 3 * 4)
  println((2 + 3) * 4)
  println(10 - 3 - 2)
  println(-3 + 5)
  println(2 * -4)
  println(1 < 2 && 2 < 3)
  println("n=" + 5)
  println(7 / 2)
}
14
20
5
2
-8
true
n=5
3.5

Points to watch:

  • && and || always evaluate both sides, on both engines. x != 0 && 10 / x > 1 does not protect the division. Use a nested if instead.
  • Comparisons chain to the left: 1 == 1 == 1 means (1 == 1) == 1, which is false.
  • Prefix minus can’t be doubled: - - x is a parse error. 0 - x always works.
  • == on lists, records and enum values is always false. See Types and Values.

Bindings and rebinding

bind name = expression gives a value a name. There is no assignment: x = 5 is a parse error. To “change” a value, bind the name again. The new binding replaces the old one from that point on.

bind start = do {
  bind x = 1
  bind x = x + 10
  bind x = x * 2
  println(x)
}
22

Whether a rebinding is still visible after a block ends depends on the block:

InsideRebinding after the block ends
if / else bodykept
while bodykept, so while loops can accumulate
for bodylost: each pass starts from a fresh copy
match armlost
function bodylocal to the call
do { } blocklost on the interpreter, kept on the JIT; don’t rely on either
bind start = do {
  bind total = 0
  for i in 1..5 { bind total = total + i }
  println(total)
  bind sum = 0
  bind i = 1
  while i < 5 {
    bind sum = sum + i
    bind i = i + 1
  }
  println(sum)
}
0
10

A top-level bind is a global constant. Functions can read it, but a function never sees the local bindings of its caller:

bind RATE = 3
fn scaled(n) { n * RATE }
bind start = do {
  bind RATE = 100
  println(scaled(2))
}
6

Blocks

do { ... } runs its statements in order, and its value is the value of the last one. start is a do block, and you can use one anywhere an expression goes:

bind start = do {
  bind total = do {
    bind a = 20
    bind b = 22
    a + b
  }
  println(total)
}
42

Functions

fn name(params) { body } declares a function at top level (or inside a mod). Its result is the last expression in the body. return value leaves early, and a bare return returns (). Functions can be recursive and can be declared in any order. Functions can’t be nested inside other functions.

fn fib(n) {
  if n < 2 { return n }
  fib(n - 1) + fib(n - 2)
}
fn greet(name) { "Hello, " + name + "!" }
bind start = do {
  println(fib(15))
  println(greet("Ling"))
}
610
Hello, Ling!
  • Type annotations such as fn f(a: number) -> text are accepted and ignored.
  • If you pass too few arguments, the missing parameters are undefined. Using one is an error on the interpreter and gives () on the JIT.
  • Calling a function that doesn’t exist is an error on the interpreter, but the JIT quietly returns (). When something “does nothing”, run it with ling run --interp.

Closures

A closure is written |params| expression, for example |x| x * 2. A closure with no parameters needs a space: | | 42, because || is the “or” operator.

Calling a closure expression directly works everywhere:

bind start = do {
  println((|x| x + 1)(5))
}
6

Closures are the least reliable part of the language today. A closure stored in a variable can’t be called by name on the interpreter, and the JIT can’t pass a closure (or a function name) to a builtin such as list_map or try. Prefer a named fn. See Known Limits.

Control flow

if / else

if is an expression. Braces are required and the condition needs no parentheses. With no else, an if whose condition is false gives ().

bind start = do {
  bind n = 7
  bind label = if n < 0 { "negative" } else if n == 0 { "zero" } else { "positive" }
  println(label)
}
positive

Use real booleans in conditions. The engines disagree about "" and []; see Types and Values.

while

while condition { body } repeats while the condition holds. The body shares the enclosing scope, so it is the loop to use for counters and totals.

bind start = do {
  bind n = 27
  bind steps = 0
  while n != 1 {
    bind n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 }
    bind steps = steps + 1
  }
  println(steps)
}
111

for

for name in sequence { body } runs the body once per item of a range or list. A range lo..hi stops before hi.

bind start = do {
  for i in 1..4 { println(i * i) }
  for name in ["ada", "lin"] { println(str_upper(name)) }
}
1
4
9
ADA
LIN

There is no break or continue. To stop early, put the loop in a function and return from it, or use a while loop with a flag.

match

match value { pattern => expression, ... } tries each arm from top to bottom and evaluates the first one that fits. Patterns:

PatternMatches
_anything
0, "yes", truethat literal value
nameanything, and binds it to name
ok(p), bad(p)a result (see Errors and Results)
Variant(p, ...), Variant()an enum value
fn classify(n) {
  match n {
    0 => "zero",
    1 => "one",
    other => "many (" + str(other) + ")"
  }
}
bind start = do {
  println(classify(0))
  println(classify(9))
}
zero
many (9)

If no arm fits, the match gives (). There are no guards and no patterns for lists or records.

Records and enums

form declares a record type. Create a record by calling the type’s name with the fields in order, and read a field with .:

form Point { x, y }
bind start = do {
  bind p = Point(3, 4)
  println(p)
  println(p.x + p.y)
}
Point { x: 3, y: 4 }
7

choose declares an enum whose variants may carry values. Build a value by calling a variant, and take it apart with match. A variant without values is still written with parentheses: Dot(). The variant’s name is available as .tag.

choose Shape { Circle(r), Rect(w, h), Dot }
fn area(s) {
  match s {
    Circle(r) => 3 * r * r,
    Rect(w, h) => w * h,
    Dot() => 0
  }
}
bind start = do {
  println(area(Circle(2)))
  println(area(Rect(3, 4)))
  println(area(Dot()))
  println(Rect(1, 2).tag)
}
12
12
0
Rect

Records can’t be changed: build a new one instead. Point { x: 1, y: 2 } literal syntax is not supported. Calling a constructor with the wrong number of fields is an error on the interpreter and gives () on the JIT.

Parse traps

  • A line starting with - or [ continues the previous line. bind x = 5 followed by a line -1 makes x equal to 4, and a line starting with [1, 2] is read as indexing.
  • Range bounds. 0..n + 1 is a parse error and 0..len(xs) silently misbehaves. Put anything but a plain name or number in parentheses: 0..(n + 1), 0..(len(xs)).
  • Field annotations in form. form P { x: number, y: number } is a parse error, because an annotation right before } swallows the brace. End the list with a comma: form P { x: number, y: number, }.
  • No assignment. x = x + 1 is a parse error. Write bind x = x + 1.
  • Empty closure. Write | | expr, not || expr.

Keywords

Every Ling keyword has an English spelling and spellings in Chinese, Japanese, Korean and Thai. The lexer turns each spelling into the same token, so you can write a whole program in one language or mix them. This page lists every keyword, its spellings, and what it really does today.

Some keywords are reserved for future features and do nothing yet. They are marked below, so you won’t be surprised when stop doesn’t leave a loop.

Spellings

Where a cell has more than one spelling, all of them work. The first one is the usual choice. These spellings come from the lexer (src/lexer/mod.rs), which is what the runtime actually accepts. In a few places it differs from lexicons/*.ling, and the lexer wins: for example Japanese choose is 選択, Korean form is 구조, and Thai form is โครงสร้าง.

English中文日本語한국어ไทย
bind令 灵符束縛 バ바인드 묶ผูก
do执実行 執실행ทำ
fn函関数 関함수ฟังก์ชัน
if若 如もし만약 조건ถ้า
else否 否则他아니면มิฉะนั้น
while循 当間 一方동안 반복ขณะที่
for历繰 ために위해สำหรับ
in于の中안에ใน
match配一致매치จับคู่
return归戻る 帰る반환 귀환คืน
form形 形式構造구조โครงสร้าง
choose选 选择選択선택เลือกแบบ
mod核モジュール 模모듈โมดูล
use载 引使う사용ใช้ นำเข้า
as为として로서เป็น
ok好 可良い좋아ตกลง
bad坏 误悪い나쁨ผิดพลาด
true真真참จริง
false假偽거짓เท็จ
try试 尝试試す시도ลอง
type符型타입ชนิด
where条件但し단โดยที่
async异 异步非同期비동기ไม่พร้อมกัน
wait待 等待待つ기다려รอ
own独 拥有所有소유เป็นเจ้าของ
lend借貸す빌려ให้ยืม
share共 共享共有공유แบ่งปัน
move移 移动移動이동ย้าย
copy复 复制複製복사คัดลอก
stop止停止 止まれ 停め멈춤หยุด
again继续継続계속ทำอีก
change变 改变変える변경เปลี่ยนแปลง
post出 发布投稿게시ส่ง
give予 给渡す전달ให้
fit适合適合적합เหมาะสม
can能できる가능สามารถ
sure确 确定確か확실แน่นอน
maybe或 可能多分아마도อาจจะ
pure纯純粋순수บริสุทธิ์
spawn启 生成起動생성สร้าง
none无なし없음ไม่มี

asm has an English spelling only.

What each keyword does

KeywordStatusWhat it does
bindactiveCreates or replaces a binding. Also defines globals and the entry point.
doactiveA block whose value is its last statement.
fnactiveDeclares a function.
if / elseactiveConditional expression.
whileactiveLoop while a condition holds. The body shares the outer scope.
for / inactiveLoop over a range or list. Each pass gets a fresh scope.
matchactivePattern matching.
returnactiveLeaves the current function with a value.
formactiveDeclares a record type.
chooseactiveDeclares an enum type with optional payloads.
modactiveGroups functions into a namespace (name::f()).
use / asactiveLoads another file, optionally under an alias.
ok / badactiveBuild a result, and match one as a pattern.
true / falseactiveThe boolean values.
trybuiltinNot syntax: the builtin try(f, args...). Works on the interpreter only.
typeignoredtype Name as T is parsed and thrown away. It swallows what follows it, so avoid it.
whereignoredfn f(x) where ... { }: everything up to { is skipped.
asyncignoredasync fn runs synchronously, like a normal function.
waitunreliableGives the value on the interpreter but () on the JIT. Don’t use it.
own lend share move copyignoredPrefix words that return their operand unchanged. No ownership checks happen.
asmignoredasm("...") is meant for bare-metal builds. In a normal run it does nothing useful.
stopreservedDoes not break out of a loop.
againreservedDoes not continue a loop.
changereservedDoes nothing. Rebind with bind instead.
post give fit can sure maybe purereservedDo nothing. They are ordinary names to the parser.
spawnreservedDoes nothing, and there is no spawn builtin.
nonereservedNot a value. The interpreter reports undefined: 'none'. Use () for “nothing”.

Reserved words are ordinary names to the parser, so bind stop = 2 is legal. On the interpreter, a bare stop or again in a loop is an undefined error; on the JIT it is silently ignored and the loop keeps going.

Active keywords

bind

bind name = expression is the only way to create or “change” a variable. Binding a name again replaces it. See Bindings.

bind start = do {
  bind price = 40
  bind price = price + 2
  println(price)
}
42

do

do { ... } runs statements in order and gives the value of the last one. The entry point is a do block bound to start. See Blocks.

fn and return

fn name(params) { body } declares a function. The last expression is the result, and return leaves early.

fn describe(n) {
  if n > 100 { return "big" }
  "small"
}
bind start = do {
  println(describe(500))
  println(describe(5))
}
big
small

A return directly inside start ends the program quietly on the JIT and is an error (unexpected top-level return) on the interpreter.

if, else, while, for, in

The control-flow keywords are described in Control flow. There is no break or continue: stop and again are reserved words only. To leave a loop early, return from a function:

fn find(xs, target) {
  for x in xs {
    if x == target { return true }
  }
  false
}
bind start = do {
  println(find([1, 2, 3], 2))
  println(find([1, 2, 3], 9))
}
true
false

match

match value { pattern => expression, ... } evaluates the first arm whose pattern fits. Patterns are _, literals, a name, ok(p) / bad(p) and enum variants. See match.

form and choose

form declares a record type and choose an enum. See Records and enums.

choose Light { Red, Yellow, Green }
fn action(l) {
  match l {
    Red() => "stop",
    Yellow() => "slow",
    Green() => "go"
  }
}
bind start = do {
  println(action(Green()))
  println(Red().tag)
}
go
Red

mod, use, as

mod name { ... } groups functions, called as name::f(). use "file.ling" loads another file, and use "file.ling" as m makes its functions available as m::f(). See Modules and Projects.

ok and bad

ok(value) and bad(reason) build results. In a match they are patterns. A bad result prints as Err(...). See Errors and Results.

fn half(n) {
  if n % 2 == 0 { ok(n / 2) } else { bad("odd number") }
}
bind start = do {
  println(half(10))
  println(match half(7) { ok(v) => v, bad(e) => "error: " + e })
}
Ok(5)
error: odd number

true and false

The boolean literals. They are the values if and while should be given.

Keywords that are parsed but ignored

The ownership words own, lend, share, move and copy can stand in front of an expression (or a parameter name) and are then ignored. There is no borrow checker, and using a value after move is fine:

bind start = do {
  bind a = own [1, 2, 3]
  bind b = move a
  println(a)
  println(b)
}
[1, 2, 3]
[1, 2, 3]

async fn declares an ordinary function that runs immediately when called. where clauses after a function’s parameters are skipped:

async fn work(n) { n * 2 }
fn next(x) where x { x + 1 }
bind start = do {
  println(work(4))
  println(next(2))
}
8
3

For real parallel work, use the thread_* builtins.

Words that look like keywords but aren’t

  • start, main, 启, เริ่ม and 시작 are names, not keywords. The runtime looks for them to find the entry point. See The entry point.
  • result, loop, break, continue, struct, enum, let, const and similar words appear in some lexicon files but are not keywords. Ling has no loop and no let: use while and bind.
  • number, text, bool, list, map and tuple are documentation words only. Ling is dynamically typed. See Types and Values.

Types and Values

Ling is dynamically typed. You never declare a type: every value carries its own, and operators and builtins check it when they run. This page lists the kinds of values, how they print, how they behave in conditions and comparisons, and how to convert between them.

The kinds of values

TypeExamplesCreated byPrints as
number3, 2.5, -7number literals, arithmetic3, 2.5
text"abc"text literals, +, text builtinsabc
booltrue, falseliterals, comparisonstrue
unit()(), functions with no result, failed lookups()
list[1, "a", true]list literals, list_new, list builtins[1, a, true]
recordPoint(3, 4)calling a form namePoint { x: 3, y: 4 }
enum valueCircle(2), Dot()calling a choose variantCircle(2)
resultok(5), bad("e")ok and badOk(5), Err(e)
function|x| x + 1closures

There is no map or dictionary, no set, no tuple, no character type and no null. Use lists, records, or parallel lists for key-value data, or store it in SQLite with the db_* builtins. Type annotations such as x: number and -> text are accepted by the parser and ignored.

form Point { x, y }
bind start = do {
  println(42)
  println("text")
  println(true)
  println(())
  println([1, "a", true])
  println(Point(3, 4))
  println(ok(5))
  println(bad("no"))
}
42
text
true
()
[1, a, true]
Point { x: 3, y: 4 }
Ok(5)
Err(no)

Numbers

Every number is a 64-bit float. Whole numbers print without a decimal point, whole numbers up to 2^53 are exact, and division always gives the exact quotient.

bind start = do {
  println(7 / 2)
  println(10 / 5)
  println(7 % 3)
  println(0.1 + 0.2)
  println(1000000 * 1000000)
}
3.5
2
1
0.30000000000000004
1000000000000

Dividing by zero is not an error. On the interpreter 1 / 0 is inf; on the JIT it is (). On both, 0 / 0 is NaN.

Text

Text is a sequence of Unicode characters. len counts characters, not bytes, and + joins text. If one side of + is text, the other side is turned into text.

bind start = do {
  println(len("héllo"))
  println("a" + "b")
  println("n=" + 5)
  println(5 + "!")
}
5
ab
n=5
5!

Reading one character with s[i] works on the interpreter only. Use substr(s, i, 1) to get a character on both engines.

Lists

A list holds values of any type, indexed from 0. List builtins return a new list, so always bind the result: bind xs = list_push(xs, v). Reading past the end gives an empty value on the JIT and stops the interpreter with index N out of bounds. See Text and Lists for the list builtins.

Unit

() means “nothing”. A function whose last expression gives no value returns (), as does an if without else whose condition is false, and a match where no arm fits.

Records, enum values and results

Records come from form, enum values from choose, and results from ok and bad. Read a record field with .name, the variant name of an enum value with .tag, and open a result with match. See Records and enums and Errors and Results.

Truthiness

if and while should be given real booleans. Other values work, but the two engines don’t fully agree:

Value in a conditionJIT (default)Interpreter
true / falsetrue / falsetrue / false
0falsefalse
()falsefalse
other numbers, non-empty text, non-empty liststruetrue
"" (empty text)truefalse
[] (empty list)truefalse

Test emptiness explicitly with len(xs) == 0 or s == "". Also note that !x means x == false, so !0 and !"" are both false. Use ! on booleans only.

Comparing values

== and != compare numbers, text, booleans and () by value. Values of different types are never equal: 1 == "1" is false.

Lists, records, enum values and results are never equal, even with identical contents. Compare their elements or fields yourself.

form P { x }
bind start = do {
  println("abc" == "abc")
  println(1 == "1")
  println([1, 2] == [1, 2])
  println(P(1) == P(1))
  println(P(1).x == P(1).x)
}
true
false
false
false
true

<, >, <= and >= are for numbers. Ordering text ("a" < "b") gives false on the JIT and is an error on the interpreter.

Conversions

BuiltinConvertsNotes
str(v)any value to textSame text that println shows. Also called to_str.
to_number(s)text to numberIgnores surrounding spaces. Returns 0 if the text isn’t a number.
hex_to_number(s)hex text to numberNo 0x prefix: hex_to_number("ff") is 255.
int(x)number to whole numberCuts off the fraction, toward zero. Also called trunc.
floor(x) / ceil(x)number to whole numberRound down / up.
round(x)number to whole numberHalves round away from zero.
bind start = do {
  println(str(3) + "!")
  println(to_number(" 4 ") + 1)
  println(to_number("abc"))
  println(int(-3.7))
  println(floor(-2.5))
  println(round(2.5))
  println(hex_to_number("ff"))
}
3!
5
0
-3
-3
3
255

There is no builtin that tells you a value’s type, and no builtin that turns a value into a boolean. Because to_number returns 0 for bad input, check the text first if 0 is a valid answer. Errors and Results shows how.

Errors and Results

Ling has no exceptions. A function that can fail returns a result: ok(value) when it worked, or bad(reason) when it didn’t. The caller opens the result with match. This page covers results, the try builtin, runtime errors and tracebacks, and the “soft failure” convention most builtins follow.

ToolUse it for
ok(value) / bad(reason)Returning success or failure from your own functions
match r { ok(v) => ..., bad(e) => ... }Handling both cases
try(f, args...)Turning a runtime error into a bad result (interpreter only)
ling run --interpSeeing runtime errors with a traceback

Results: ok and bad

ok(value) wraps a success value and bad(reason) wraps a failure. The reason is usually text, but it can be any value. A result prints as Ok(...) or Err(...). (err is another name for bad when you build a result, but patterns must use bad.)

fn safe_div(a, b) {
  if b == 0 { bad("divide by zero") } else { ok(a / b) }
}
bind start = do {
  println(safe_div(6, 3))
  println(safe_div(1, 0))
}
Ok(2)
Err(divide by zero)

Handling a result with match

ok(v) and bad(e) are also patterns. The name inside the parentheses is bound to the wrapped value for that arm:

fn safe_div(a, b) {
  if b == 0 { bad("divide by zero") } else { ok(a / b) }
}
fn show(r) {
  match r {
    ok(v) => "value " + str(v),
    bad(why) => "failed: " + why
  }
}
bind start = do {
  println(show(safe_div(8, 2)))
  println(show(safe_div(8, 0)))
}
value 4
failed: divide by zero

match is the only way to look inside a result, so small helpers pay off:

fn unwrap_or(r, fallback) {
  match r {
    ok(v) => v,
    _ => fallback
  }
}
fn safe_sqrt(x) {
  if x < 0 { bad("negative") } else { ok(sqrt(x)) }
}
bind start = do {
  println(unwrap_or(safe_sqrt(16), 0))
  println(unwrap_or(safe_sqrt(-16), 0))
}
4
0

Calling a method on a result returns the wrapped value (ok(5).anything is 5). That is rarely what you want. Use match.

Validating input

Check each rule in turn and give each failure its own reason:

fn parse_age(text) {
  bind t = trim(text)
  if len(t) == 0 {
    bad("empty input")
  } else if to_number(t) == 0 && t != "0" {
    bad("not a number: " + t)
  } else if to_number(t) > 130 {
    bad("too large: " + t)
  } else {
    ok(to_number(t))
  }
}
fn show(r) {
  match r {
    ok(v) => "age " + str(v),
    bad(why) => "rejected (" + why + ")"
  }
}
bind start = do {
  for s in ["42", " 7 ", "", "forty", "200"] {
    println(show(parse_age(s)))
  }
}
age 42
age 7
rejected (empty input)
rejected (not a number: forty)
rejected (too large: 200)

When one step depends on another, nest the matches and add context to each bad, so the final message says where things went wrong:

fn parse_num(text) {
  bind n = to_number(text)
  if n == 0 && text != "0" { bad("not a number: " + text) } else { ok(n) }
}
fn area(wtext, htext) {
  match parse_num(wtext) {
    bad(e) => bad("width: " + e),
    ok(w) => match parse_num(htext) {
      bad(e) => bad("height: " + e),
      ok(h) => ok(w * h)
    }
  }
}
bind start = do {
  println(area("4", "2.5"))
  println(area("4", "x"))
}
Ok(10)
Err(height: not a number: x)

Runtime errors and tracebacks

Some problems stop a program with a runtime error: calling an unknown function, reading a missing file, indexing past the end of a list, a constructor with the wrong number of fields, and so on. The interpreter prints the error, the file, and a traceback with the deepest call last:

fn load(p) { read_file(p) }
fn go() { load("no_such_file.txt") }
bind start = do {
  println(go())
}
$ ling run --interp broken.ling
error[runtime]: read_file 'no_such_file.txt': The system cannot find the file specified. (os error 2)
 --> broken.ling
  traceback (deepest call last):
    0: start
    1: go
    2: load

The program stops with a non-zero exit code. (The OS message after the colon depends on your system.)

The JIT doesn’t stop. On the default engine most of these problems quietly give () and the program carries on: the program above prints () under ling run. When a program misbehaves, run it once with ling run --interp to see the real error.

Ling has no assert, panic or exit builtin. To signal failure, return a bad result and print a clear message.

try: catching a runtime error

try(f, args...) calls f with the given arguments. It returns ok(result) if the call worked and bad(message) if it raised a runtime error. Pass the function itself (its bare name, no parentheses), followed by its arguments. A closure works too: try(| | 6 * 7).

try works only on the interpreter. The JIT can’t pass a function to a builtin, so there try always returns bad("try: first argument must be a function"):

fn plus1(x) { x + 1 }
fn broken(x) { missing_function(x) }
bind start = do {
  println(try(plus1, 4))
  println(try(broken, 4))
}
Err(try: first argument must be a function)
Err(try: first argument must be a function)

The same program on the interpreter:

$ ling run --interp try_demo.ling
Ok(5)
Err(unknown function 'missing_function')

Programs that call http_serve always run on the interpreter, so try works inside web request handlers. Everywhere else, treat try as a development aid and write functions that return ok and bad yourself.

Soft failure in builtins

Most builtins don’t return results. On failure they return a harmless neutral value and keep going:

BuiltinOn failure
to_number("x")0
list_get(xs, 99)"" (empty text)
str_find("abc", "z")-1
file_exists(path)false
read_file("missing.txt")() on the JIT, a runtime error on the interpreter
bind start = do {
  println(to_number("banana"))
  println("[" + list_get([1, 2, 3], 99) + "]")
  println(str_find("hello", "z"))
  println(file_exists("no-such-file.txt"))
}
0
[]
-1
false

A failure can look like a real value: to_number("0") and to_number("zero") are both 0. Ask first: call file_exists before read_file, compare an index with len(xs), and validate text before trusting to_number. A small wrapper turns a soft failure into a real result:

fn load_text(path) {
  if file_exists(path) { ok(read_file(path)) } else { bad("no such file: " + path) }
}
bind start = do {
  println(load_text("missing.cfg"))
}
Err(no such file: missing.cfg)

Modules and Projects

When a program outgrows one file, move functions into library files and load them with use. This page covers use, mod blocks, what happens when names collide, and how to lay out a project with lingfu.

Ling’s module system is small: use loads a file into one shared namespace, and nothing is private. A few naming habits, described below, keep that comfortable.

FormWhat it does
use "lib/file.ling"Loads the file; its functions, types and top-level bindings become visible by plain name
use "lib/file.ling" as mLoads the file; call its functions as m::name()
mod name { fn f() { ... } }Groups functions in one file; call them as name::f()

use: loading another file

use "path" loads another .ling file. The path is text, and it is resolved relative to the file that contains the use, not to the folder you ran ling from. The .ling extension may be left off.

Everything in the loaded file becomes available: functions, form and choose types, and top-level bind values. A loaded file can itself use other files, with paths relative to its own location.

lib/textkit.ling

// textkit: small text helpers
fn tk_pad_left(text, width) {
  bind gap = width - len(text)
  if gap > 0 { str_repeat(" ", gap) + text } else { text }
}
fn tk_rule(width) { str_repeat("-", width) }

lib/report.ling loads textkit.ling from its own folder:

use "textkit.ling"
form Item { name, qty, }
fn rp_line(item) { item.name + tk_pad_left(str(item.qty), 6) }

main.ling

use "lib/report.ling"
bind start = do {
  println(rp_line(Item("tea", 3)))
  println(rp_line(Item("jam", 12)))
  println(tk_rule(9))
}
$ ling run main.ling
tea     3
jam    12
---------

main.ling never loads textkit.ling directly, but tk_rule is still visible: every loaded file shares one namespace.

use … as

With as, the loaded file’s functions are called through the alias. They are then not available by plain name:

use "lib/textkit.ling" as tk
bind start = do {
  println(tk::tk_rule(5))
}
$ ling run alias.ling
-----

Name collisions

All loaded names share one namespace, and there is no error or warning when two definitions collide:

  • If two loaded files define the same function, the one loaded last wins, even for callers inside the earlier file.
  • A definition in the main file beats anything it loads.

With lib/first.ling containing fn who() { "first" } and lib/second.ling containing fn who() { "second" }:

use "lib/first.ling"
use "lib/second.ling"
bind start = do {
  println(who())
}
$ ling run clash.ling
second

Add fn who() { "main file" } to the main file and it prints main file instead.

The same rule applies to the entry point: if a library binds start and is loaded after the main file’s start, the library’s start runs. So:

  • Give each library a short prefix (tk_, rp_) and use it on every function.
  • Never put a start binding in a library. Only the main program has one.
  • Pass data in as parameters. A library function sees top-level bindings, but never the local bindings of its caller.

mod: a namespace inside a file

mod name { ... } groups functions under a name that you reach with ::. It is useful when several groups would otherwise need the same function names:

mod vec {
  fn add(a, b) { [a[0] + b[0], a[1] + b[1]] }
  fn dot(a, b) { a[0] * b[0] + a[1] * b[1] }
  fn len2(a) { vec::dot(a, a) }
}
mod money {
  fn add(a, b) { round((a + b) * 100) / 100 }
}
bind start = do {
  println(vec::add([1, 2], [3, 4]))
  println(vec::len2([3, 4]))
  println(money::add(0.1, 0.2))
}
[4, 6]
25
0.3

Rules for mod:

  • Call sibling functions with the qualified name (vec::dot), as len2 does. A bare dot(a, a) fails on the interpreter and gives () on the JIT.
  • Functions in a mod can call the file’s top-level functions without a prefix.
  • Don’t bind values inside a mod. vec::ORIGIN gives () on the JIT and the text vec::ORIGIN on the interpreter, and even the module’s own functions can’t see it. Expose a constant as a function instead: fn origin() { [0, 0] }, called as vec::origin().

Projects with lingfu

lingfu new <name> creates a project folder:

$ lingfu new shop
~ Ling Manifest — Spirit Token Descends ~
Creating project: shop

✓ Spirit Realm created!
  cd shop
  lingfu build
  lingfu run
shop/
  Ling.toml          the manifest
  README.md
  ling.ignore
  lexicons/en.ling   language data (leave it alone)
  src/start.ling     the entry point
  tests/test.ling    a starter test

Put your libraries under src/, for example src/lib/textkit.ling, and load them from src/start.ling with use "lib/textkit.ling".

CommandWhat it does
lingfu runRuns src/start.ling
lingfu testRuns every .ling file in tests/
lingfu buildBuilds a distributable (needs the entry line below)

Entry points in a project

  • The program is src/start.ling, with a bind start = do { ... }.
  • A test in tests/ is a program too. It binds any name to a do block (the starter test uses bind test = do { ... }) and loads the code it tests with a path relative to itself, such as use "../src/lib/textkit.ling". Every file in tests/ must have an entry point: a helper file without one fails with no entry point.
  • A library has no entry binding at all.

The manifest

Ling.toml is created for you. lingfu run and lingfu test work without changes, but lingfu build looks for main.ling unless the manifest names the entry file. Add an entry line to the [spirit] section:

[spirit]
name = "shop"
kind = "bin"
version = "2030.0.0"
entry = "src/start.ling"

See lingfu for all commands and Known Limits for the current tooling quirks.

Writing in Five Languages

You can write Ling in English, Chinese, Japanese, Korean or Thai. Every keyword has a name in each of these languages, and so do most everyday builtins. The interpreter accepts all of them at once: there is no setting to switch, and you can mix languages in one file, even in one line.

The same program, five times

Here is one small program written in each language. Keywords, builtins, names, comments and text are all in that language, and each version runs as it is.

English

# Count the fruit in a basket
fn describe(n) {
    if n == 1 {
        return "1 fruit"
    } else {
        return to_str(n) + " fruits"
    }
}

bind start = do {
    bind basket = ["apple", "pear", "plum"]
    for fruit in basket {
        print("- ", fruit)
    }
    print(describe(len(basket)))
    print("square root of 16: ", sqrt(16))
}
- apple
- pear
- plum
3 fruits
square root of 16: 4

中文

# 数一数篮子里的水果
函 描述(数量) {
    若 数量 == 1 {
        归 "1 个水果"
    } 否则 {
        归 to_str(数量) + " 个水果"
    }
}

令 始 = 执 {
    令 篮子 = ["苹果", "梨", "李子"]
    历 水果 于 篮子 {
        打印("- ", 水果)
    }
    打印(描述(长度(篮子)))
    打印("16 的平方根:", 平方根(16))
}
- 苹果
- 梨
- 李子
3 个水果
16 的平方根:4

日本語

# かごの果物を数える
関数 説明(個数) {
    もし 個数 == 1 {
        戻る "果物 1 個"
    } 他 {
        戻る "果物 " + to_str(個数) + " 個"
    }
}

束縛 開始 = 実行 {
    束縛 かご = ["りんご", "なし", "すもも"]
    繰 果物 の中 かご {
        印刷("- ", 果物)
    }
    印刷(説明(長さ(かご)))
    印刷("16 の平方根:", 平方根(16))
}
- りんご
- なし
- すもも
果物 3 個
16 の平方根:4

한국어

# 바구니 속 과일 세기
함수 설명(개수) {
    만약 개수 == 1 {
        반환 "과일 1개"
    } 아니면 {
        반환 "과일 " + to_str(개수) + "개"
    }
}

바인드 시작 = 실행 {
    바인드 바구니 = ["사과", "배", "자두"]
    위해 과일 안에 바구니 {
        출력("- ", 과일)
    }
    출력(설명(길이(바구니)))
    출력("16의 제곱근: ", 제곱근(16))
}
- 사과
- 배
- 자두
과일 3개
16의 제곱근: 4

ไทย

# นับผลไม้ในตะกร้า
ฟังก์ชัน บรรยาย(จำนวน) {
    ถ้า จำนวน == 1 {
        คืน "ผลไม้ 1 ผล"
    } มิฉะนั้น {
        คืน "ผลไม้ " + to_str(จำนวน) + " ผล"
    }
}

ผูก เริ่ม = ทำ {
    ผูก ตะกร้า = ["แอปเปิล", "สาลี่", "พลัม"]
    สำหรับ ผลไม้ ใน ตะกร้า {
        พิมพ์("- ", ผลไม้)
    }
    พิมพ์(บรรยาย(ความยาว(ตะกร้า)))
    พิมพ์("รากที่สองของ 16: ", รากที่สอง(16))
}
- แอปเปิล
- สาลี่
- พลัม
ผลไม้ 3 ผล
รากที่สองของ 16: 4

A few things to notice:

  • Names you choose (describe, 篮子, かご, 바구니, ตะกร้า) can use any of these scripts.
  • The program starts at the binding whose value is a do block, so you can call it start, 始, 開始, 시작 or เริ่ม.
  • to_str stays in English in every version, because it has no alias in these languages. English names always work.
  • When a file uses another language, ling run prints a short note such as [detected language: Thai (ภาษาไทย)] to standard error. Your program’s output is unchanged.

Keywords

The most common keywords:

English中文日本語한국어ไทย
bind令束縛바인드ผูก
do执実行실행ทำ
fn函関数함수ฟังก์ชัน
return归戻る반환คืน
if若もし만약ถ้า
else否则他아니면มิฉะนั้น
while循間동안ขณะที่
for历繰위해สำหรับ
in于の中안에ใน
match配一致매치จับคู่
form形形구조โครงสร้าง
ok好良い좋아ตกลง
bad坏悪い나쁨ผิดพลาด
true真真참จริง
false假偽거짓เท็จ

Some keywords have more than one spelling (Chinese 如 also means if, Korean 반복 also means while). For the full list, see Keywords.

Builtins

Builtins work the same way: print, 打印, 印刷, 출력 and พิมพ์ are one function.

English中文日本語한국어ไทย
print打印印刷출력พิมพ์
len长度長さ길이ความยาว
sqrt平方根平方根제곱근รากที่สอง
abs绝对值絶対値절댓값ค่าสัมบูรณ์
max最大最大최댓값สูงสุด
rand随机乱数난수สุ่ม
list_push列表添加リスト追加목록추가เพิ่มรายการ
open_window开窗ウィンドウ開く창열기เปิดหน้าต่าง
window_is_open窗开開いている창열림หน้าต่างเปิดอยู่
fill填塗り潰し채우기เติม
present显表示표시แสดงผล
set_color设色色設定색설정สีดินสอ
key_down按键キー押す키누름กดค้าง
audio_blip提示音ビープ音효과음เสียงบี๊บ
time_now当前时间経過時間현재시간เวลาปัจจุบัน

Which builtins have aliases:

  • In all five languages: printing, maths, lists, the window and frame loop, 2D and 3D drawing, most keyboard input, audio and music playback, time, and the ui_* widgets.
  • English only: most text helpers (to_str, to_number, str_upper, str_split, …), file helpers such as write_file, the music studio (daw_*), and most of the web server, database and request helpers (http_*, db_*, query_param, json_escape). Some of these have a Thai alias (http_route is also เว็บเส้นทาง, db_open is also ฐานข้อมูลเปิด), but no Chinese, Japanese or Korean one.

The Builtins by Crate pages list each builtin with its aliases.

Tip: A misspelled or unknown name is not an error on the default engine; the call just returns (). For example 长 is not a builtin (the Chinese for len is 长度). If a call seems to do nothing, run ling run --interp yourfile.ling, which stops with unknown function.

Mixing languages in one file

Nothing stops you from using several languages together:

# English, Chinese, Japanese, Korean and Thai in one file
函 double(x) {
    归 x * 2
}

bind start = do {
    束縛 n = 21
    만약 n > 10 {
        พิมพ์("double: ", double(n))
    }
    print(长度([1, 2, 3]))
}
double: 42
3

This is handy when you learn from an example in another language, or when a team shares code. For a project you plan to keep, one language per project is easier to read.

Convert a project with lingfu normalize

lingfu normalize rewrites a whole project into one language. Run it in the project folder:

lingfu normalize --dry-run zh    # show what would change
lingfu normalize zh              # rewrite to Chinese
lingfu normalize en              # and back to English

The language can be en, zh, ja, ko or th (or a name such as thai).

  • It translates keywords and builtin names in every .ling file under the current folder, including subfolders.
  • It also renames files and folders whose names it knows how to translate. Add --content-only to change only file contents, or --files-only to only rename.
  • It doesn’t translate your own names, comments or text. Do those by hand.
  • Builtins without an alias in the target language keep their English names.

Warning: normalize changes files in place. Commit your work or make a copy first, and run it only in the project’s own folder.

After converting, run the program once to check it. In particular, look at form, ok and bad: if the new spelling doesn’t parse or does nothing, replace it with the one in the keyword table above. Builtins can be affected too: if a converted call suddenly returns (), run ling run --interp, which names the unknown function, and switch that call back to its English name.

Known Limits

Ling is young and moves quickly. This page collects the behaviours that surprise people most, so you can recognise them in minutes instead of hours. Everything here was checked against the current ling binary (2030.1.53) on both engines: the default JIT (ling run) and the interpreter (ling run --interp).

Tip: When a program misbehaves, run it once with ling run --interp. The interpreter reports unknown functions and runtime errors that the JIT quietly turns into ().

JIT and interpreter at a glance

SituationJIT (default)Interpreter
Unknown function namereturns () silentlyunknown function error
Runtime error (missing file, bad index, …)returns () or an empty value, keeps goingstops with an error and a traceback
1 / 0()inf
pi as a bare name() (write pi())the value
"" or [] in a conditiontruefalse
Index past the end of a listempty valueindex N out of bounds error
One character of text, s[i]empty valuethe character (use substr(s, i, 1) on both)
for c in "text"empty valueseach character
Ordering text, "a" < "b"falseerror
bind inside do { }visible afterwardsdiscarded
Closure stored in a variable, f(3)()unknown function 'f' error
Function or closure passed to a builtin (try, list_map, …)becomes ()works
wait expr()the value
Printing a range value 0..5[0, 5][0, 1, 2, 3, 4]
Constructor with the wrong number of fields()error
Missing function argument, when used()undefined error
return directly inside startends the program quietlyunexpected top-level return error

A program that avoids these corners behaves the same on both engines.

There is no assignment

x = x + 1 is a parse error. Rebind instead: bind x = x + 1. See Bindings.

Loops and scope

ConstructDoes a bind inside update the outer variable?
while bodyyes
if bodyyes
for bodyno: each pass gets a fresh copy of the scope
do { } blockyes on the JIT, no on the interpreter; don’t rely on either

To accumulate a total or build a list, use a while loop with a counter.

There is no break or continue. stop and again are reserved words that do nothing: on the JIT the loop just keeps going, and on the interpreter they are undefined errors. Put the loop in a function and return, or use while with a flag.

Range bounds must be simple

0..n and 0..(n + 1) work. 0..n + 1 is a parse error, and 0..len(xs) silently does the wrong thing (an empty loop on the JIT, an error on the interpreter). Wrap anything but a plain name or number in parentheses: 0..(len(xs)).

&& and || always evaluate both sides

Neither engine short-circuits. In x != 0 && 10 / x > 1 the division still runs when x is 0. Use nested ifs when the right side must not run.

Numbers and text

  • Number literals are decimal digits with at most one fractional part. There is no 1e3, 0xff, 1_000, .5 or 3.. Worse, 1e3 and 0xff aren’t parse errors: they read as 1 or 0 followed by an unknown name.
  • Text uses double quotes only and has no interpolation. Build text with + and str().
  • print and println both end the line, and both join their arguments with no separator: println("sum", 1 + 2) prints sum3.
  • !x means x == false, so !0 and !"" are false. Use ! on booleans only.

Comparing structured values

== on lists, records, enum values and results is always false, even for identical contents. Compare elements or fields yourself. See Types and Values.

What the type system does and doesn’t do

Ling is dynamically typed. Type annotations such as x: number and -> T are parsed and ignored. There is no map or dictionary, no set, no tuple and no JSON parser. Use records or parallel lists, or store data in SQLite with the db_* builtins.

Keywords that do nothing

These words are reserved but have no effect:

stop, again, change, post, give, fit, can, sure, maybe, pure, spawn, none

The ownership words own, lend, share, move and copy are parsed and ignored, with no borrow or move checking. async fn runs synchronously. type declarations are thrown away and swallow what follows them. See Keywords.

Closures and function values

A closure expression called directly, (|x| x + 1)(5), works everywhere. Beyond that:

  • A closure stored in a variable can’t be called by name on the interpreter, and is unreliable on the JIT.
  • The JIT can’t pass a function or closure to a builtin. list_map, list_filter and similar builtins return (), and try() always returns bad("try: first argument must be a function"). They work on the interpreter.
  • Programs that call http_serve run on the interpreter automatically, so closures and try work in request handlers.

Prefer named top-level fns and plain loops.

Modules

  • use "file" loads into one shared namespace. If two files define the same function, the last one loaded silently wins, even for callers in the earlier file. This also applies to start, so a library must never bind start.
  • Inside a mod, call sibling functions with the qualified name (geo::area). A bare call fails.
  • Values bound inside a mod are not usable. Expose constants as functions.

Prefix your library functions with the library name, for example geom_area. See Modules and Projects.

Tooling

  • lingfu new creates src/start.ling, but lingfu build looks for main.ling unless the manifest says otherwise. Add entry = "src/start.ling" to the [spirit] section of Ling.toml.
  • lingfu check, lingfu fmt and lingfu translate call ling subcommands that don’t exist. They print ling’s usage text and do nothing; check and fmt still report success. Use ling run --interp to check a program and lingfu normalize <lang> to translate one (it rewrites every .ling file in the current folder, so use it on a copy).
  • lingfu normalize gets a few keywords wrong. It writes form as a word the lexer doesn’t accept in Chinese, Korean and Thai (use the spelling from Keywords), leaves choose in English, and in Japanese and Thai writes ok/bad with builtin names that don’t work as match patterns. Some ownership words (copy, lend, share) also come out wrong in Japanese and Thai. Run the result and fix those words by hand.
  • lingfu build compiles generated Rust with Cargo, so it needs a Rust toolchain.

Testing

lingfu test runs tests on the JIT, which doesn’t stop on runtime errors, so it can print All tests passed! for a test that failed. Make your tests print a clear PASS or FAIL line and check it, or run them with ling run --interp. A helper file inside tests/ is treated as a test and fails with no entry point, so keep helpers elsewhere.

Parse traps

  • A line that starts with - or [ continues the previous line.
  • form P { x: number, y: number } is a parse error. End annotated field lists with a comma: form P { x: number, y: number, }.
  • An empty closure needs a space, | | expr, because || is “or”.
  • fn main() { ... } is not an entry point. Use bind main = do { ... }.
  • assert, panic, exit, append_file and delta_time are not builtins. For frame timing, subtract successive time_now() values.

Overview

Builtins are the functions that come with Ling: printing, math, text, files, windows, sound, the web server and much more. This section lists them by topic, with their names in each language, what they take and return, and short examples you can run.

How builtins work

Always available. You never import a builtin. Call it by name anywhere in your program:

bind start = do {
  print(sqrt(16) + max(2, 5))
}
9

Positional arguments. Arguments have no names; their order matters. A missing trailing argument usually takes a documented default instead of causing an error, so clamp(1.5) limits to the range 0..1.

Failure is a value. Most builtins report problems by returning something you can test: false, 0, -1, an empty list, or a bad(...) result. Each entry says which. Builtins that can fail in interesting ways return ok(value) or bad(reason); see Errors and Results.

Names in five languages. Many builtins have names in Chinese, Japanese, Korean and Thai as well as English. They all call the same function, and the English name always works, in any file, next to any other language:

bind start = do {
  print(sqrt(16))
  印(根(16))
  印刷(平方根(16))
  출력(제곱근(16))
  พิมพ์(รากที่สอง(16))
}
4
4
4
4
4

lingfu normalize --to <lang> rewrites a program’s keywords and builtins into one language. See Writing in Five Languages. The runtime also knows some names in other languages (French, German, Russian, Arabic, Persian, Hebrew, Urdu); these pages list only the five documented languages.

Profiles

cargo install ling-lang installs the full profile, which includes every builtin. If you installed a smaller install profile, some families of builtins are left out of your build. Calling one stops the program with an error that names the profile to add:

'http_get' needs the `web` profile, which this build of ling leaves out (reinstall with: cargo install ling-lang --features web, or the default full install)
ProfileBuiltin families (examples)
coreThe Output, Text and Files pages (except processes), windows, 2D drawing, fonts, images, meshes
webhttp_*, db_*, zip_*, tar_gz_*, video_*, run_process, proc_*, hashing and crypto
privacyp2p_*, lingtp_*, ssh_*, lw_*
gamerb_*, soft_*, liquid_*, gltf_*, gpu_*, body_*, pad_*, dialog_*, ui_*
ainn_*, bt_*, stt_*, learned dialog models
audioaudio_*, music_*, mic_*, fft_*

Heavy extras such as llm_* (local language models) and vision_* are opt-in on top of any profile.

Reading these pages

Each reference page has the same shape:

  1. An introduction with the rules that apply to the whole page.
  2. Summary tables. The first column is the signature, such as clamp(x, low, high). The language columns give the localized names; — means there is no localized name yet, so use the English one. Only your reading language’s column is shown when the page is translated.
  3. One section per builtin or group: parameters, return value, gotchas, and an example.

Examples marked ling were run with ling run and the output shown under them is real. Examples that need a window, sound, the network or a server are checked for syntax only, so they have no output block. Fragments without a start block are pieces of a larger program.

Ling has two backends: the default compiled one and the interpreter (ling run --interp). Where they differ, for example functions passed as arguments, which only work on the interpreter, the entry says so. Known Limits collects these differences.

Pages in this section

PageWhat it covers
Output, Math and Logicprint, format, ok/bad, rounding, trigonometry, noise, rand, sleep
Text and ListsMeasuring, searching, cutting and converting text; building and reading lists
Files, Time and SystemFiles and directories, time, command line, environment, processes, threads
Window and CameraOpening a window, the frame loop, the 3D camera
2D Drawing and ImagesPixels, lines, shapes, text on screen, loading and drawing images
3D Shapes and MeshesBuilt-in 3D shapes, meshes, textures
Fonts and UIFonts, text layout and interface widgets
AnimationTweens, easing and animated motion
Post-FX and LightingLights and screen effects
AudioPlaying sounds and synthesizing audio
MusicNotes, scales, music playback and MIDI
PhysicsRigid bodies, soft bodies and liquids
Acoustic BodiesPhysical objects that make sound
Input and MicrophoneKeyboard, mouse, gamepads and the microphone
DialogCinematic dialog boxes that type out text, for games
Web Server and HTTPRoutes, handlers, HTTP client requests
Database (SQLite)Opening a database, running queries
NetworkingPeer-to-peer, lingtp:// and SSH
CryptographyHashes, passwords, signatures and encryption
AI and Language ModelsNeural networks, behaviour trees, speech-to-text, local language models

Output, Math and Logic

These builtins print to the console, build text, do arithmetic and pause the program. They need no window, so every example on this page runs in a plain terminal with ling run.

All numbers in Ling are 64-bit floating point. Whole values print without a decimal point (3, not 3.0). Angles are in radians. A missing trailing numeric argument usually takes a default instead of raising an error.

Summary

Output and results

Builtin中文日本語한국어ไทยPurpose
print(value, ...)印, 打印印刷출력พิมพ์Print the arguments, joined with no separator, then a newline
println(value, ...)印, 打印印刷출력พิมพ์Same builtin as print
print_file(text)———พิมพ์ไฟล์Print text without a newline
print_color(color, value, ...)———พิมพ์สีPrint a line in a bright ANSI colour
format(template, value, ...)格式フォーマット서식รูปแบบFill {} placeholders in a template
format::join(list)格式::拼接———Concatenate list items as text
ok(value)好良し좋아โอเคWrap a success result
bad(reason)坏悪い나쁨ผิดWrap a failure result (alias err)
try(function, arg, ...)————Call a function, turning a runtime error into bad
sleep(ms)睡眠眠る, スリープ잠자기, 잠นอนPause for a number of milliseconds

Math

Builtin中文日本語한국어ไทยPurpose
abs(x)绝对值, 绝对絶対値절댓값, 절대값ค่าสัมบูรณ์Absolute value
floor(x)向下取整, 下整床関数내림ปัดลงRound down
ceil(x)向上取整, 上整天井関数올림ปัดขึ้นRound up
round(x)四舍五入, 四舍四捨五入반올림ปัดเศษRound to nearest; halves go away from zero
trunc(x)取整, 截整整数化, 切り捨て정수화, 버림ตัดทศนิยมDrop the fraction (alias int)
fract(x)小数部分—소수부—Fractional part
min(a, b)最小最小최솟값ต่ำสุดSmaller of two numbers
max(a, b)最大最大최댓값สูงสุดLarger of two numbers
clamp(x, low, high)截取範囲制限범위제한จำกัดLimit x to low..high
sign(x)符号符号関数부호เครื่องหมาย-1 for negative, otherwise 1
sqrt(x)根平方根제곱근รากที่สองSquare root
cbrt(x)立方根—세제곱근รากที่สามCube root
pow(base, exp)幂べき乗거듭제곱ยกกำลังPower
exp(x)指数—지수—e to the power x
ln(x)对数対数로그ลอการิทึมNatural logarithm (alias log)
log2(x), log10(x)对数2, 对数10—로그2, 로그10—Base-2 and base-10 logarithms
hypot(x, y)斜边—빗변—sqrt(x*x + y*y)
sin(x), cos(x), tan(x)正弦, 余弦, 正切サイン, コサイン, タンジェント사인, 코사인, 탄젠트ไซน์, โคไซน์, แทนเจนต์Trigonometry (radians)
asin(x), acos(x), atan(x)反正弦, 反余弦, 反正切アークサイン, アークコサイン, アークタンジェント아크사인, 아크코사인, 아크탄젠트อาร์กไซน์, อาร์กโคไซน์, อาร์กแทนเจนต์Inverse trigonometry
atan2(y, x)反正切2アークタンジェント2아크탄젠트2—Angle of the point (x, y)
tanh(x)双曲正切—쌍곡탄젠트—Hyperbolic tangent
pi()圆周率円周率파이พาย3.14159…
tau()双周率タウ타우ทาว2 × pi
lerp(a, b, t)线性插值線形補間선형보간ค่าระหว่างa + (b - a) * t
smoothstep(low, high, x)平滑步进スムーズステップ스무스스텝เปลี่ยนแบบนุ่มSmooth 0-to-1 S-curve
vnoise(x, y, seed)柏林噪声2Dバリューノイズ2D값노이즈2Dนอยส์2ดีSmooth 2D value noise, 0..1
fbm(x, y, octaves, seed)分形噪声フラクタルノイズ프랙탈노이즈นอยส์ออร์แกนิกLayered (fractal) noise
perlin(x, y, z)柏林噪声3Dパーリンノイズ3D펄린노이즈3Dเพอร์ลิน3ดี3D Perlin noise, about -1..1
rand()随机乱数난수สุ่มRandom number in 0 up to 1

Output

print(value, ...) and println(value, ...)

print and println are the same builtin. Each argument is converted to text, the pieces are joined with no separator, and a newline is added. Lists print as [1, 2, 3], results as Ok(v) and Err(e).

bind start = do {
  print("Hello, Ling!")
  print(42, " ", 3.5, " ", true)
  print([1, 2, 3])
  print("sum", 1 + 2)
  print("sum ", 1 + 2)
}
Hello, Ling!
42 3.5 true
[1, 2, 3]
sum3
sum 3

Put spaces inside the strings yourself, or build the line with format.

Prints its first argument without a newline. Despite the name, it does not touch the file system. It is the only way to keep printing on the same line.

bind start = do {
  for i in 1..4 {
    print_file(i)
    print_file(" ")
  }
  print("go!")
}
1 2 3 go!

Prints a line in a bold, bright ANSI colour. color is 0 to 7: black, red, green, yellow, blue, magenta, cyan, white. The remaining arguments are joined like print. The escape codes are written as-is, so they show up as control characters if you redirect the output to a file.

bind start = do {
  print_color(2, "ok: ", "all tests passed")
  print_color(1, "error!")
}

format(template, value, ...)

Returns text with each {} replaced by the next argument. {:.N} formats a number with N decimal places. A {} with no matching argument becomes empty; extra arguments are ignored. Only {} and {:.N} are supported (no widths, no {0} or {name}, no escaped braces).

bind start = do {
  print(format("{} + {} = {}", 2, 3, 2 + 3))
  print(format("pi is about {:.3}", pi()))
  print(format("{:.1}%", 45.678))
  print(format("{} and {}", "only one"))
}
2 + 3 = 5
pi is about 3.142
45.7%
only one and 

format::join(list) concatenates every item as text with no separator. To put something between the items, use list_join (see Text and Lists).

Results

ok(value) and bad(reason)

Ling has no exceptions. A function that can fail returns ok(value) or bad(reason), and the caller unpacks it with match. They print as Ok(...) and Err(...); err is an English alias of bad. See Errors and Results for the full story.

fn half(n) {
  if n % 2 == 0 { ok(n / 2) } else { bad("odd number") }
}
bind start = do {
  print(half(10))
  print(half(7))
  print(match half(7) { ok(v) => v, bad(e) => "failed: " + e })
}
Ok(5)
Err(odd number)
failed: odd number

try(function, arg, ...)

Calls function with the remaining arguments. Returns ok(result), or bad(message) if the call raised a runtime error.

Interpreter only. The default backend passes functions and closures given as arguments as (), so try returns Err(try: first argument must be a function). Run programs that use try with ling run --interp. A closure with no parameters is written | | expr, with a space.

fn safe_read(path) { try(| | read_file(path)) }

Math

Rounding

floor rounds down, ceil rounds up, round rounds to the nearest whole number (halves go away from zero), trunc drops the fraction, and fract keeps only the fraction. int is an English alias of trunc: it does not convert text to a number (use to_number for that).

bind start = do {
  print(floor(2.7), " ", floor(0 - 2.1))
  print(ceil(2.1), " ", ceil(0 - 2.9))
  print(round(2.5), " ", round(2.4), " ", round(0 - 2.5))
  print(trunc(2.9), " ", trunc(0 - 2.9), " ", int(7.99))
  print(fract(2.25))
}
2 -3
3 -2
3 2 -3
2 -2 7
0.25

min, max, clamp, sign, abs

min and max take exactly two numbers; for a list use list_min and list_max. clamp defaults to the range 0..1 and swaps the bounds if low > high. sign(0) is 1, not 0.

bind start = do {
  print(min(3, 1), " ", max(3, 1))
  print(clamp(15, 0, 10), " ", clamp(0 - 3, 0, 10))
  print(sign(0 - 4), " ", sign(0), " ", abs(0 - 7))
}
1 3
10 0
-1 1 7

Powers, roots and logarithms

sqrt of a negative number is NaN. log is the natural logarithm (same as ln); use log10 for base 10.

bind start = do {
  print(sqrt(16), " ", pow(2, 10), " ", pow(9, 0.5))
  print(cbrt(27), " ", hypot(3, 4), " ", exp(1))
  print(ln(exp(2)), " ", log(1), " ", log2(8), " ", log10(1000))
  print(sqrt(0 - 1))
}
4 1024 3
3 5 2.718281828459045
2 0 3 3
NaN

Trigonometry and constants

Angles are in radians. Always call pi() and tau() with parentheses: a bare pi is () under the default backend.

bind start = do {
  print(sin(pi() / 2), " ", cos(pi()))
  print(atan2(1, 1) * 4)
  print(tau())
}
1 -1
3.141592653589793
6.283185307179586

Interpolation and noise

lerp(a, b, t) does not clamp t. smoothstep(low, high, x) returns 0 below low, 1 above high, and a smooth curve between. The noise functions are deterministic: the same arguments always give the same value, which makes them handy for terrain and textures.

bind start = do {
  print(lerp(0, 10, 0.25), " ", smoothstep(0, 1, 0.5), " ", smoothstep(0, 1, 2))
  print(vnoise(1.5, 2.5, 0) == vnoise(1.5, 2.5, 0))
  print(fbm(0.3, 0.7, 4, 1) >= 0)
}
2.5 0.5 1
true
true

rand()

Returns a pseudo-random number from 0 up to (not including) 1. There is no seed and no integer form, so scale and round it yourself. It is not for security: use random_hex (see Files, Time and System) for unpredictable values.

bind start = do {
  bind die = floor(rand() * 6) + 1
  print(die >= 1 && die <= 6)
}
true

Logic and comparison

Logic and comparison are operators, not builtins: ==, !=, <, <=, >, >=, &&, || and !. Numbers, text and booleans compare by value. Two gotchas: lists are never equal under == (compare their items instead), and ordering text with < is not reliable.

bind start = do {
  print(1 < 2 && !(3 == 4))
  print("a" == "a", " ", 2 != 3)
  print([1, 2] == [1, 2])
}
true
true true
false

Pausing

sleep(ms)

Pauses the program for the given number of milliseconds (sleep_ms is an English alias). To measure time, see time_now in Files, Time and System.

bind start = do {
  sleep(50)
  print("done")
}
done

Text and Lists

Text (strings) and lists are the two everyday collections in Ling. This page covers the builtins that measure, search, cut and convert text, and the ones that build and read lists. For a gentler introduction, see the Lists and Text tutorial.

Two rules apply throughout:

  • Builtins never change their input. They return a new value, so rebind the result: bind xs = list_push(xs, 5).
  • Bad input rarely raises an error. An out-of-range index or unparsable number gives a fallback value ("", 0, -1) instead. Each entry says which.

Summary

Text

Builtin中文日本語한국어ไทยPurpose
len(value)长度長さ길이ความยาวNumber of characters (or list items)
to_str(value)———แปลงสตริงAny value as text (alias str)
to_number(text)转数字———Parse a number; 0 if invalid
hex_to_number(text)十六进制转数字———Parse hex digits; 0 if invalid
split(text, sep)———แยกSplit into a list of strings
trim(text)———ตัดช่องว่างRemove surrounding whitespace
starts_with(text, prefix)———เริ่มด้วยDoes the text start with prefix?
ends_with(text, suffix)———ลงท้ายด้วยDoes the text end with suffix?
str_contains(text, part)字符串包含—문자열포함มีข้อความDoes the text contain part?
str_find(text, part)———หาในสตริงCharacter index of part, or -1
substr(text, start, length)———ส่วนสตริงCut out part of the text
str_replace(text, from, to)———แทนสตริงReplace every occurrence
str_repeat(text, count)———ทำซ้ำสตริงRepeat the text
str_upper(text)————Upper case
str_lower(text)————Lower case
str_strip_prefix(text, prefix)———ตัดคำนำหน้าRemove a prefix if present
chr(code)字符—문자อักขระCharacter for a Unicode code point
ord(text)字码—문자코드รหัสอักขระCode point of the first character
hash_str(text)———แฮชStable hash in 0..1 (not cryptographic)
hash_int(text, n)———แฮชจำนวนStable hash in 0..n-1

Lists

Builtin中文日本語한국어ไทยPurpose
list_new()新建列表新規リスト새목록รายการใหม่Empty list
list_push(list, value)列表添加リスト追加목록추가เพิ่มรายการList with value added at the end
list_get(list, index)取元素, 要素取得—요소가져오기รับรายการItem at index; "" if out of range
list_set(list, index, value)设元素, 要素設定—요소설정ตั้งรายการList with one item replaced
list_join(list, sep)连接—연결รวมรายการJoin the items into text (alias join)
list_cat(a, b)————Two lists joined together
list_iota(n)————[0, 1, ..., n-1]
list_max(list, default)列表最大值———Largest number, or default if empty
list_min(list, default)列表最小值———Smallest number, or default if empty
list_map(list, fn)映射列表———Apply fn to each item (interpreter only)
list_filter(list, fn)过滤列表———Keep items where fn is true (interpreter only)
list_find(list, fn)查找列表———First item where fn is true (interpreter only)

Text

Joining and converting

+ joins text, and converts a number on either side to text. to_str converts any value explicitly. to_number ignores surrounding whitespace and returns 0 for anything it cannot read, so it cannot tell "0" from bad input. It does not read hex; use hex_to_number for that.

bind start = do {
  print("score: " + 10)
  print(to_str(3) + "!")
  print(to_number(" 42 ") + 1, " ", to_number("abc"))
  print(hex_to_number("ff"))
}
score: 10
3!
43 0
255

len(value)

Counts the characters of a text or the items of a list; anything else gives 0. The method form "text".len() counts bytes instead, so it differs for non-ASCII text.

bind start = do {
  print(len("Ling"), " ", len([1, 2, 3]))
  print(len("日本"), " ", "日本".len())
}
4 3
2 6

Searching

starts_with, ends_with and str_contains return true or false. str_find returns the 0-based character index of the first match, or -1. The method text.contains(part) works too.

bind start = do {
  bind word = "hello"
  print(starts_with(word, "he"), " ", ends_with(word, "lo"))
  print(str_contains(word, "ell"), " ", word.contains("z"))
  print(str_find(word, "l"), " ", str_find(word, "z"))
}
true true
true false
2 -1

Cutting and changing

substr(text, start, length) counts characters from 0; leave out length to go to the end. Out-of-range values are clamped, never an error. str_replace replaces every occurrence.

bind start = do {
  print(substr("hello", 1, 3), " ", substr("hello", 2))
  print(str_replace("a-b-c", "-", "+"))
  print(trim("   padded   ") + "|")
  print(str_upper("Ling"), " ", str_lower("LING"))
  print(str_repeat("ab", 3), " ", str_strip_prefix("v1.2", "v"))
}
ell llo
a+b+c
padded|
LING ling
ababab 1.2

split(text, sep)

Returns a list of strings. Without a separator (or with "") it splits on newlines. It never trims, so two separators in a row give an empty string.

bind start = do {
  print(split("one two three", " "))
  print(split("a,b,,c", ","))
  print(len(split("line 1\nline 2")))
}
[one, two, three]
[a, b, , c]
2

Characters and hashes

ord gives the code point of the first character (-1 for empty text), and chr turns a code point back into a one-character text. hash_str and hash_int give the same value for the same text every run, which is useful for picking a stable colour or variant from a name.

bind start = do {
  print(ord("A"), " ", chr(97))
  print(hash_str("apple") == hash_str("apple"))
  print(hash_int("apple", 10))
}
65 a
true
5

Lists

Building and reading

Write a list literally as [1, 2, 3], or start from list_new() and add items with list_push. Read an item with xs[i] (0-based) or list_get(xs, i). The difference is what happens out of range: list_get returns "", while xs[i] is an error on the interpreter. list_set returns a copy with one item replaced and ignores an out-of-range index.

bind start = do {
  bind xs = list_new()
  bind xs = list_push(xs, "a")
  bind xs = list_push(xs, "b")
  bind xs = list_set(xs, 0, "z")
  print(xs, " ", len(xs))
  print(xs[1], " ", list_get(xs, 0))
  print(list_get(xs, 9) == "")
}
[z, b] 2
b z
true

The method xs.push(value) does the same as list_push. Always rebind the result: the interpreter leaves the original list unchanged, the default backend may change it in place, and your program should not depend on either.

Combining

bind start = do {
  print(list_join(["a", "b", "c"], ", "))
  print(list_join([1, 2, 3], "-"))
  print(list_cat([1, 2], [3]), " ", list_iota(4))
  print(list_max([3, 9, 2], 0), " ", list_min([], 0 - 1))
}
a, b, c
1-2-3
[1, 2, 3] [0, 1, 2, 3]
9 -1

Loops instead of map and filter

list_map, list_filter and list_find take a function, and functions passed to builtins only work on the interpreter (ling run --interp); the default backend passes () instead. list_filter keeps an item only when the function returns exactly true.

fn doubled(xs) { list_map(xs, |x| x * 2) }

There are also no sort, slice or reverse builtins. A while loop does all of these and runs on every backend. Use while rather than for when you accumulate: a bind inside a for body does not reach the outer scope.

bind start = do {
  bind xs = [3, 1, 2, 4]
  bind total = 0
  bind rev = list_new()
  bind i = len(xs) - 1
  while i >= 0 {
    bind total = total + xs[i]
    bind rev = list_push(rev, xs[i])
    bind i = i - 1
  }
  print(total, " ", rev)
}
10 [4, 2, 1, 3]

Files, Time and System

These builtins read and write files, inspect paths, tell the time, read the command line and environment, start other programs and run work on other threads. Everything here works in a plain terminal; nothing needs a window.

Paths are text. Relative paths start from the directory you run ling in. Most file builtins report failure with a return value (false, 0, an empty list) rather than stopping the program; each entry says which.

Summary

Files and paths

Builtin中文日本語한국어ไทยPurpose
read_file(path)———อ่านไฟล์Read a UTF-8 text file
write_file(path, text)———เขียนไฟล์Create or overwrite a text file
read_file_bytes(path)读字节—바이트읽기อ่านไบต์Read any file as a list of bytes
write_file_bytes(path, bytes)写字节—바이트쓰기เขียนไบต์Write a list of bytes to a file
file_write_bytes(path, bytes, append)————Write or append bytes
file_exists(path)文件存在———Does the path exist?
is_file(path)———เป็นไฟล์Is it a file?
is_dir(path)———เป็นไดเรกทอรีIs it a directory?
list_dir(path)———รายการไดเรกทอรีPaths of the entries in a directory
make_dir(path)———สร้างไดเรกทอรีCreate a directory
copy_file(from, to)———คัดลอกไฟล์Copy a file
rename_file(from, to)重命名文件ファイル改名파일이름변경เปลี่ยนชื่อไฟล์Rename or move a file
remove_file(path)删除文件ファイル削除파일삭제ลบไฟล์Delete a file
remove_dir_all(path)———ลบไดเรกทอรีทั้งหมดDelete a directory and everything in it
file_size(path)———ขนาดไฟล์Size in bytes
file_modified(path)———เวลาที่แก้ไขLast change time (Unix seconds)
file_created(path)———เวลาที่สร้างCreation time (Unix seconds)
file_magic(path)———มายาไฟล์Detect gzip, zip, png or other
path_name(path)———ชื่อไฟล์Last part of a path
path_ext(path)———นามสกุลไฟล์File extension
absolute_path(path)———พาธสัมบูรณ์Make a path absolute

Time, environment and processes

Builtin中文日本語한국어ไทยPurpose
time_now()当前时间経過時間현재시간เวลาปัจจุบันSeconds since the program started
epoch_now()现在时刻—현재시각เวลาโลกSeconds since 1970-01-01 UTC (alias now_unix)
random_hex(bytes)——무작위16진수—Secure random bytes as hex text
get_args()———รับอาร์กิวเมนต์The whole command line as a list
cli_arg(name, default)———อาร์กิวเมนต์Value of a --name value option
env_get(name, default)———รับตัวแปรแวดล้อมRead an environment variable
run_process(cmd, args, timeout, log)———รันโปรเซสRun a program and wait for it
proc_start(cmd, args, log)————Start a program in the background
proc_poll(id)————Exit code, or -2 while running
proc_kill(id)————Stop a background program

Files

Reading and writing text

write_file creates or overwrites a file. read_file returns its contents as text. A missing file is an error on the interpreter, but returns () on the default backend, so check with file_exists first.

bind start = do {
  write_file("notes.txt", "line one\nline two")
  print(file_exists("notes.txt"), " ", file_size("notes.txt"))
  if file_exists("notes.txt") {
    bind lines = split(read_file("notes.txt"), "\n")
    print(len(lines), " lines, first: ", lines[0])
  }
  print(remove_file("notes.txt"), " ", remove_file("notes.txt"))
}
true 17
2 lines, first: line one
true false

remove_file returns false when there was nothing to delete.

Bytes

For binary files, read_file_bytes returns a list of numbers 0 to 255 (an empty list on error) and write_file_bytes writes one back, returning true on success. file_write_bytes(path, bytes, true) appends instead of overwriting.

bind start = do {
  print(write_file_bytes("hi.bin", [72, 105]))
  print(read_file_bytes("hi.bin"))
  file_write_bytes("hi.bin", [33], true)
  print(read_file("hi.bin"))
  print(file_magic("hi.bin"), " ", file_magic("nothing.bin"))
}
true
[72, 105]
Hi!
other missing

Directories

make_dir creates a directory (and any missing parents) and returns true on success. list_dir returns each entry as a path that starts with the directory you passed. copy_file and rename_file return true on success.

bind start = do {
  make_dir("out")
  write_file("out/a.txt", "A")
  copy_file("out/a.txt", "out/b.txt")
  rename_file("out/b.txt", "out/c.txt")
  print(list_dir("out"))
  print(is_dir("out"), " ", is_file("out"))
  print(remove_dir_all("out"), " ", file_exists("out"))
}
[out/a.txt, out/c.txt]
true false
true false

remove_dir_all deletes the directory and everything inside it, with no undo. A path that does not exist counts as success.

Paths

path_name and path_ext return the last part of a path and its extension (empty text if there is none). absolute_path puts the current directory in front of a relative path; it does not check that the path exists.

bind start = do {
  print(path_name("photos/cat.png"), " ", path_ext("photos/cat.png"))
  print(path_ext("README"), "|")
}
cat.png png
|

Time

time_now() and epoch_now()

time_now counts seconds (with fractions) since the program started, which is what you want for timing and animation. epoch_now is the wall-clock time as Unix seconds. There are no date-formatting builtins.

bind start = do {
  bind t0 = time_now()
  sleep(20)
  print(time_now() - t0 >= 0.02)
  print(epoch_now() > 1700000000)
}
true
true

random_hex(bytes)

Returns bytes cryptographically secure random bytes as lower-case hex (default 16 bytes, so 32 characters). Use it for tokens and IDs; use rand() for games.

bind start = do {
  print(len(random_hex(16)))
  print(random_hex(4) == random_hex(4))
}
32
false

Command line and environment

cli_arg(name, default) and get_args()

cli_arg("port", "8080") returns the value after --port on the command line, or the default. Only the two-word form --port 9000 is understood. get_args() returns the whole command line: for ling run app.ling a b it starts with the ling executable, then run, then the script, then your arguments.

bind start = do {
  print(cli_arg("port", "8080"))
  print(get_args()[1])
}
8080
run

env_get(name, default)

Reads an environment variable, or returns the default (empty text if you leave it out).

bind start = do {
  print(env_get("MY_APP_MODE", "development"))
}
development

Processes

run_process(cmd, args, timeout, log) runs a program directly (no shell, so no quoting problems or injection), appends its output to the log file and waits. It returns the exit code, -1 if the program could not start, or -2 if it was killed after timeout seconds.

proc_start(cmd, args, log) starts the program without waiting and returns an id (-1 on failure). proc_poll(id) returns -2 while it runs and the exit code afterwards; proc_kill(id) stops it.

bind start = do {
  print(run_process("git", ["--version"], 10, "git.log"))
  print(trim(read_file("git.log")))
  bind id = proc_start("git", ["status"], "status.log")
  while proc_poll(id) == -2 { sleep(100) }
  print("finished")
}

The process builtins belong to the web install profile. In a build without it they fail with an error that tells you how to reinstall.

Threads and channels

Ling threads are isolates: each runs its own interpreter, and they share nothing except channels and a write-once store, so they cannot race. Values sent between them are copied; functions cannot be sent.

BuiltinPurpose
thread_spawn(file, fn_name, args, caps)Run a function from another .ling file on a new thread; returns ok(handle)
thread_join(handle)Wait for the thread; returns ok(value) or bad(error)
thread_cpus()Number of hardware threads
chan_new(capacity)New channel as [send_handle, receive_handle]
chan_send(send, value)Send a value (blocks while full)
chan_recv(receive)Receive the next value as ok(value), or bad("closed")
chan_close(handle)Close a channel end
chan_len(handle)Number of queued messages
shared_put(key, value)Store a value once; bad("exists") if the key is taken
shared_get(key, default)Read a stored value

A channel works inside a single program too:

bind start = do {
  bind ch = chan_new(4)
  chan_send(ch[0], "hello")
  chan_send(ch[0], 42)
  print(chan_len(ch[1]))
  print(chan_recv(ch[1]), " ", chan_recv(ch[1]))
  chan_close(ch[0])
  print(chan_recv(ch[1]))
  print(shared_put("config", [1, 2]), " ", shared_put("config", 0))
  print(shared_get("config", []))
}
2
Ok(hello) Ok(42)
Err(closed)
Ok(()) Err(exists)
[1, 2]

thread_spawn loads the function from a separate file, resolved relative to the calling file. caps lists what the thread may do, from fs db net p2p proc keys clipboard; a thread never gets a capability its parent lacks. Unwrap the handle with match before joining:

// main.ling, next to worker.ling, which defines: fn square(n) { n * n }
fn square_on_thread(n) {
  bind h = match thread_spawn("worker.ling", "square", [n], []) { ok(v) => v, bad(e) => e }
  thread_join(h)
}

Window and Camera

Every graphical Ling program opens a window, runs a frame loop, and aims a single 3D camera. This page covers those three things: the window and its frame loop, frame pacing and timing, and the camera that projects 3D points onto the screen. Drawing is on the next pages: 2D Drawing and Images and 3D Shapes and Meshes.

The frame loop

A graphics program always has the same shape. Open a window, then repeat until it closes: clear, draw, present().

bind start = do {
    open_window(800, 600, "Frame loop")
    bind frame = 0
    while window_is_open() {
        fill(10, 12, 30)                  # 1. clear to a background colour
        set_color(255, 200, 80)           # 2. draw
        draw_disc(400 + 200 * sin(frame * 0.05), 300, 40)
        present()                         # 3. show the frame
        bind frame = frame + 1
    }
}

Three facts are worth remembering:

  1. window_is_open() turns false when the user closes the window or presses Escape. You don’t need to handle Escape yourself.
  2. present() is the only call that puts pixels on screen. It also draws the queued 3D geometry, runs post-processing and samples the mouse. A frame without present() is invisible.
  3. There is no delta-time builtin. Subtract the previous time_now() from the current one, or count frames with frame_count().

Calling a builtin that doesn’t exist (for example draw_rect, which Ling doesn’t have) is silently ignored. If a drawing call seems to do nothing, check its spelling first.

Coordinates

SpaceOrigin+x+y+z
Screen (2D)top-left pixelrightdownnot used
World (3D)camera pivotrightdownaway from the camera

Because +y points down, “above” is negative y: a ceiling sits at y = -3 and a floor at y = 3.

The default projection centres the view on the window, uses a focal length equal to the window height in pixels, and adds a depth offset zdist = 5 before the perspective divide:

screen_x = width/2  + height * x / (z + zdist)
screen_y = height/2 + height * y / (z + zdist)

Summary: window and frame

Builtin中文日本語한국어ไทยPurpose
open_window(w, h, title, resizable)开窗ウィンドウ開く창열기เปิดหน้าต่างOpen a window
open_fullscreen(title, w, h)全屏全画面전체화면เปิดหน้าต่างเต็มจอBorderless full-screen window
open_fullscreen_scaled(title, scale)————Full screen at 1/scale resolution
window_is_open()窗开開いている창열림หน้าต่างเปิดอยู่Loop condition
present()显表示표시แสดงผลFinish and show the frame
flush_3d(), flush_post()————Draw queued 3D now, mid-frame
quit()————Close the window from code
get_width(), get_height()宽, 高幅取得, 高取得너비, 높이ความกว้าง, ความสูงFramebuffer size
set_fps(n)设帧率フレームレート設定프레임설정ตั้งเฟรมเรตCap the frame rate
set_vsync(on)垂直同步垂直同期수직동기ตั้งวีซิงก์Pace to the monitor refresh
monitor_width(), monitor_height()屏宽, 屏高画面幅, 画面高화면너비, 화면높이ความกว้างจอ, ความสูงจอMonitor size
monitor_refresh()刷新率リフレッシュレート주사율อัตรารีเฟรชMonitor refresh rate in Hz
monitor_info()屏幕信息画面情報화면정보ข้อมูลจอ[width, height, hz]
wait_window()————Keep the last frame on screen
screenshot(tag)————Save the frame as PNG
record_frame(), record_count()————Save numbered frames for a video
frame_count()帧数フレーム数프레임수เฟรมFrames presented so far
time_now()当前时间経過時間현재시간เวลาปัจจุบันSeconds since the program started

Window and frame

open_window(w, h, title, resizable)

Opens the program’s window and allocates its framebuffer.

  • Parameters: w, h size in pixels (default 800 by 600); title (default "Ling"); resizable optional, 1 makes the window resizable (default 0).
  • Returns: nothing.
  • Note: the numbers come first and the title third. Opening a window also resets the camera projection to its defaults. With a resizable window, read get_width() and get_height() every frame. If the window can’t be created, the program stops with cannot open window.
bind start = do {
    open_window(1024, 640, "My game", 1)
}

open_fullscreen(title, w, h) and open_fullscreen_scaled(title, scale)

open_fullscreen opens a borderless window that covers the primary monitor. w and h are optional (default: the monitor’s resolution). Note that the title comes first here.

open_fullscreen_scaled renders at a fraction of the monitor resolution and scales the result up, trading sharpness for speed. scale is 1, 2 or 4 (anything else counts as 1); get_width() and get_height() report the reduced size.

bind start = do {
    open_fullscreen_scaled("Retro", 2)
}

window_is_open()

true while the window is open; false after the user closes it, presses Escape, or your code calls quit(). Before any window is opened it returns false, so a loop guarded by it doesn’t run.

present()

Ends the frame: draws every queued 3D primitive, applies post-processing, copies the framebuffer to the window and reads the mouse.

3D shapes (cube, vtex_*, draw_line_3d and the rest) are depth-sorted and only rasterised here, so you can issue them in any order. Direct 2D calls (draw_line, triangle, draw_disc, tex_*, image_draw) write to the framebuffer immediately, so queued 3D geometry ends up on top of them. To draw a HUD over a 3D scene, call flush_3d() first. The ui_* widgets detect clicks across frames, so they need present() once per frame.

flush_3d() and flush_post()

flush_3d() draws the queued 3D geometry into the framebuffer now, without presenting. Anything you draw afterwards lands on top. flush_post() does the same and then runs the post-processing chain immediately, so a HUD drawn after it isn’t blurred by bloom. See Post-FX and Lighting.

bind start = do {
    cube(0, 0, 8, 1, 1, 1, 0, 0, 0, 0)
    flush_3d()                          # the cube is now in the framebuffer
    ui_bar(20, 20, 200, 14, 0.5, 1)     # drawn over it
    present()
}

quit()

Closes the window from your code, exactly like pressing Escape. exit_game and close_window are English synonyms.

bind start = do {
    if ui_button(20, 20, 100, 32) == 1 { quit() }
}

get_width() and get_height()

The current framebuffer size in pixels. For a fixed window these equal the open_window arguments; for a resizable one they change when the user resizes it. Without a window they return 0.

bind start = do {
    bind cx = get_width() / 2
    bind cy = get_height() / 2
}

set_fps(n) and set_vsync(on)

set_fps(n) caps the frame rate (default 60, minimum 1). Call it after open_window. set_vsync(on) paces the loop to the monitor’s refresh rate instead. It is frame pacing, not tear-free vertical sync. An explicit set_fps, or the environment variable LING_FPS_CAP, wins.

bind start = do {
    open_window(800, 600, "Capped")
    set_fps(30)
}

monitor_width(), monitor_height(), monitor_refresh(), monitor_info()

The primary monitor’s width and height in pixels and its refresh rate in hertz. monitor_info() returns all three as a list [width, height, hz]. You can call them before opening a window, for example to size it.

bind start = do {
    bind info = monitor_info()
    open_window(info[0] / 2, info[1] / 2, "Half the screen")
}

wait_window()

Blocks, keeping the last frame on screen, until the window is closed or Escape is pressed. Handy for a program that draws one still picture.

bind start = do {
    open_window(400, 300, "Still")
    fill(20, 40, 80)
    present()
    wait_window()
}

screenshot(tag)

Saves the current framebuffer as a PNG and returns its path, screenshots/ss_<unix-time>_<tag>_<width>x<height>.png. tag defaults to "game"; characters other than letters and digits become underscores. The folder is created where the program runs. Call it after present() to capture a complete frame.

bind start = do {
    present()
    println(screenshot("title-screen"))
}

record_frame() and record_count()

record_frame() writes the current framebuffer to recordings/frame_00000.ppm, frame_00001.ppm and so on, for assembling into a video later, and returns the index of the frame it wrote. record_count() returns how many frames have been written.

frame_count() and time_now()

frame_count() is the number of frames presented since the program started. time_now() is the number of seconds since the program started, as a fraction. For a frame-time delta, remember the previous value:

bind start = do {
    bind last = time_now()
    while window_is_open() {
        bind now = time_now()
        bind dt = now - last
        bind last = now
        fill(0, 0, 0)
        present()
    }
}

Camera

All 3D builtins project world points through one global camera, defined by three things:

  • the pivot (x, y, z), set with set_camera_pos, which is subtracted from every point;
  • the orientation, set with set_camera as the cosine and sine of a yaw and a pitch angle;
  • the depth offset zdist, set with set_zdist, added before the perspective divide.

A positive yaw turns the camera to its right, so things straight ahead slide left on screen. A positive pitch tilts it down, so things ahead slide up. For a yaw angle a, “forward” in the world is (sin a, cos a) in the x-z plane. Set the camera every frame, before drawing 3D geometry.

Builtin中文日本語한국어ไทยPurpose
set_camera(cy, sy, cp, sp)设镜カメラ設定카메라설정ตั้งกล้องOrientation from cos/sin of yaw and pitch
set_camera_pos(x, y, z)镜坐标カメラ座標카메라좌표ตั้งตำแหน่งกล้องMove the pivot
move_camera(dx, dy, dz)————Move the pivot by an offset
set_zdist(d)镜距Z距離設定Z거리설정ตั้งระยะห่างDepth offset
set_projection(cx, cy, focal, zdist)投影投影設定투영설정ตั้งโปรเจกชันAll lens parameters at once
tm_fov(degrees, width)————Set the focal length from a field of view
set_camera_roll(angle)————Roll about the view axis
set_camera_hyper(R, saddle, px, mid_y, pz)————Hyperbolic-space view
project_3d(x, y, z)投影3D3D投影3D투영ฉาย3มิติWorld point to screen
mouse_ray()————Screen (mouse) to world ray

set_camera(cy, sy, cp, sp)

Sets the orientation from precomputed values: cy, sy are the cosine and sine of the yaw angle, cp, sp the cosine and sine of the pitch angle (defaults 1, 0, 1, 0, looking straight along +z). Pass the four numbers, not the angles.

bind start = do {
    bind yaw = 0.3
    bind pitch = 0.1
    set_camera(cos(yaw), sin(yaw), cos(pitch), sin(pitch))
}

set_camera_pos(x, y, z) and move_camera(dx, dy, dz)

set_camera_pos moves the camera pivot to a world position (default 0, 0, 0); move_camera adds an offset to it. Remember y is down: to raise the camera, decrease y. When audio is running, the audio listener follows the camera position.

bind start = do {
    set_camera_pos(0, -2, -6)      # two units up, six back
}

set_zdist(d), set_projection(cx, cy, focal, zdist) and tm_fov(degrees, width)

set_zdist(d) sets the depth offset (default 5, reset when a window opens). A larger value pushes the scene away and flattens the perspective; geometry nearer than -zdist is clipped.

set_projection overrides every lens parameter: cx, cy the optical centre in pixels, focal the focal length in pixels (larger zooms in), and zdist. You need it only for unusual setups such as split screen.

tm_fov(degrees, width) sets the focal length so the view spans a horizontal angle; width is the viewport width in pixels (default: the window width). tm_fov(0) restores the default focal length.

bind start = do {
    set_projection(get_width() / 2, get_height() / 2, get_height() * 1.5, 5)   # zoomed in
}

set_camera_roll(angle) and set_camera_hyper(R, saddle, px, mid_y, pz)

set_camera_roll rolls the view about its forward axis, in radians (alias camera_roll). set_camera_hyper switches on a hyperbolic view around the pivot (px, mid_y, pz): ground distances are compressed as R * tanh(d / R) and space bends like a saddle of strength saddle. R = 0 turns it off.

project_3d(x, y, z)

Projects a world point with the current camera and returns [screen_x, screen_y, depth]. A point behind the camera gives [-99999, -99999, depth]. Use it to pin 2D labels to 3D objects. Without a window the projection assumes a 1920 by 1080 frame, so this runs in a terminal:

bind start = do {
    set_camera(1, 0, 1, 0)
    println("ahead:   " + str(project_3d(0, 0, 5)))
    println("right:   " + str(project_3d(1, 0, 5)))
    set_camera_pos(2, 0, 0)
    println("moved:   " + str(project_3d(0, 0, 5)))
    set_camera_pos(0, 0, 0)
    println("behind:  " + str(project_3d(0, 0, -20)))
}
ahead:   [960, 540, 5]
right:   [1068, 540, 5]
moved:   [744, 540, 5]
behind:  [-99999, -99999, -20]

One unit to the right at depth 10 (5 plus zdist) moves 108 pixels with a focal length of 1080.

The ja and ko aliases 3D投影 and 3D투영 start with a digit, so they are read as the number 3 and can’t be called. Use project_3d in Japanese and Korean code.

mouse_ray()

The world-space ray from the camera pivot through the pixel under the mouse, as a list [ox, oy, oz, dx, dy, dz]: an origin and a direction. It is the inverse of project_3d. Step along it to find the ground under the cursor for click-to-move.

bind start = do {
    bind ray = mouse_ray()
    bind t = (2 - ray[1]) / ray[4]          # where the ray meets the floor at y = 2
    bind gx = ray[0] + ray[3] * t
    bind gz = ray[2] + ray[5] * t
}

A free-fly camera

Mouse look, WASD walking and a spinning cube. Moving along (sin yaw, cos yaw) keeps walking aligned with the view. Mouse and keyboard builtins are on Input and Microphone; lights on Post-FX and Lighting.

bind start = do {
    open_window(900, 600, "Fly")
    capture_mouse()
    set_depth_test(1)
    bind yaw = 0.0
    bind pitch = 0.0
    bind px = 0.0
    bind pz = -4.0
    bind t = 0.0
    while window_is_open() {
        bind yaw = yaw + mouse_dx() * 0.003
        bind pitch = clamp(pitch + mouse_dy() * 0.003, -1.5, 1.5)
        bind fx = sin(yaw) * 0.08
        bind fz = cos(yaw) * 0.08
        if key_down("w") { bind px = px + fx  bind pz = pz + fz }
        if key_down("s") { bind px = px - fx  bind pz = pz - fz }
        if key_down("d") { bind px = px + fz  bind pz = pz - fx }
        if key_down("a") { bind px = px - fz  bind pz = pz + fx }
        set_camera(cos(yaw), sin(yaw), cos(pitch), sin(pitch))
        set_camera_pos(px, 0, pz)
        fill(8, 10, 24)
        clear_lights()
        add_light(-3, -6, 0, 1.0, 0.95, 0.85, 1.0, 0)
        vtex_grid(0, 2, 8, 1, 0, 0, 0, 0, 1, 20, 20, 1, 1, t, 0)
        set_color(240, 150, 110)
        cube(0, 0, 8, 1, 1, 1, t * 0.5, t, 0, 0)
        present()
        bind t = t + 0.02
    }
}

2D Drawing and Images

These builtins paint straight into the window’s framebuffer in screen pixels: lines, triangles, circles, polygons, gradients and soft shadows, plus images loaded from files or built pixel by pixel. They all need an open window and belong between fill() and present() (see Window and Camera).

How 2D drawing works

  • Coordinates are pixels. The origin is the top-left corner, +x points right and +y points down. Coordinates outside the window are simply not drawn.
  • The pen colour. Shapes are drawn in the current pen colour, set with set_color. It stays in effect until you change it. 3D shapes also use it as their base colour.
  • Colour values are numbers from 0 to 255. They are not clamped: the runtime packs (r << 16) | (g << 8) | b, so a value above 255 spills into the next channel. Negative values become 0.
  • Immediate writes. 2D calls write pixels right away. Queued 3D geometry is drawn later, at present(), so it covers your 2D drawing. To draw 2D on top of a 3D scene, call flush_3d() first.
  • Packed colours. Some builtins take one number 0xRRGGBB. Ling has no hex literals, so write it as r * 65536 + g * 256 + b (for example 51 * 65536 + 102 * 256 + 255).
bind start = do {
    open_window(640, 360, "2D")
    while window_is_open() {
        fill(12, 14, 30)
        set_color(230, 90, 90)
        triangle(60, 300, 160, 140, 260, 300)
        set_color(90, 200, 255)
        draw_circle(380, 150, 60)
        set_color(120, 255, 160)
        draw_disc(520, 150, 40)
        set_color(255, 220, 90)
        draw_arc(380, 280, 50, 0, 3.14159)
        grad_rect(20, 320, 600, 24, 255, 80, 0, 0, 80, 255, 0)
        present()
    }
}

Summary: pen and shapes

Builtin中文日本語한국어ไทยPurpose
fill(r, g, b)填塗り潰し채우기เติมClear the frame to a colour
set_color(r, g, b)设色色設定색설정สีดินสอPen colour
set_color_hsl(h, s, l)色相HSL色HSL색설정สีHSLวาดPen colour from hue, saturation, lightness
mix_color(r0, g0, b0, r1, g1, b1, t)混合颜色色混合색혼합ผสมสีPen colour blended between two colours
set_alpha(a)设透明アルファ設定투명도설정ตั้งความโปร่งใสOpacity for gradients and 3D
set_blend(mode)混合模式ブレンドモード블렌드모드โหมดผสมNormal or additive blending
set_antialias(on), get_antialias()————Smooth line strokes
draw_pixel(x, y)画点点描く점그리기วาดจุดOne pixel
draw_line(x0, y0, x1, y1)画线線描く선그리기วาดเส้นA line
triangle(x0, y0, x1, y1, x2, y2)画三角三角形描画삼각형그리기วาดสามเหลี่ยมFilled triangle
draw_circle(cx, cy, r)————Circle outline
draw_disc(cx, cy, r)画实心圆塗りつぶし円원채우기วาดวงกลมทึบFilled circle
draw_arc(cx, cy, r, a0, a1, segments)————Part of a circle
draw_poly(points)填充多边形ポリゴン塗り다각형채우기เติมรูปหลายเหลี่ยมFilled polygon
grad_rect(x, y, w, h, r0, g0, b0, r1, g1, b1, dir)渐变矩形グラデ矩形그라데사각สี่เหลี่ยมไล่สีGradient rectangle
grad_triangle(...)渐变三角グラデ三角그라데삼각สามเหลี่ยมไล่สีTriangle with a colour per corner
set_gradient_space(mode)渐变空间グラデ空間그라데이션공간ปริภูมิไล่สีPerceptual or sRGB gradients
shadow_blob(cx, cy, rx, ry, alpha)阴影斑影ブロブ그림자블롭เงาวงรีSoft shadow ellipse
cast_shadow(cx, cy, height)投射阴影影を落とす그림자드리우기ทอดเงาShadow that follows height
shadow_params(base, grow, alpha, fade, soft)阴影参数影設定그림자설정ตั้งค่าเงาTune cast_shadow
depth_triangle(...), depth_line(...)深度三角, 深度线深度三角形, 深度線깊이삼각, 깊이선สามเหลี่ยมเรียงลึก, เส้นเรียงลึก2D shapes sorted with 3D
set_frame_blur(amount)————Afterimage trails

Pen and blending

fill(r, g, b)

Clears the whole framebuffer to a colour and resets the depth buffer. Call it first in every frame. Each channel defaults to 0, so fill() clears to black. It doesn’t change the pen colour. clear is an English synonym.

set_color(r, g, b), set_color_hsl(h, s, l) and mix_color(...)

set_color sets the pen colour (each channel defaults to 255).

set_color_hsl sets it from hue in degrees (0 to 360), saturation and lightness (0 to 100; defaults 70 and 50). Stepping the hue is the easy way to a rainbow.

mix_color(r0, g0, b0, r1, g1, b1, t) sets the pen to a blend of two colours, t from 0 to 1 (default 0.5). It blends in the OkLab colour space, so mid-tones look clean rather than muddy.

bind start = do {
    open_window(700, 300, "Rainbow")
    fill(0, 0, 0)
    bind i = 0
    while i < 12 {
        set_color_hsl(i * 30, 80, 55)
        draw_disc(60 + i * 50, 150, 20)
        bind i = i + 1
    }
    present()
    wait_window()
}

set_alpha(a)

Pen opacity from 0 (invisible) to 1 (opaque), default 1. It applies to the gradient fills and to queued 3D shapes.

set_blend(mode)

How new pixels combine with what is already there: 0 normal (default), 1 additive. With additive blending overlapping shapes get brighter, which is the basis of every glow effect. Queued 3D draws also accept 2 multiply, 3 screen, 4 subtract and 5 overlay. Set it back to 0 when you are done.

bind start = do {
    set_blend(1)
    set_color(60, 40, 20)
    draw_disc(500, 280, 40)
    draw_disc(530, 280, 40)       # the overlap is brighter
    set_blend(0)
}

set_antialias(on) and get_antialias()

Smooths line strokes: lines, arcs, circle outlines and 3D edges. Off by default, which gives crisp pixel lines; set_antialias() with no argument turns it on. get_antialias() reads the setting back. Text smoothing is separate (see Fonts and UI).

Shapes

draw_pixel(x, y) and draw_line(x0, y0, x1, y1)

draw_pixel sets one pixel. draw_line draws a one-pixel line between two points; it honours set_antialias and additive blending.

triangle(x0, y0, x1, y1, x2, y2)

A filled triangle. Build rectangles from two triangles, or use draw_poly. draw_triangle is an English synonym.

bind start = do {
    set_color(230, 90, 90)
    triangle(100, 100, 300, 100, 300, 200)
    triangle(100, 100, 300, 200, 100, 200)      # together: a rectangle
}

draw_circle(cx, cy, r) and draw_disc(cx, cy, r)

A circle outline and a filled circle, centre and radius in pixels (radius default 10). draw_disc honours the blend mode, so with set_blend(1) it paints a glow.

draw_arc(cx, cy, r, a0, a1, segments)

Strokes part of a circle from angle a0 to a1 in radians (default 0 to 2π, a full circle); segments is optional. Because +y is down, angles grow clockwise on screen: 0 is to the right, pi() / 2 is straight down.

draw_poly(points)

A filled polygon that closes itself. points is a flat list [x0, y0, x1, y1, ...]. Combine it with project_3d to fill a shape between projected 3D points.

bind start = do {
    set_color(200, 140, 255)
    draw_poly([100, 100, 200, 120, 180, 200, 90, 180])
}

grad_rect(x, y, w, h, r0, g0, b0, r1, g1, b1, dir) and grad_triangle(...)

grad_rect fills a rectangle with a gradient from the first colour to the second. dir is 0 for left to right and anything else for top to bottom (default 1).

grad_triangle(x0, y0, r0, g0, b0, x1, y1, r1, g1, b1, x2, y2, r2, g2, b2) gives each corner its own colour and blends smoothly between them: a cheap “lit” surface.

Both honour set_alpha. Gradients blend perceptually by default; set_gradient_space(0) switches to plain sRGB.

shadow_blob, cast_shadow and shadow_params

shadow_blob(cx, cy, rx, ry, alpha) draws a soft ellipse in the pen colour (radii default 16 and 8, alpha default 0.5). A dark pen gives an ordinary shadow; any other colour a tinted one.

cast_shadow(cx, cy, height) draws a contact shadow whose size and softness follow the height of the object above the ground: low objects get small, dark, sharp shadows, high ones large faint ones. shadow_params(base, grow, alpha, fade, soft) tunes it; each argument you leave out keeps its value.

bind start = do {
    set_color(0, 0, 20)
    cast_shadow(320, 330, 24)
}

depth_triangle(x0, y0, x1, y1, x2, y2, z) and depth_line(x0, y0, x1, y1, z)

Queue a 2D triangle or line to be depth-sorted together with the 3D geometry and drawn at present(). Larger z is farther away. Use them for 2D sprites that must pass in front of and behind 3D objects.

set_frame_blur(amount)

Afterimage trails: each frame is mixed with a faded copy of the last one. amount goes from 0 to 0.95; about 0.9 leaves trails that last roughly a second at 60 frames per second. 0 turns it off.

Images

Images live in a table inside the runtime. Each load or creation returns a handle, a small number you pass to the other image_* builtins. -1 means failure.

BuiltinPurpose
image_load(path)Load a PNG, JPEG or other raster image; returns a handle or -1
image_draw(id, x, y, w, h)Draw it scaled to w by h pixels
image_new(w, h)A new transparent image
image_set_pixel(id, x, y, r, g, b, a)Paint one pixel
image_pixel_r(id, x, y), _g, _b, _aRead one channel (0 to 255)
image_width(id), image_height(id)Size in pixels
image_save(id, path)Write a PNG; 1 or -1
image_replace(id, path)Load a new file into an existing handle
image_tint(id, color)A one-colour copy shaped by the alpha
image_resized(id, w, h)A resized copy
image_svg(svg_text, w, h)Render SVG source text to an image
image_free(id)Release the pixels

image_load(path)

Loads a raster image and returns its handle, or -1 (with a message on the error stream) if the file can’t be read. The path is tried as given, then relative to the script’s folder. Loading the same path again returns the cached handle, so it is safe to call inside the frame loop.

image_draw(id, x, y, w, h, cx, cy, cw, ch, opacity)

Draws the image with its top-left corner at x, y, scaled (nearest neighbour) to w by h pixels and alpha-blended over the frame. w and h are required: if they are 0 nothing is drawn, so pass image_width(id) and image_height(id) for the natural size. Optional: a clip rectangle cx, cy, cw, ch outside which nothing is drawn, and an opacity from 0 to 1 after it. Images are shown as they are, without the toon shading the post-processing applies to 3D.

bind start = do {
    open_window(640, 400, "Sprite")
    bind hero = image_load("hero.png")
    bind x = 0
    while window_is_open() {
        fill(20, 24, 40)
        if hero >= 0 {
            image_draw(hero, x, 160, image_width(hero) * 2, image_height(hero) * 2)
        }
        present()
        bind x = (x + 2) % 640
    }
}

image_new, image_set_pixel and the pixel readers

image_new(w, h) creates a blank, fully transparent image. image_set_pixel(id, x, y, r, g, b, a) paints one pixel (a defaults to 255). image_pixel_r, image_pixel_g, image_pixel_b and image_pixel_a read one channel of a pixel. Out-of-range positions and bad handles are ignored when writing and read as 0. These work without a window:

bind start = do {
    bind img = image_new(8, 4)
    image_set_pixel(img, 2, 1, 255, 128, 0)
    println("size:  " + str(image_width(img)) + " x " + str(image_height(img)))
    println("pixel: " + str(image_pixel_r(img, 2, 1)) + ", " + str(image_pixel_g(img, 2, 1)))
    println("empty: " + str(image_pixel_a(img, 0, 0)))
    bind blue = image_tint(img, 51 * 65536 + 102 * 256 + 255)
    println("tint:  " + str(image_pixel_b(blue, 2, 1)))
}
size:  8 x 4
pixel: 255, 128
empty: 0
tint:  255

image_pixel_u16(id, x, y) returns r * 256 + g in one call, for 16-bit height maps.

image_save(id, path) and image_replace(id, path)

image_save writes an image (loaded or created) to a file, keeping alpha, and creates missing folders. The path is relative to where the program runs. It returns 1, or -1 on failure. image_replace decodes a new file into an existing handle, so a picture you reload often doesn’t grow the image table; it returns 1 or -1.

To save the window itself, use screenshot (see Window and Camera).

image_tint, image_resized, image_svg and image_free

image_tint(id, color) returns a new image in one packed colour, shaped by the original’s alpha: an icon redrawn in any colour. image_resized(id, w, h) returns a resized copy. image_svg(svg_text, w, h) renders SVG source text (not a path) to a new image; read a file first with read_file. All three return a new handle or -1.

image_free(id) releases an image’s pixels. The handle stays valid but draws nothing.

Text

For text, use the vector fonts or the built-in stroke font, both on Fonts and UI. The quickest way to put a label on screen needs no font file:

bind start = do {
    set_color(120, 255, 160)
    ui_text(30, 30, 16, "SCORE 0420")
}

ui_text draws letters as capitals and knows only basic ASCII characters; anything else shows as a small box. For other scripts, load a font with font_load and draw with font_text_fill.

3D Shapes and Meshes

These builtins put things into the 3D scene: about two dozen parametric solids, raw triangles and lines, vtex_* vector patterns laid on planes, tex_* pixel textures, and meshes loaded from files (Ling’s own formats and glTF). Everything here needs an open window and the camera from Window and Camera. Lights, shading styles and post-processing are on Post-FX and Lighting.

3D calls don’t draw immediately. They join a depth queue that is sorted and drawn at present() (or flush_3d()), so you can issue them in any order within a frame.

Primitive solids

Every solid takes the same arguments:

name(cx, cy, cz,  sx, sy, sz,  rx, ry, rz,  mode,  e0, e1, e2)
ArgumentsMeaning
cx, cy, czCentre in world coordinates
sx, sy, szScale per axis (default 1). Shapes are about one unit in radius, so the scale is roughly the half-size: cube(0, 0, 8, 1, 1, 1) is a 2-unit cube
rx, ry, rzRotation in radians (default 0), applied X, then Y, then Z
mode0 filled (default), 1 wireframe, 2 both
e0, e1, e2Shape-specific extras (see the table below); 0 or omitted means the default

Only the position is required; trailing arguments can be dropped. The pen colour (set_color) is the fill and wire colour. Solids are lit by the scene lights and shaded in the toon style.

Remember +y points down. A cone has its apex at +y, so unrotated it points down the screen; rotate it by π on x to flip it. gear and torus lie in the x-z plane; rotate by about 1.57 on x to face the camera.

bind start = do {
    open_window(900, 600, "Shapes")
    set_depth_test(1)
    bind n = 0
    while window_is_open() {
        fill(8, 10, 24)
        set_camera(1, 0, 1, 0)
        clear_lights()
        add_light(-2, -6, -2, 1.0, 0.95, 0.85, 0.6, 0)
        bind a = n * 0.03
        set_color(230, 120, 90)
        cube(-2.8, 0, 7.5, 0.8, 0.8, 0.8, a, a * 0.7, 0, 0)
        set_color(120, 200, 255)
        sphere(0, 0, 7.5, 0.9, 0.9, 0.9, 0, 0, 0, 0)
        set_color(190, 190, 200)
        gear(2.8, 0, 7.5, 0.9, 0.3, 0.9, 1.57, a * 2, 0, 0, 14, 0.3)
        present()
        bind n = n + 1
    }
}

Summary: solids

Builtin中文日本語한국어ไทยExtras e0, e1, e2
cube立方体立方体정육면체ลูกบาศก์none (alias box)
sphere球体球구ทรงกลมsegments 16, rings 12
icosphere二十面球アイコ球아이코구체ทรงกลมเหลี่ยมsubdivisions 0 to 4 (1)
dome穹顶ドーム돔โดมsegments 24, rings 8 (a closed hemisphere)
cylinder圆柱円柱원기둥ทรงกระบอกsegments 24
cone圆锥円錐원뿔กรวยsegments 24
capsule胶囊カプセル캡슐แคปซูลsegments 16, rings per cap 6
torus圆环トーラス토러스ทอรัสsegments 32, sides 12, tube 0.35 (alias ring)
pyramid金字塔ピラミッド피라미드พีระมิดsides 4
prism棱柱角柱각기둥ปริซึมsides 6
frustum棱台錐台원뿔대กรวยตัดsides 24, top ratio 0.5
tetrahedron四面体四面体정사면체ทรงสี่หน้าnone (alias d4)
octahedron八面体八面体정팔면체ทรงแปดหน้าnone (alias d8)
dodecahedron十二面体十二面体정십이면체ทรงสิบสองหน้าnone (alias d12)
icosahedron二十面体二十面体정이십면체ทรงยี่สิบหน้าnone (alias d20)
gear齿轮歯車톱니바퀴เฟืองteeth 12, tooth depth 0.25 (alias cog)
gyro陀螺ジャイロ자이로ไจโรrings 3
arch拱门アーチ아치ซุ้มโค้งsegments 24, tube 0.18
stairs楼梯階段계단บันไดsteps 5 (2 to 40)
helix螺旋线らせん나선เกลียวturns 3, tube 0.15, sides 8
spring弹簧ばね스프링สปริงturns 6, tube 0.12, sides 8
star_prism星柱星柱별기둥แท่งดาวpoints 5, inner ratio 0.5 (alias star)
capsule_chain胶囊链カプセル鎖캡슐체인โซ่แคปซูลbeads 3 (1 to 12) (alias chain)
mobius莫比乌斯メビウス뫼비우스เมอบีอุสsegments 60, width 0.3

Notes on individual solids

  • cylinder runs along local y from -1 to 1, so it is 2 * sy tall. A small sy such as 0.05 makes a disc or plate.
  • torus: tube is the tube radius as a fraction of the outer radius (0.02 to 0.9).
  • frustum: the top ratio is the top radius over the base radius. Near 0 is a cone, 1 a cylinder; a small ratio with a tall sy makes an obelisk.
  • gear: the thickness comes from sy; teeth range from 3 to 96, tooth depth from 0.02 to 0.6.
  • stairs: each step is one step further in +y and +z. Since +y is down, they seem to descend as they recede; rotate by π on rz to flip them.
  • gyro nests gimbal rings on alternating axes; capsule_chain lines beads up along x.
  • The dice (tetrahedron to icosahedron) look like gems with mode 2 and a bright colour.
bind start = do {
    set_color(255, 140, 180)
    icosahedron(0, 0, 8, 1, 1, 1, 0.4, 0.7, 0, 2)
    cone(3, 0, 8, 0.8, 1, 0.8, 3.14159, 0, 0, 0)       # apex up
}

Triangles, lines and the depth test

Builtin中文日本語한국어ไทยPurpose
draw_triangle_3d(ax, ay, az, bx, by, bz, cx, cy, cz)————One lit triangle
draw_quad_3d(...), draw_polygon_3d(...)————A lit convex polygon
draw_line_3d(ax, ay, az, bx, by, bz)————A depth-sorted line
set_depth_test(on)深度测试深度テスト깊이테스트ทดสอบความลึกPer-pixel depth buffer
clear_depth()————Clear the depth buffer mid-frame

draw_triangle_3d, draw_quad_3d and draw_polygon_3d

Draw world-space geometry in the pen colour, lit, fogged and clipped at the near plane. draw_triangle_3d takes three points; the winding order decides which side faces the light. draw_quad_3d takes four x, y, z triples (12 numbers); draw_pent_3d and draw_hex_3d take 5 and 6. They share one implementation with draw_polygon_3d, which also accepts a single flat list [x0, y0, z0, x1, y1, z1, ...]. At most 8 vertices are used.

bind start = do {
    set_color(120, 200, 255)
    draw_quad_3d(-2, 1, 8, 2, 1, 8, 2, 1, 12, -2, 1, 12)     # a floor tile
    draw_polygon_3d([0, -1, 8, 1, 0, 8, 0, 1, 8, -1, 0, 8])  # a diamond
}

draw_line_3d(ax, ay, az, bx, by, bz)

A line between two world points, depth-sorted with the rest and clipped at the near plane. Use set_antialias(1) for smooth lines.

set_depth_test(on) and clear_depth()

The depth test is off by default: queued geometry is painted far to near. Turn it on (1) whenever solids may intersect, and for ambient occlusion, outlines and depth of field. fill() already clears the depth buffer each frame; clear_depth() is for starting a fresh depth pass mid-frame.

Vector patterns: vtex_*

Each vtex_* call draws an animated line pattern on a plane in 3D space. The first nine arguments are the same for all of them, and the last two are always fr and hue:

vtex_name(cx, cy, cz,  ux, uy, uz,  vx, vy, vz,  ...pattern arguments...,  fr, hue)

cx, cy, cz is the centre. u is the direction “right” runs in the pattern and v the direction “up” runs. fr is a frame counter you supply, which drives colour and motion; hue offsets the colour so neighbouring patterns differ. The colour cycles through a rainbow on its own; it doesn’t use the pen colour.

Planeuv
Floor or ceiling1, 0, 00, 0, 1
Wall facing the camera, upright1, 0, 00, -1, 0
Side wall, upright0, 0, 10, -1, 0

Upright patterns use v = (0, -1, 0) because +y is down. The patterns are plain line segments, so they are cheap, and they are drawn slightly toward the camera so they sit on top of a surface in the same place.

Builtin中文日本語한국어ไทยPattern arguments (defaults)
vtex_grid纹格格子模様격자무늬ลายตารางcols 10, rows 10, cell_w 1, cell_h 1
vtex_rings纹环リング模様링무늬ลายวงซ้อนrings 6, sides 6, max_r 3, twist 0
vtex_star纹星星模様별무늬ลายดาวpoints 6, r_out 2, r_in 1, spin per frame 0.01
vtex_spiral纹螺螺旋模様나선무늬ลายเกลียวturns 3, max_r 3, steps 120
vtex_flower纹花花模様꽃무늬ลายดอกไม้radius 1, sides 24 (Flower of Life)
vtex_halftone纹半调ハーフトーン하프톤무늬ลายจุดcols 16, rows 12, cell_w 0.5, cell_h 0.5, density 0.4
vtex_tessellated————cols 14, rows 10, cell 0.6, amplitude 0.25, freq 4
vtex_hyperbolic_uv————max_r 5, circles 12, rays 18 (Poincaré-disc grid)
vtex_letter_rain————cols 16, visible 14, col_w 0.65, row_h 0.6, speed 0.025
vtex_lotus纹莲蓮模様연꽃무늬ลายดอกบัวr_inner 1, r_outer 2, petals 12
vtex_chakra纹轮輪模様바퀴무늬ลายจักรr 2, spokes 8 (Dhamma wheel)
vtex_yantra纹扬特拉ヤントラ模様얀트라무늬ลายยันต์layers 4, max_r 3
vtex_spiked_cog纹刺轮スパイクコグ스파이크톱니무늬ฟันเฟืองหนามteeth 12, r_body 1, r_spike 1.3, r_hub 0.2, spokes 6
vtex_torii纹鸟居鳥居도리이ประตูโทริอิwidth 4, height 5
vtex_pagoda纹塔塔탑เจดีย์tiers 5, base_w 2, tier_h 1, taper 0.72, eave 0.28

Some details: vtex_rings turns each ring by twist radians more than the last, making a vortex. vtex_halftone density runs from 0 (invisible) to 1 (full hatching). vtex_tessellated shakes a triangle grid with a travelling sine wave. vtex_letter_rain is “matrix” rain made of Thai letters. vtex_pagoda has 3 to 7 tiers, each taper times narrower than the one below.

bind start = do {
    open_window(900, 600, "vtex")
    bind n = 0
    while window_is_open() {
        fill(4, 5, 12)
        set_camera(1, 0, 1, 0)
        vtex_grid(0, 3, 9, 1, 0, 0, 0, 0, 1, 12, 8, 1, 1, n, 0)
        vtex_rings(-3, -1, 8, 1, 0, 0, 0, -1, 0, 6, 6, 1.2, 0.2, n, 0)
        vtex_lotus(0, -1, 8, 1, 0, 0, 0, -1, 0, 0.4, 1.2, 12, n, 1)
        vtex_pagoda(3, 1.9, 8, 1, 0, 0, 0, -1, 0, 5, 1.6, 0.5, 0.72, 0.2, n, 2)
        present()
        bind n = n + 1
    }
}

orb_shell(cx, cy, cz, radius, rot_y, rot_x, density, r, g, b) is a relative of the patterns: a translucent shell of interleaved spirals wound around a sphere (density 1 to 48, default 10; tint defaults to a pale grey). Aliases: zh 球壳, ja オーブ殻, ko 오브껍질, th เปลือกทรงกลม.

Pixel textures: tex_*

The tex_* builtins fill a screen rectangle with a procedural pattern, one pixel at a time, immediately. Like other 2D calls, they are covered by queued 3D geometry. All start with the rectangle x, y, w, h in pixels (default 0, 0, 256, 256).

Every pixel is computed on every call, so a large texture is slow. Keep them small, or draw them once and leave them on screen.

Where a palette is accepted it is one of "rainbow", "fire", "ocean", "psychedelic", "neon" or "forest"; an unknown name falls back to rainbow.

BuiltinPurpose
tex_checkerboard(x, y, w, h, tiles, r1, g1, b1, r2, g2, b2)Two-colour checker (8 tiles, white and black)
tex_gradient(x, y, w, h, angle_deg, r1, g1, b1, r2, g2, b2)Linear gradient along an angle (0 is left to right)
tex_noise(x, y, w, h, scale, octaves, seed, palette)Fractal noise (scale 4, octaves 1 to 8)
tex_spiral(x, y, w, h, freq, bands, time, palette)Spiral bands that turn with time
tex_ripple(x, y, w, h, freq, cx, cy, time, palette)Ripples from cx, cy (0 to 1 inside the rectangle)
tex_mandelbrot(x, y, w, h, zoom, cx, cy, max_iter, palette)Mandelbrot set
tex_julia(x, y, w, h, c_re, c_im, max_iter, palette)Julia set (c = -0.7 + 0.27i)
tex_voronoi(x, y, w, h, cells, seed, palette)Voronoi cells (16 cells)
tex_halftone(x, y, w, h, dot_size, time, palette)Halftone dots
tex_freq_map(x, y, w, h, time, speed, palette)Spectrum from the last fft_bands call (see Audio)

tex_mandelbrot shows 1 / zoom units of the complex plane in both directions, so zoom 1 shows only the main cardioid; use about 0.4 to see the whole set.

bind start = do {
    open_window(660, 340, "tex")
    fill(0, 0, 0)
    tex_checkerboard(10, 10, 200, 150, 8, 240, 240, 240, 30, 30, 60)
    tex_noise(230, 10, 200, 150, 5, 4, 7, "fire")
    tex_mandelbrot(450, 10, 200, 150, 0.4, -0.5, 0, 64, "psychedelic")
    present()
    wait_window()
}

Meshes

Ling can draw meshes you build in lists, its own binary mesh formats, and glTF models. All of them are projected through the camera and queued with the rest of the 3D scene.

draw_mesh(positions, indices, ox, oy, oz, scale, mode)

Draws a triangle mesh stored in two lists: positions is flat [x0, y0, z0, x1, y1, z1, ...] and indices lists three vertex numbers per triangle. Every vertex is scaled by scale (default 1) and moved by ox, oy, oz. mode 0 lights it in the pen colour; 1 gives each triangle a rainbow colour. Bad indices are ignored.

bind start = do {
    bind pos = [0, -1, 8, 1, 1, 8, -1, 1, 8, 0, 0, 10]
    bind idx = [0, 1, 2, 0, 2, 3, 0, 3, 1]
    set_color(200, 160, 255)
    draw_mesh(pos, idx, 0, 0, 0, 1, 0)
}

mesh_load(path) and mesh_draw(id, x, y, z, scale, yaw)

mesh_load reads a .lmesh file (a compact format with one flat colour per triangle) and returns a handle or -1. mesh_draw draws it unlit, with its own colours, at a position, uniform scale and yaw angle. Further optional arguments (sway, arm, lean, leg, tuck, default 0) deform a character mesh: sway leans the upper body and arm swings the arms. mesh_free(id) releases the geometry. Aliases for mesh_load: zh 载入网格, ja メッシュ読込, ko 메시로드, th โหลดเมช.

glTF models: gltf_*

gltf_load(path) reads a .glb or .gltf file, including its skeleton, skin and animations, and returns a handle or -1. glTF is Y-up; the draw calls flip it into Ling’s Y-down world for you.

BuiltinPurpose
gltf_load(path)Load a model; handle or -1
gltf_draw(h, x, y, z, scale, yaw)Draw it lit, in its rest pose
gltf_anim_draw_tex(h, x, y, z, scale, yaw, clip, time)Draw it textured, posed by an animation clip at time seconds
gltf_anim_count(h), gltf_anim_name(h, i), gltf_anim_dur(h, i)Animation clips: count, name, length in seconds
gltf_bounds(h, clip, time)[minx, miny, minz, maxx, maxy, maxz] as drawn, in glTF space
gltf_tris(h)Triangle count
gltf_mesh_count(h), gltf_mesh_name(h, i)The model’s meshes
gltf_mesh_show(h, i, on)Show or hide one mesh in later draws (equipment, outfits)
gltf_mesh_tint(h, i, color)Multiply one mesh by a packed colour
gltf_joint_count(h), gltf_joint_name(h, j)Skeleton bones

In gltf_bounds y is up, so the top of a model drawn at ground height gy with scale s is at gy - maxy * s.

bind start = do {
    open_window(800, 600, "Model")
    set_depth_test(1)
    bind fox = gltf_load("models/fox.glb")
    bind clip = 0
    while window_is_open() {
        fill(20, 24, 40)
        clear_lights()
        add_light(-3, -6, 2, 1.0, 1.0, 1.0, 1.0, 0)
        if fox >= 0 {
            bind len = gltf_anim_dur(fox, clip)
            gltf_anim_draw_tex(fox, 0, 2, 8, 0.02, time_now(), clip, time_now() % max(len, 0.01))
        }
        present()
    }
}

Textured meshes: tm_*

The tm_* family draws textured geometry for 3D games. Textures and meshes each get a handle.

BuiltinPurpose
tm_tex_load(path, size)Load a PNG, SVG or SVGZ as a square texture of size pixels (default 256); id or -1
tm_load(path)Load an .ltm mesh (named groups of textured triangles); id or -1
tm_groups(m), tm_group(m, name), tm_group_name(m, g), tm_group_tris(m, g)Inspect a mesh’s groups
tm_bounds(m, g)[minx, miny, minz, maxx, maxy, maxz] of one group, or all with g = -1
tm_edges(m, g, max)Outline edges as a flat list of segments, for minimaps and wireframes
tm_draw(m, g, tex, x, y, z, scale, rot, tint, alpha, ...)Queue a group as textured triangles
tm_sprite(tex, cx, cy, w, h, rot, tint, alpha, blend)A rotated textured rectangle drawn straight onto the screen
tm_billboard(tex, x, y, z, size, rot, tint, alpha, blend)A camera-facing textured square in 3D
tm_quad(tex, x, y, z, ux, uy, uz, vx, vy, vz, tint, alpha, blend)A textured quad in any orientation (decals)
tm_wire(kind, x, y, z, size, rx, ry, rz, color, detail, thick)A wireframe shape
tm_solid(kind, x, y, z, size, rx, ry, rz, color, alpha, blend)A faceted, flat-shaded crystal solid

Common conventions: tint and color are packed 0xRRGGBB numbers (default white), alpha goes from 0 to 1, and blend is 0 normal or 1 additive. A texture id of -1 means a built-in soft glow dot; for tm_quad, -2 is a soft round shadow.

  • tm_draw continues with uoff, voff, uscale, vscale (texture scroll and scale), shade (0 to 1, darkens faces turned from the light), blend and cull (0 none, 1 or 2 one winding). rot is a yaw angle or a row-major 3 by 3 list. It returns the number of triangles queued.
  • tm_sprite draws onto the 2D framebuffer, so call it after flush_3d() for a HUD or title card.
  • tm_wire kinds: 0 cube, 1 tetrahedron, 2 octahedron, 3 icosahedron, 4 torus, 5 sphere, 6 ring, 7 star prism, 8 grid. size is the radius; thick 1 doubles the strokes.
  • tm_solid kinds: 0 cube, 1 tetrahedron, 2 octahedron, 3 icosahedron, 9 a shard (a stretched octahedron).
bind start = do {
    open_window(800, 600, "Crystals")
    bind t = 0.0
    while window_is_open() {
        fill(6, 8, 20)
        set_blend(1)
        tm_wire(3, -2, 0, 8, 1, t, t * 0.7, 0, 65535, 12, 1)
        set_blend(0)
        tm_solid(9, 2, 0, 8, 0.8, 0, t, 0, 16744576, 0.8, 1)
        present()
        bind t = t + 0.02
    }
}

Fonts and UI

This page covers text and interface: TrueType and OpenType fonts drawn as sharp vector outlines, the built-in stroke font, and the ui_* toolkit of meters, gauges and controls. All of them draw into the same framebuffer as the 2D drawing calls, so they belong between fill() and present(). To draw them over a 3D scene, call flush_3d() first. The typewriter dialog box has its own page: Dialog.

Fonts

Ling draws two kinds of text:

  • Vector fonts. font_load reads a .ttf or .otf file; font_text_fill, font_text and font_text_3d draw its glyph outlines. The curves are kept, so text is sharp at any size. Latin, Chinese, Japanese, Korean and Thai all work if the font has the glyphs.
  • The stroke font. ui_text draws a simple monospaced “holographic” face that needs no font file, for basic ASCII text.

The first time a glyph is used, its outline is cached on disk under cache/fonts/ in the folder the program runs in, so later runs start faster. In the web runtime font_load returns -1; check the handle and fall back to ui_text if you want a program to run in both.

bind start = do {
    open_window(720, 320, "Fonts")
    bind f = font_load("assets/fonts/Exo2.ttf", 600)
    bind cjk = font_load("assets/fonts/NotoSansSC.ttf")
    while window_is_open() {
        fill(8, 10, 24)
        set_color(0, 230, 255)
        font_text_fill(f, 30, 40, 48, "Hello Ling")
        set_color(255, 200, 80)
        font_text(f, 30, 110, 48, "Stroked Outline")
        set_color(255, 255, 255)
        font_text_fill(cjk, 30, 180, 40, "你好 こんにちは")
        set_color(120, 255, 160)
        ui_text(30, 260, 16, "UI TEXT 0123")
        present()
    }
}

Summary: fonts

Builtin中文日本語한국어ไทยPurpose
font_load(path, weight)加载字体フォント読込글꼴로드โหลดฟอนต์Load a font, get a handle
font_text_fill(font, x, y, px, text)填充字体フォント塗り글꼴채움เติมฟอนต์Filled text
font_text(font, x, y, px, text)字体文本フォント文字글꼴텍스트ข้อความฟอนต์Outlined text
font_text_3d(font, ..., size, text, rows)字体3Dフォント3D글꼴3Dข้อความฟอนต์3มิติText on a 3D plane
font_width(font, px, text)字体宽度フォント幅글꼴너비ความกว้างฟอนต์Measure a string in pixels
font_advance(font, char)————Advance of one glyph, in ems
font_glyph_outline(font, char, tol)————A glyph’s outline as polylines
font_fallback(primary, fallback, scale)————Fallback font for missing characters
set_font_antialias(on), get_font_antialias()————Smooth glyph edges
ui_text(x, y, scale, text)界面文字UI文字UI텍스트ข้อความหน้าจอBuilt-in stroke font

font_load(path, weight)

Loads a font and returns a handle (0 for the first font, 1 for the next, and so on), or -1 if it can’t be read; a message then goes to the error stream. The path is tried as given, then relative to the script’s folder. weight is optional: for a variable font, a number such as 600 gives a bold look; 0 or nothing uses the font’s default.

The Ling repository ships Exo2, Orbitron, Rajdhani, Noto Sans (SC, JP, KR, Thai) and Galmuri in assets/fonts/. If your program may start from different folders, try a second path:

bind start = do {
    bind f = font_load("assets/fonts/Exo2.ttf", 600)
    if f < 0 { bind f = font_load("../../assets/fonts/Exo2.ttf", 600) }
}

font_text_fill(font, x, y, px, text) and font_text(font, x, y, px, text)

font_text_fill draws solid glyphs in the pen colour; font_text draws their outlines, which is cheaper and honours set_blend and set_antialias. x, y is the top-left of the line, not the baseline: capitals start about 0.3 * px below y, and the baseline is about 0.97 * px below it. px is the size in pixels (default 16). Edges are crisp unless you call set_font_antialias(1). A bad handle draws nothing.

font_text_3d(font, cx, cy, cz, ux, uy, uz, vx, vy, vz, size, text, fill_rows)

Draws text on a plane in 3D, depth-sorted with the scene so it turns with the camera. c is where the line starts, u the direction the text advances (default 1, 0, 0), v the glyphs’ up direction (default 0, 1, 0), and size the height of one em in world units (default 1). Because +y is down, upright text needs v = (0, -1, 0). Outlines only, unless fill_rows is above 0: then each glyph is filled with that many scan lines.

bind start = do {
    bind f = font_load("assets/fonts/Exo2.ttf", 600)
    set_color(120, 230, 255)
    font_text_3d(f, -2, 0, 8, 1, 0, 0, 0, -1, 0, 0.6, "LING 3D")
}

font_width(font, px, text)

The width of a string in pixels (0 for a bad handle). Note the order: the size comes before the text. To centre a label in a box bx, by, bw, bh, draw it at x = bx + (bw - font_width(f, px, text)) / 2 and y = by + bh / 2 - 0.64 * px.

font_advance(font, char) and font_glyph_outline(font, char, tol)

font_advance gives the advance width of one character in ems (multiply by the pixel size). font_glyph_outline returns a character’s outline for your own effects: a list of contours, each a flat list [x0, y0, x1, y1, ...] in em units with the baseline at 0 and y pointing up. tol is how far the polyline may stray from the true curve (default 0.01 em). It is empty on failure.

font_fallback(primary, fallback, scale)

Uses fallback for every character primary lacks, for example a wide Unicode font behind a stylish Latin one. scale sizes the fallback relative to the primary (default 1). Pass -1 as fallback to remove it. It returns the primary handle, or -1 if a handle is bad.

bind start = do {
    bind latin = font_load("assets/fonts/Orbitron.ttf", 600)
    bind wide = font_load("assets/fonts/NotoSansSC.ttf")
    font_fallback(latin, wide, 0.9)
}

set_font_antialias(on) and get_font_antialias()

Turns glyph smoothing on or off (off by default, for crisp text). set_font_antialias() with no argument turns it on. This is separate from set_antialias, which affects line strokes.

ui_text(x, y, scale, text)

Draws text in the built-in stroke font, in the pen colour. x, y is the top-left; glyphs are scale pixels tall (default 16), each scale * 0.62 wide with a gap of scale * 0.24. Letters are drawn as capitals, and characters the face lacks (including all non-ASCII text) show as a small box.

The UI toolkit

The ui_* builtins are an immediate-mode toolkit. Nothing is stored between frames: you call each widget every frame with the current value, it draws itself, and an interactive control returns the new value. Your program keeps all the state in ordinary variables.

bind start = do {
    open_window(480, 220, "Controls")
    bind volume = 0.4
    bind enabled = 0
    while window_is_open() {
        fill(6, 10, 22)
        bind volume = ui_slider(40, 60, 280, volume, 0, 1)
        bind enabled = ui_toggle(40, 100, 52, 24, enabled)
        if ui_button(40, 150, 120, 36) == 1 { println("clicked") }
        set_color(220, 240, 255)
        ui_text(64, 160, 14, "PLAY")
        present()
    }
}

Shared conventions:

  • Coordinates are screen pixels. Rectangular widgets take x, y, w, h; round ones a centre cx, cy and radius r.
  • Colours come from the theme (ui_theme). Most widgets accept an optional trailing r, g, b that overrides their main colour for that call. Pass all three or none.
  • Widgets draw no text. A button has no label and a tab strip no captions. Draw labels yourself with ui_text or font_text_fill.
  • Interaction reads the left mouse button. A button returns 1 on the single frame the mouse goes down over it, so compare with == 1. This needs present() once per frame.
  • Blend. Widgets honour set_blend, so set_blend(1) makes them glow.

Summary: UI toolkit

Builtin中文日本語한국어ไทยPurpose
ui_theme(...)界面主题UIテーマ인터페이스테마ธีมส่วนติดต่อSet the six theme colours
ui_theme_colors()————Read the theme back
ui_hot(x, y, w, h)热区ホットエリア핫존พื้นที่สัมผัสIs the mouse inside?
ui_frame(x, y, w, h, bracket)边框フレーム枠프레임틀กรอบCorner brackets
ui_bevel(x, y, w, h, bevel)斜角框ベベル枠베벨틀กรอบเฉียงCorner-cut outline
ui_panel(x, y, w, h, bevel)面板パネル패널แผงFilled backdrop panel
ui_scanlines(x, y, w, h, density)扫描线走査線스캔라인เส้นสแกนCRT scan lines
ui_radar(cx, cy, r, sweep)雷达レーダー레이더เรดาร์Radar scope
ui_compass(x, y, w, h, heading)罗盘コンパス나침반เข็มทิศCompass strip (degrees)
ui_reticle(cx, cy, r, spread)准星照準조준선เป้าเล็งAiming reticle
ui_target(x, y, w, h, lock)锁定框ターゲット표적กรอบเป้าTarget-lock brackets
ui_bar(x, y, w, h, value, max)进度条バー막대แถบFill bar
ui_segbar(x, y, w, h, value, max, segments)分段条分割バー분할막대แถบแบ่งBar of blocks
ui_gauge(cx, cy, r, value, max)仪表ゲージ게이지มาตรวัดDial with a needle
ui_ring(cx, cy, r, value, max)环表リングメーター링미터วงแหวนวัดProgress ring
ui_vu(x, y, w, h, levels)音量条VUメーター음량막대มาตรเสียงLevel meter from a list
ui_spark(x, y, w, h, values)迷你图スパークライン스파크라인กราฟจิ๋วTiny line graph
ui_battery(x, y, w, h, value, max)电池バッテリー배터리แบตเตอรี่Battery icon
ui_progress(x, y, w, h, fraction)进度プログレス진행바ความคืบหน้าThin progress bar
ui_button(x, y, w, h)按钮ボタン버튼ปุ่มButton; 1 when clicked
ui_toggle(x, y, w, h, state)开关トグル토글สวิตช์On/off switch
ui_slider(x, y, w, value, min, max)滑块スライダー슬라이더แถบเลื่อนHorizontal slider
ui_checkbox(x, y, size, checked)复选框チェックボックス체크박스ช่องเลือกCheck box
ui_tabs(x, y, w, h, count, active)标签页タブ탭แท็บTab strip
ui_stepper(x, y, w, h, value, step)步进器ステッパー스테퍼ตัวปรับค่าMinus and plus buttons
ui_tooltip(x, y, w, h)提示框ツールチップ툴팁คำแนะนำCallout bubble
ui_healthbar(x, y, w, h, value, max, pulse)血条体力バー체력바แถบพลังชีวิตGame health bar
ui_cooldown(cx, cy, r, fraction)冷却クールダウン쿨다운คูลดาวน์Cooldown pie
ui_counter(x, y, dw, dh, value, digits)计数器カウンター카운터ตัวนับSeven-segment number
ui_minimap(x, y, w, h)小地图ミニマップ미니맵แผนที่ย่อMinimap frame
ui_dpad(cx, cy, r)方向键方向パッド방향패드ปุ่มทิศทางOn-screen d-pad
ui_slotgrid(x, y, cols, rows, cell, selected)物品格スロットグリッド슬롯격자ช่องไอเทมInventory grid
ui_vignette(intensity)暗角ビネット비네트ขอบมืดScreen-edge alert glow
ui_gauge3d(cx, cy, r, value, max, spin)立体仪表立体ゲージ입체게이지มาตรวัด3มิติSpinning ring gauge
ui_panel3d(x, y, w, h, depth)立体面板立体パネル입체패널แผง3มิติExtruded panel
ui_radar3d(cx, cy, r, tilt, sweep)立体雷达立体レーダー입체레이더เรดาร์3มิติTilted radar dish
ui_sound(name)界面音UI音인터페이스음เสียงปุ่มShort interface sound

ui_theme(...) and ui_theme_colors()

ui_theme sets the colours every widget draws from: six r, g, b triples in the order primary, accent, track (the dim background of meters), warn, text and bg (panel fill). Triples you leave out keep their value, so ui_theme(255, 0, 128) changes only the primary. ui_theme_colors() returns the live theme as a list of 18 numbers, so hand-drawn interface can match it:

bind start = do {
    ui_theme(255, 0, 128)
    println(ui_theme_colors())
}
[255, 0, 128, 40, 255, 180, 44, 62, 100, 255, 90, 90, 190, 235, 255, 10, 16, 24]

The output also shows the built-in defaults for the other five colours.

Layout helpers: ui_hot, ui_frame, ui_bevel, ui_panel, ui_scanlines

ui_hot returns true when the mouse is inside a rectangle; use it for hover effects and your own controls. ui_frame (bracket arm length, default 14) and ui_bevel (corner cut, default 10) draw outlines in the pen colour. ui_panel draws a bevelled panel filled with the theme’s bg colour (bevel default 12; optional border colour from the sixth argument). ui_scanlines draws density horizontal lines (default 24).

bind start = do {
    ui_panel(20, 20, 340, 200, 14)
    if ui_hot(40, 140, 120, 36) { set_color(255, 255, 255) } else { set_color(120, 140, 160) }
    ui_bevel(40, 140, 120, 36, 8)
}

HUD: ui_radar, ui_compass, ui_reticle, ui_target

ui_radar draws range rings and a sweep at angle sweep in radians; drive it from time_now(). ui_compass shows a strip centred on heading in degrees, with a tick every 15 degrees. ui_reticle draws a ring whose gaps open as spread goes from 0 to 1. ui_target draws brackets that close in as lock goes from 0 to 1.

Meters: ui_bar, ui_segbar, ui_gauge, ui_ring, ui_vu, ui_spark, ui_battery, ui_progress

Each meter shows value out of max (default 1). ui_segbar splits the bar into segments blocks (default 10). ui_gauge is a dial with a needle; ui_ring fills clockwise. ui_vu takes a list of levels from 0 to 1, one bar each, shading toward the warn colour as they rise. ui_spark scales a list of at least two numbers to fit its box. ui_battery turns to the warn colour below 25 percent. ui_progress takes a single fraction from 0 to 1.

bind start = do {
    ui_bar(40, 70, 280, 14, 70, 100)
    ui_segbar(40, 96, 280, 14, 6, 10, 10)
    ui_gauge(450, 120, 50, 62, 100)
    ui_vu(330, 330, 160, 60, [0.2, 0.5, 0.8, 1.0, 0.7, 0.3])
}

Controls: ui_button, ui_toggle, ui_slider, ui_checkbox, ui_tabs, ui_stepper, ui_tooltip

  • ui_button highlights on hover and returns 1 on the frame it is clicked, otherwise 0.
  • ui_toggle and ui_checkbox take the current state and return the new one, 1 or 0.
  • ui_slider has no height argument (the grab area is 20 pixels tall). It returns the new value, which follows the cursor while the button is held.
  • ui_tabs draws count equal tabs and returns the active index (from 0). Divide the width by count to place captions.
  • ui_stepper returns value plus or minus step when a side is clicked. It draws no number.
  • ui_tooltip is a callout bubble; draw it near the cursor when something is hovered.
bind start = do {
    bind tab = 0
    bind count = 3
    bind tab = ui_tabs(20, 250, 300, 28, 3, tab)
    bind count = ui_stepper(160, 178, 140, 28, count, 1)
    ui_text(222, 186, 14, str(count))
}

Game UI: ui_healthbar, ui_cooldown, ui_counter, ui_minimap, ui_dpad, ui_slotgrid, ui_vignette

ui_healthbar shifts from the warn colour when empty to the accent colour when full; pulse (0 to 1) flashes it toward white below 30 percent. ui_cooldown fills a pie wedge clockwise from twelve o’clock. ui_counter shows value as digits seven-segment digits. ui_minimap draws an empty map frame; plot your own dots with draw_disc. ui_dpad returns 0 none, 1 up, 2 right, 3 down or 4 left while the mouse is held on it. ui_slotgrid highlights slot selected (-1 for none). ui_vignette glows along the screen edges, for a damage flash.

bind start = do {
    bind hp = 24
    ui_healthbar(20, 300, 220, 16, hp, 100, 0.5 + 0.5 * sin(time_now() * 8))
    ui_counter(20, 340, 16, 28, 1234, 5)
    ui_slotgrid(400, 260, 5, 2, 40, 1)
}

Pseudo-3D: ui_gauge3d, ui_panel3d, ui_radar3d

ui_gauge3d draws a wireframe band that turns with spin, lit up to value. ui_panel3d lifts a bevelled panel off the screen by depth pixels (default 14). ui_radar3d tilts the radar into the screen (tilt 0 to 1, default 0.9).

ui_sound(name)

Plays a short synthesised interface sound: "click" (also the fallback for unknown names), "hover", "confirm", "toggle", "tick" or "error". It is silent if audio isn’t running.

bind start = do {
    if ui_button(20, 400, 120, 36) == 1 { ui_sound("confirm") }
}

Animation

Anima is Ling’s animation system. Anything that moves, whether a 2D drawing, a 3D mesh, a particle or a plain number, is driven by small drivers: functions you call every frame with the current time. Each driver returns a number, and you feed that number into a size, a position, an angle or a pattern argument.

The drivers come in two temperaments:

  • Organic drivers (灵, “spirit”) make soft, lifelike motion: breathing, swaying, walking, springy follow-through and two-bone inverse kinematics.
  • Mechanical drivers (机, “machine”) make exact, rigid motion: meshed gears, cams, slider-cranks and rack and pinion.

You can mix both in one character, for example a creature with a breathing chest and a mechanical jaw. For imported 3D characters with a skeleton, the gltf_* builtins at the end of this page play skeletal animation clips.

Summary

Builtin中文日本語한국어ไทยPurpose
tween(a, b, t)补间補間트윈แทรกค่าLinear interpolation
tween_ease(a, b, t, curve)缓动补间緩和補間이징트윈แทรกนุ่มEased interpolation
ease(curve, t)————Value of a UI easing curve
breathe(t, rate, depth)呼吸呼吸호흡หายใจBreathing scale around 1
wobble(t, freq, amp, phase)摆动揺れ흔들림โยกSway or jiggle
gait_phase(t, speed)步相歩相걸음위상เฟสก้าวWalk-cycle phase
gait_swing(t, speed, stride)步摆歩振り걸음흔들ก้าวแกว่งLeg swing
gait_lift(t, speed, height)抬脚足上げ발들기ยกเท้าFoot lift
spring_to(pos, vel, target, k, d, dt)弹向バネ寄せ스프링이동สปริงไปOne damped-spring step
ik2(l1, l2, tx, ty)反解逆運動역운동ไอเค2Two-bone inverse kinematics
gear_couple(angle, teeth_in, teeth_out)齿轮联动歯車連動기어연동เฟืองทดTwo meshed gears
gear_train(angle, teeth)齿轮组歯車列기어열ชุดเฟืองA chain of meshed gears
cam_lift(angle, lift)凸轮升程カム揚程캠리프트ยกลูกเบี้ยวCam follower
piston(angle, crank, rod)活塞ピストン피스톤ลูกสูบSlider-crank
rack(angle, radius)齿条ラック랙แร็คRack and pinion

How drivers work

Drivers are pure functions. They keep no hidden state, so the same arguments always give the same answer.

  • Time-based drivers (breathe, wobble, gait_*) take the current time from you, usually time_now() or a variable you advance by 1/60 each frame. Nothing plays in the background.
  • The spring driver (spring_to) returns its new state, and you pass it back in on the next frame. Your program owns the state.

Angles are in radians. Lengths use whatever units your drawing uses. The drivers compute in single precision, so the examples round their results with a small helper r3.

Interpolation

tween(a, b, t) and tween_ease(a, b, t, curve)

tween returns a + (b - a) * t. The progress t is clamped to 0..1, so you can keep increasing it past 1 and the value stays at b.

tween_ease does the same through an easing curve. curve is a name from the Anima table below (default "linear"). Elastic and back curves can overshoot b.

ease(curve, t)

The raw value of a UI-toolkit easing curve at progress t (clamped to 0..1): 0 at the start, 1 at the end. The curve name comes first. Use it when you need the curve itself, for example to blend two colours. It has no localized names.

fn r3(x: number) -> number {
    round(x * 1000) / 1000
}

bind start = do {
    print(tween(0, 10, 0.25))
    print(tween(0, 10, 2.0))
    print(r3(tween_ease(0, 100, 0.5, "cubic_in")))
    print(r3(tween_ease(0, 100, 0.5, "bounce_out")))
    print(ease("quad_in", 0.5))
    print(r3(ease("smooth", 0.25)))
}
2.5
10
12.5
76.563
0.25
0.125

Easing curve names

The two builtins use different name sets. Both ignore case.

tween_ease (Anima curves). Underscores are optional. Unknown names give linear.

FamilyNames
Basiclinear, step
Quadraticquad_in, quad_out, quad_in_out
Cubiccubic_in, cubic_out, cubic_in_out (also smooth)
Sinesine_in, sine_out, sine_in_out
Exponentialexpo_in, expo_out, expo_in_out
Elasticelastic_in, elastic_out (also elastic)
Backback_in, back_out, back_in_out (also overshoot)
Bouncebounce_in, bounce_out (also bounce)

ease (UI curves). Dashes and underscores are interchangeable. Unknown names give quad_inout.

NameShape
linearStraight line
quad_in, ease_inSlow start
quad_out, ease_outSlow finish
quad_inout, ease, smoothSlow start and finish (the default)
cubic_in, cubic_out, cubic_inoutStronger versions
quart_outFast start, long slow finish
sine, sine_inoutGentle sine in-out
expo, expo_outExponential decay
back, back_outOvershoots, then settles
elastic, elastic_outSpringy overshoot
bounce, bounce_outBounces at the end

Organic drivers

breathe(t, rate, depth)

A breathing multiplier centred on 1: 1 + depth * sin(2π * rate * t). rate is breaths per second (default 1), depth the amplitude (default 0.1). Multiply a size or a pattern radius by it.

wobble(t, freq, amp, phase)

A sine sway for secondary motion: amp * sin(2π * (freq * t + phase)). Defaults: freq 1, amp 1, phase 0. The phase is in cycles, so 0.25 is a quarter-cycle shift. Give each limb a different phase and the body sways out of lockstep.

gait_phase(t, speed), gait_swing(t, speed, stride) and gait_lift(t, speed, height)

A walk cycle. speed is cycles per second (default 1).

  • gait_phase returns where the cycle is, from 0 up to (not including) 1.
  • gait_swing returns the forward and backward swing of a leg, between -stride and stride. For the other leg, use t + 0.5 / speed.
  • gait_lift returns how high the foot is raised: positive during the swing half, 0 while planted. Screen y points down, so subtract it: foot_y = ground_y - gait_lift(...).
fn r3(x: number) -> number {
    round(x * 1000) / 1000
}

bind start = do {
    bind t = 0.125
    print(r3(breathe(t, 1, 0.2)))
    print(r3(wobble(t, 1, 10, 0)))
    print(r3(gait_phase(t, 2)))
    print(r3(gait_swing(t, 1, 30)))
    print(r3(gait_lift(t, 1, 10)))
}
1.141
7.071
0.25
21.213
7.071

spring_to(pos, vel, target, stiffness, damping, dt)

One step of a damped spring pulling pos toward target. Use it for follow-through, camera smoothing and tails. Defaults: stiffness 120, damping 14, dt 1/60. It returns a two-element list [new_pos, new_vel]. Keep both numbers and pass them back next frame.

With the defaults, the value overshoots a little, then settles within about a second:

bind start = do {
    bind pos = 0.0
    bind vel = 0.0
    bind frame = 0
    while frame < 60 {
        bind s = spring_to(pos, vel, 1.0, 120, 14, 1 / 60)
        bind pos = s[0]
        bind vel = s[1]
        bind frame = frame + 1
        if frame % 15 == 0 {
            print(str(frame) + ": " + str(round(pos * 1000) / 1000))
        }
    }
}
15: 0.982
30: 1.021
45: 0.997
60: 1

ik2(l1, l2, tx, ty)

Planar two-bone inverse kinematics: the shoulder and elbow angles that bring the tip of a two-segment arm or leg to a target. l1 and l2 are the bone lengths (default 1), and (tx, ty) is the target relative to the shoulder.

It returns [shoulder, elbow] in radians. shoulder is the angle of the first bone, and elbow is the bend of the second bone relative to the first. A target out of reach is clamped, so the limb stretches toward it. To place the joints:

  • elbow = shoulder position + l1 * (cos(shoulder), sin(shoulder))
  • hand = elbow + l2 * (cos(shoulder + elbow), sin(shoulder + elbow))
fn r3(x: number) -> number {
    round(x * 1000) / 1000
}

bind start = do {
    bind a = ik2(1, 1, 1, 1)
    print([r3(a[0]), r3(a[1])])
}
[1.571, -1.571]

Mechanical drivers

BuiltinReturns
gear_couple(angle, teeth_in, teeth_out)The driven gear’s angle: -angle * teeth_in / teeth_out (0 if teeth_out is 0). Meshed gears turn the opposite way.
gear_train(angle, teeth)A list with the angle of every gear in a chain. teeth is a list of tooth counts; the first element of the result is angle itself.
cam_lift(angle, lift)Cam follower height: lift * (1 - cos(angle)) / 2, from 0 at angle 0 to lift at π.
piston(angle, crank, rod)Piston pin position along the cylinder from the crank centre. Defaults: crank 1, rod 2 (the rod should be longer than the crank).
rack(angle, radius)Rack travel: angle * radius.

A 12-tooth gear driving a 36-tooth gear turns it a third as fast, the other way:

fn r3(x: number) -> number {
    round(x * 1000) / 1000
}

bind start = do {
    print(r3(gear_couple(3, 12, 36)))
    bind g = gear_train(1, [12, 36, 12])
    print([r3(g[0]), r3(g[1]), r3(g[2])])
    print(r3(cam_lift(3.14159265, 2)))
    print(r3(piston(0, 1, 3)))
    print(rack(2, 0.5))
}
-1
[1, -0.333, 1]
2
4
1

A moving scene

This window combines a breathing disc, a walking foot and a spring that chases a moving target. The spring’s position and velocity are carried from frame to frame.

bind start = do {
    open_window(640, 360, "Anima")
    bind t = 0.0
    bind px = 0.0
    bind pv = 0.0
    while window_is_open() {
        fill(10, 12, 28)
        # organic: a breathing disc
        set_color(120, 220, 255)
        draw_disc(120, 120, 40 * breathe(t, 0.4, 0.12))
        # organic: a walking foot
        bind sw = gait_swing(t, 1.0, 30)
        bind lift = gait_lift(t, 1.0, 20)
        set_color(255, 210, 90)
        draw_line(120, 200, 120 + sw, 260 - lift)
        draw_disc(120 + sw, 260 - lift, 10)
        # organic: a spring chasing a target
        bind target = 400 + 80 * sin(t * 1.3)
        bind s = spring_to(px, pv, target, 120, 10, 0.016)
        bind px = s[0]
        bind pv = s[1]
        set_color(120, 255, 160)
        draw_disc(px, 180, 12)
        present()
        bind t = t + 0.016
    }
}

Skeletal animation (glTF)

Rigged characters exported as .glb or .gltf carry a skeleton, skin weights and animation clips. These builtins load such a model and draw it skinned. They have no localized names, except the two textured draws: gltf_anim_draw_tex is also 骨骼动画纹理绘制 (zh), スキンアニメ描画 (ja), 글꼴애니텍스처 (ko), วาดแอนิเมชันมีพื้นผิว (th), and gltf_pose_draw_tex is also 骨骼姿势纹理绘制, スキンポーズ描画, 글꼴포즈텍스처, วาดสกินมีพื้นผิว.

BuiltinPurpose
gltf_load(path)Load a model. Returns a handle, or -1 on failure.
gltf_anim_count(h)Number of animation clips.
gltf_anim_name(h, i)Name of clip i.
gltf_anim_dur(h, i)Length of clip i in seconds.
gltf_joint_count(h)Number of skin joints (bones).
gltf_joint_name(h, j)Name of joint j.
gltf_autorig(h)Give a model without a skeleton a procedural 20-bone humanoid rig. Returns the bone count.
gltf_anim_draw_tex(h, x, y, z, scale, yaw, clip, time)Draw the model textured and skinned by clip clip at time seconds.
gltf_pose_draw(h, x, y, z, scale, yaw, pose)Draw the model skinned by your own pose (flat colours).
gltf_pose_draw_tex(h, x, y, z, scale, yaw, pose)The same, textured.
gltf_bounds(h, clip, time)[minX, minY, minZ, maxX, maxY, maxZ] of the model as drawn with that clip and time.

Notes:

  • Clip time wraps, so you can pass an ever-growing time and the clip loops.
  • pose is a flat list of Euler angles in radians, three per bone (X, Y, Z).
  • glTF models are Y-up. The draws flip them into the renderer’s y-down space, so (x, y, z) is where the model’s origin (usually its feet) goes.
  • gltf_anim_draw_tex takes more optional arguments after time: ambient light, back-face culling (1 to cull), a source model whose clips drive this one (for equipment matched by joint name), a list of extra per-bone rotations, and a 0xRRGGBB tint.
  • gltf_draw(h, x, y, z, scale, yaw) draws the model unskinned. gltf_mesh_count, gltf_mesh_name, gltf_mesh_show(h, i, on) and gltf_mesh_tint(h, i, 0xRRGGBB) show, hide or tint individual meshes, for example to swap equipment.
bind start = do {
    open_window(960, 540, "Walk")
    set_depth_test(1)
    bind hero = gltf_load("hero.glb")
    bind i = 0
    while i < gltf_anim_count(hero) {
        print(gltf_anim_name(hero, i) + ": " + str(gltf_anim_dur(hero, i)) + " s")
        bind i = i + 1
    }
    while window_is_open() {
        fill(20, 24, 40)
        gltf_anim_draw_tex(hero, 0, 2, 6, 1, 0.5, 0, time_now())
        flush_3d()
        present()
    }
}

What is not a builtin

The ling-animation crate also has keyframe tracks and timelines, a joint rig with skinning matrices, procedural biped and quadruped gaits, a four-bar linkage solver and a facial rig. Those are Rust APIs for embedders, not Ling builtins. Names such as rig_load or anim_play that appear in older documents do not exist, and delta_time() is not implemented. Use time_now() for time.

See also: Post-FX and Lighting, Window and Camera.

Post-FX and Lighting

This page covers how Ling lights a 3D scene and how it finishes each frame. Lights and shading decide the colour of every triangle as it is drawn. Then a screen-space post chain runs over the finished image: ambient occlusion, ink outlines, a tone ramp, bloom and anti-aliasing. On top of that you can add depth of field, a screen warp and soft volumetric light shafts.

Everything here draws into the open window, so the examples are ling-gui programs.

Summary

Builtin中文日本語한국어ไทยPurpose
set_ambient(level)环境光環境光設定환경광설정ตั้งแสงรอบข้างAmbient light level
add_light(x, y, z, r, g, b, intensity, radius)加灯ライト追加조명추가เพิ่มแสงAdd a point light
clear_lights()清灯ライト消去조명초기화ล้างแสงRemove all lights
set_fog(r, g, b, start, end)雾霧設定안개설정ตั้งหมอกDistance fog
set_shade_mode(m)设置着色シェード設定셰이드모드ตั้งการแรเงาFlat, cel or holographic shading
set_cel_bands(n)设置色阶セル段数셀밴드ตั้งระดับสีNumber of brightness bands
set_shadow_color(r, g, b)设置阴影色影の色그림자색ตั้งสีเงาTint of unlit areas
set_rim(strength, r, g, b)设置边缘光リム設定림라이트ตั้งขอบเรืองRim glow on silhouettes
set_flat_shade(on)平面着色フラット着色평면음영ตั้งแฟลตเชดSkip lighting entirely
set_material(key, value)设置材质マテリアル設定재질설정ตั้งวัสดุSet a material property
reset_material()重置材质マテリアルリセット재질초기화รีเซ็ตวัสดุBack to ordinary lighting
set_ssao(strength, radius_px, zrange)环境光遮蔽アンビエントオクルージョン앰비언트오클루전ตั้งเงาสัมผัสAmbient occlusion
toon_outlines(thickness, color, threshold)卡通轮廓トゥーンアウトライン툰아웃라인ตั้งเส้นขอบการ์ตูนInk outlines
tone_stop(t, value)色调停止トーンストップ톤스톱ตั้งจุดโทนAdd a tone-ramp stop
tone_smooth(on)色调平滑トーンスムーズ톤스무스ตั้งโทนนุ่มHard bands or smooth ramp
tone_bezier(y1, y2)色调贝塞尔トーンベジェ톤베지어ตั้งโทนเบซิเยร์Contrast curve
tone_bezier_off()关闭色调贝塞尔トーンベジェオフ톤베지어끄기ปิดโทนเบซิเยร์Remove the contrast curve
tone_ramp_reset()重置色调渐变トーンランプリセット톤램프리셋รีเซ็ตการไล่โทนDefault three-band ramp
tone_ramp_clear()清除色调渐变トーンランプクリア톤램프클리어ล้างการไล่โทนRemove all stops
tone_soft(soft, sheen)色调柔边トーンソフト톤소프트โทนขอบนุ่มSoft band edges, smooth highlights
set_bloom(strength, threshold)泛光ブルーム블룸ตั้งบลูมGlow around bright pixels
set_fxaa(on)屏幕抗锯齿画面アンチエイリアス화면안티앨리어싱ลบรอยหยักScreen anti-aliasing
flush_post()后期冲刷—포스트플러시—Run the post chain now, before the HUD
depth_blur(focus, range, radius, oil)景深景深—เบลอความลึกDepth of field
screen_distort(amount, t, step)屏幕扭曲画面歪み화면왜곡บิดจอViscous screen warp
light_pool(x, y, z, radius, r, g, b, intensity)光池ライトプール빛웅덩이แอ่งแสงPool of light on the floor
light_beam(x, y, z, floor_y, radius, r, g, b, intensity)光柱ライトビーム빛기둥ลำแสงไฟVolumetric light shaft

The interpreter accepts every name in the table. lingfu normalize translates only some of them (the lights and set_ambient), so the localized examples on this site keep the English names for the rest.

Lights

Lights follow the same per-frame routine as drawing: clear them, add them, draw.

set_ambient(level)

The light that reaches every surface regardless of lights, from 0 to 1 (default 0.15).

add_light(x, y, z, r, g, b, intensity, radius)

Adds a coloured point light at a world position. The colour can be 0 to 1 or 0 to 255: if any channel is above 1.5, all three are read as 0 to 255. intensity is a brightness multiplier (default 1). radius is the distance at which the light fades to nothing; 0 means no falloff (the default).

The order is position, colour, intensity, radius. Lights add up until you call clear_lights(), so clear and re-add them every frame.

set_fog(r, g, b, start, end)

Distance fog: geometry fades toward the colour (0 to 255) between camera depths start and end. end of 0 or less turns fog off. The volumetric lights below fade with the fog too.

bind start = do {
    open_window(720, 420, "Lights")
    set_depth_test(1)
    set_ambient(0.2)
    set_fog(8, 10, 24, 10, 40)
    while window_is_open() {
        fill(8, 10, 24)
        clear_lights()
        add_light(0, -5, 4, 1.0, 0.85, 0.6, 1.2, 20)
        set_color(240, 150, 110)
        cube(0, 0, 8, 1, 1, 1, 0.3, time_now(), 0, 0)
        present()
    }
}

Shading

For each vertex the shader mixes your pen colour with the ambient term (tinted by the shadow colour where a surface faces away from every light), each light’s contribution, a rim glow toward the silhouette, and in the default mode a faint iridescent sheen. The result is quantised into a few brightness bands.

The defaults are deliberately stylised: a cool indigo shadow tint, a cyan rim and the holographic sheen. For colours that match your pen, use set_shade_mode(1), set_rim(0, 0, 0, 0) and a dark neutral set_shadow_color.

BuiltinParameters
set_shade_mode(m)0 flat, one band per triangle; 1 smooth cel, no sheen, rim reduced; 2 holographic (default).
set_cel_bands(n)Number of bands, at least 2 (default 4).
set_shadow_color(r, g, b)Tint for unlit areas, 0 to 255 (default 26, 33, 77).
set_rim(strength, r, g, b)Rim strength (default 0.6; 0 turns it off) and colour 0 to 255 (default 115, 217, 255).
set_flat_shade(on)Non-zero skips all lighting and draws the raw pen colour. Meant for performance tests.

set_material(key, value) and reset_material()

set_material turns on a physically based toon material for later draw_triangle_3d and polygon draws. key is a string and value a number; colour keys take a packed 0xRRGGBB number. Keys: albedo, roughness, metallic, emission, emission_strength, specular, specular_tint, subsurface, subsurface_color, clearcoat, clearcoat_roughness, transmission, ior, iridescence, sheen, anisotropy, anisotropy_angle, toon_bands, shadow_softness, outline_px, outline_color, highlight_color. Unknown keys are ignored. reset_material() switches back to ordinary lighting. The primitive solids (cube, sphere, …) do not read the material.

The post chain

The post chain runs inside present() in this order:

  1. Ambient occlusion (set_ssao): soft contact shadows from the depth buffer.
  2. Outlines (toon_outlines): ink lines where depth jumps.
  3. Tone ramp (tone_*): maps brightness to cel bands.
  4. Bloom (set_bloom): glow bleeding from bright pixels.
  5. FXAA (set_fxaa): edge anti-aliasing over the final image.

Ambient occlusion, outlines, bloom and FXAA are off until you turn them on. The tone ramp always runs, starting from the default three-band ramp. Occlusion and outlines read the depth buffer, so call set_depth_test(1) first.

Vector lines and text are exempt from the tone ramp, so interface text and wireframes never snap into bands.

set_ssao(strength, radius_px, zrange)

Soft darkening in corners, creases and under objects, computed at half resolution and smoothed. strength 0 to 1 (0 is off), radius_px the sampling radius in pixels (default 6), zrange the depth window in which a neighbour counts as an occluder (default 12).

toon_outlines(thickness, color, threshold)

Ink lines on depth discontinuities. thickness is the half-width in pixels (0 is off, 1.5 is a good anime default), color a packed 0xRRGGBB number (default 0, black), threshold the depth jump that counts as an edge (default 0.05).

The tone ramp

The tone ramp is a list of stops, each mapping an input brightness t to an output brightness value (both 0 to 1). The default ramp has three bands: 0.08 below 0.25, 0.50 below 0.60, and 1.00 above.

  • tone_stop(t, value) adds a stop. Stops are kept sorted by t.
  • tone_ramp_clear() removes all stops so you can build your own. tone_ramp_reset() restores the default.
  • tone_smooth(on): 0 snaps hard between stops (default), 1 blends smoothly.
  • tone_bezier(y1, y2) remaps the input brightness through a cubic Bézier before the lookup. About 0.333, 0.667 is neutral (the defaults), 0, 0 is shadow-heavy, 1, 1 highlight-heavy and 0.1, 0.9 an S-curve. tone_bezier_off() removes it.
  • tone_soft(soft, sheen): soft (0 to 1, default 0.32) is the fraction of each band gap that blends across the boundary, from razor-sharp at 0 to soft shadow edges around 0.3. sheen (0 to 1, default 0.65) lets bright pixels keep their gradient, so highlights look like a clean sheen instead of scratchy bands.

Two common looks:

LookCalls
Crisp anime celtone_smooth(0), tone_soft(0.32, 0.65)
Painterly, smoothtone_smooth(1), tone_bezier(0.12, 0.88), tone_soft(0.32, 0.65)

set_bloom(strength, threshold)

Bright pixels bleed a soft glow, computed at quarter resolution. strength defaults to 0.45 (0 is off); threshold is the luminance cutoff from 0 to 0.99 (default 0.74).

set_fxaa(on)

A light anti-aliasing pass over the whole image (default argument 1). It softens polygon stair-steps and outline jaggies and leaves flat fills alone. It is different from set_antialias, which smooths wireframe strokes as they are drawn.

flush_post()

Flushes the 3D queue like flush_3d(), then runs the post chain immediately. present() skips the chain for that frame, so a HUD drawn after flush_post() stays crisp, with no bloom or blur. post_now() is another English name for it.

bind start = do {
    open_window(960, 540, "Toon")
    set_depth_test(1)
    set_shade_mode(1)
    set_rim(0, 0, 0, 0)
    set_shadow_color(30, 30, 50)
    toon_outlines(1.5, 0, 0.05)
    set_ssao(0.4, 7, 14)
    tone_smooth(1)
    tone_bezier(0.12, 0.88)
    tone_soft(0.32, 0.65)
    set_bloom(0.5, 0.74)
    set_fxaa(1)
    while window_is_open() {
        fill(20, 24, 40)
        clear_lights()
        add_light(-2, -6, -2, 1.0, 0.95, 0.85, 0.8, 0)
        set_color(220, 180, 120)
        sphere(0, 0, 8, 1.5, 1.5, 1.5, 0, time_now(), 0, 0)
        flush_post()
        set_color(255, 255, 255)
        ui_text(20, 20, 16, "HUD")
        present()
    }
}

Screen effects

depth_blur(focus, range, radius, oil)

Depth of field over the frame, using the depth buffer. The image is sharp at camera depth focus (default 30) and reaches full blur radius pixels (default 3) as depth moves range away (default 60). Background with no geometry blurs fully. oil (0 to 1, default 0) adds an iridescent oil-slick fringe and hue swirl to the blurred zone, for water or heat haze. dof and depth_of_field are other English names.

Call it after flush_3d() (so the depth buffer is filled) and before you draw the interface. It needs set_depth_test(1).

screen_distort(amount, t, step)

A viscous full-screen warp that wraps at the edges, for goo, heat haze and dream effects. amount is the largest displacement in pixels (default 8), t a time value so the warp moves (default 0), and step 1 for full resolution or 2 and up for a cheaper block warp (default 1). Like depth_blur, call it after the 3D flush and before the interface. It is not available in the browser build.

bind start = do {
    open_window(960, 540, "Haze")
    set_depth_test(1)
    while window_is_open() {
        fill(10, 20, 40)
        set_color(120, 200, 255)
        cube(0, 0, 8, 1, 1, 1, 0, time_now(), 0, 0)
        cube(3, 0, 20, 1, 1, 1, 0, time_now(), 0, 0)
        flush_3d()
        depth_blur(8, 6, 4, 0.3)
        screen_distort(4, time_now(), 2)
        present()
    }
}

Volumetric light

light_pool and light_beam draw soft, additive gradients that look like light spreading through water or dusty air. Their outer edges fade to black, so with additive blending they have no visible rim. Both fade with distance fog, and their cost is fill rate: the bigger on screen, the more expensive.

light_pool(x, y, z, radius, r, g, b, intensity)

The coloured splash a lamp throws on the floor at height y. Defaults: position 0, radius 20, colour 255 (0 to 255 per channel), intensity 1 (about 0.2 to 1.5 looks good).

light_beam(x, y, z, floor_y, radius, r, g, b, intensity)

A god-ray: a double cone from the light position down to the floor plane at floor_y, widening to radius (default 14). Pair it with a light_pool at its base.

Draw both with set_blend(1) (additive) and return to set_blend(0) afterwards. They look best with tone_smooth(1), because hard bands turn smooth gradients into flat steps.

bind start = do {
    open_window(720, 420, "Volumetric")
    set_depth_test(1)
    set_ambient(0.2)
    set_shade_mode(1)
    tone_smooth(1)
    set_bloom(0.5, 0.74)
    while window_is_open() {
        fill(6, 8, 18)
        set_camera(1, 0, cos(0.25), sin(0.25))
        set_camera_pos(0, -3, 0)
        clear_lights()
        add_light(0, -5, 8, 1.0, 0.9, 0.7, 0.8, 0)
        set_color(220, 180, 120)
        cylinder(0, 1.3, 9, 0.8, 0.7, 0.8, 0, 0, 0, 0)
        set_blend(1)
        light_beam(0, -6, 9, 2, 3.0, 255, 220, 160, 0.8)
        light_pool(0, 2, 9, 5.0, 255, 220, 160, 0.9)
        set_blend(0)
        flush_3d()
        present()
    }
}

Older names

shadow_smooth(softness) is an older shortcut that sets tone_smooth and tone_bezier together; use those instead. toon_highlight(...) is accepted but does nothing; use tone_stop and tone_soft.

See also: Window and Camera, 3D Shapes and Meshes, Animation.

Audio

The audio engine plays everything a game needs: continuous tones placed in 3D space, short blips and sound effects, sample files, a looping background track and a master effect chain. A separate FFT analyser turns sample data into frequency bands for audio-reactive visuals.

For whole songs, instrument patches, MIDI and the DAW, see Music. For the microphone, see Input and Microphone.

Things to know first:

  • The runtime opens the audio device when the program starts. With no output device, the audio_* builtins silently do nothing.
  • Times are in seconds. Arguments shown in a signature are optional from the point where a default is listed.
  • Audio is native only: in the browser build the FFT builtins do nothing and some calls take fewer arguments (noted below).
  • Because these examples make sound, they are ling-gui programs. The FFT example at the end runs anywhere.

Summary

Builtin中文日本語한국어ไทยPurpose
audio_volume(level)音量音量음량ระดับเสียงMaster volume
audio_bgm(path, volume)背景乐BGM배경음악เพลงประกอบLoop a WAV as background music
audio_bgm_volume(level)背景乐音量BGM音量배경음악음량ระดับเพลงประกอบBackground-music volume
audio_tone(slot, x, y, z, w, freq, amp, lfo_rate, lfo_depth, wave, duty)音调音調음조เสียงโทนContinuous positional oscillator
audio_glide(amp_ms, freq_ms)————Smoothing time for tone changes
audio_listener(cos_yaw, sin_yaw, cos_pitch, sin_pitch)音频监听音声リスナー오디오리스너ผู้ฟังListener orientation
audio_blip(freq, duration, wave, amp)提示音ビープ音효과음เสียงบี๊บShort interface blip
ui_sound(name)界面音UI音인터페이스음เสียงปุ่มBuilt-in interface sound
audio_sfx(x, y, z, w, freq, amp, duration, wave)音效空間効果音공간효과음เสียงเอฟเฟกต์Positional one-shot effect
morph_note(x, y, z, w, freq, amp, duration, material, morph)变形音モーフ音모프음โน้ตมอร์ฟPhysical/digital morph note
audio_stop_sfx()停止音效効果音停止효과음정지หยุดเอฟเฟกต์ทั้งหมดStop all one-shot voices
audio_sample_load(path)载入采样サンプル読込샘플로드โหลดตัวอย่างเสียงDecode a sound file
audio_sample_play(id, x, y, z, w, volume, loop, pitch)播放采样サンプル再生샘플재생เล่นตัวอย่างเสียงPlay a sample in 3D
audio_sample_play_flat(id, volume, loop, pitch)————Play a sample without positioning
audio_sample_stop(voice)停止采样サンプル停止샘플정지หยุดตัวอย่างเสียงStop a sample voice
audio_sample_duration(id)采样时长サンプル長さ샘플길이ความยาวตัวอย่างเสียงLength of a sample
audio_fx_delay(time, feedback, mix)回声ディレイ効果딜레이เสียงสะท้อนMaster echo
audio_fx_reverb(mix)混响リバーブ리버브เสียงก้องMaster reverb
audio_fx_lowpass(cutoff)低通滤波ローパス저역통과กรองความถี่ต่ำMaster low-pass filter
fft_push(samples)频谱输入FFT入力FFT입력วิเคราะห์เสียงFeed samples to the analyser
fft_bands(n)频段周波数帯주파수대แถบความถี่Log-spaced frequency bands
fft_beat()节拍检测ビート検出비트จังหวะเสียงIs there a beat now?
fft_beat_ratio()节拍比ビート比비트비율อัตราจังหวะBeat strength
fft_rms()均方根二乗平均RMS레벨ระดับRMSOverall loudness
fft_dominant_freq()主频主要周波数주파수ความถี่หลักStrongest frequency in Hz

How the engine mixes

One output stream carries four kinds of sound:

  • Tones: long-lived oscillators in numbered slots, placed in space (audio_tone).
  • One-shots: blips (audio_blip, ui_sound), positional effects (audio_sfx) and morph notes (morph_note).
  • Samples: decoded files played in 3D or flat (audio_sample_*).
  • Background music: one looping WAV (audio_bgm).

The listener is the camera. Pan is equal-power left/right from the sound’s position relative to the camera, and level falls off with distance. set_camera_pos moves the listener; audio_listener turns it. The final mix is soft-clipped, so loud mixes distort gently instead of clipping hard.

Tone slots grow on demand. There are 32 blip voices, 64 effect voices, 32 morph voices and 64 sample voices; when a pool is full, the oldest voice is dropped.

Volume and background music

audio_volume(level)

Master gain for everything this engine mixes (default 0.7; 1.0 is unity). It does not affect the music engine, which has its own music_volume.

audio_bgm(path, volume) and audio_bgm_volume(level)

audio_bgm loads a WAV file and loops it as background music (default volume 0.5). A second call replaces the track. If the file can’t be read, an error goes to standard error and the program continues in silence. The path is used exactly as given. For MP3, OGG, FLAC or AAC, use audio_sample_load or music_load.

audio_bgm_volume changes the level without reloading.

bind start = do {
    audio_volume(0.6)
    audio_bgm("theme.wav", 0.4)
    audio_bgm_volume(0.15)
}

Tones

audio_tone(slot, x, y, z, w, freq, amp, lfo_rate, lfo_depth, wave, duty)

Creates or retunes a continuous oscillator. Reusing a slot updates that tone in place, and frequency and amplitude glide to their new values, so you can call it every frame.

ParameterDefaultMeaning
slot0Tone slot number.
x, y, z0World position of the source.
w1Fourth-dimension value. It drives a slow sub-oscillator that cross-modulates the tone; 0 disables it.
freq220Frequency in Hz.
amp0.15Amplitude. Pass 0 to silence the slot (there is no delete).
lfo_rate0.5Vibrato speed in Hz.
lfo_depth0.02Vibrato depth as a fraction of freq.
wave"sine""sine", "square", "saw", "triangle" or "noise" (stepped noise pitched at freq).
duty0.5Square pulse width, for example 0.125, 0.25, 0.5, 0.75 for chiptune voices.

audio_glide(amp_ms, freq_ms)

Sets how long tone amplitude and frequency take to glide to a new value, in milliseconds (0 or less keeps the default). A chiptune player that updates tones once per frame sounds smoother at about 10 ms.

audio_listener(cos_yaw, sin_yaw, cos_pitch, sin_pitch)

Turns the listener. Pass the same four numbers you give set_camera (defaults 1, 0, 1, 0). Call it each frame when the camera turns.

bind start = do {
    open_window(640, 360, "Tones")
    audio_tone(0, 0, 0, 6, 0, 261.63, 0.10, 0.5, 0.01)
    audio_tone(1, 0, 0, 6, 0, 440.0, 0.06, 0, 0, "square", 0.25)
    bind yaw = 0.0
    while window_is_open() {
        bind yaw = yaw + 0.01
        set_camera(cos(yaw), sin(yaw), 1, 0)
        audio_listener(cos(yaw), sin(yaw), 1, 0)
        fill(10, 12, 28)
        present()
    }
}

One-shot sounds

audio_blip(freq, duration, wave, amp)

A short, non-positional blip with a fast attack and decay. Defaults: freq 660 Hz, duration 0.08 s (minimum 0.01), wave "sine", amp 0.25. Wave names: "sine", "square" ("sq"), "saw" ("sawtooth"), "tri" ("triangle"), "noise". Unknown names play a sine.

ui_sound(name)

One of the built-in interface sounds: "click" (default), "hover", "confirm", "error", "toggle", "tick". Any other name plays "click".

audio_sfx(x, y, z, w, freq, amp, duration, wave)

A synthesised one-shot at a world position, panned and attenuated like a tone. Defaults: position 0, w 1, freq 440, amp 0.3, duration 0.15, wave "sine".

morph_note(x, y, z, w, freq, amp, duration, material, morph)

A “yin-yang” note that blends a physical model with a digital one. material is 0 bowed string, 1 plucked, 2 blown, 3 struck metal. morph goes from 0 (light, acoustic) to 1 (dark, digital: FM, bit crush, drive). Defaults: freq 220, amp 0.3, duration 0.6.

audio_stop_sfx()

Stops every one-shot effect, morph note and sample voice at once, so tails don’t leak across a scene change. Tones, background music and the music engine keep playing.

bind start = do {
    ui_sound("confirm")
    audio_blip(880, 0.06, "square", 0.2)
    audio_sfx(1.5, 0, 4, 1, 330, 0.3, 0.2, "triangle")
    morph_note(0, 0, 5, 1, 220, 0.3, 1.2, 1, 0.4)
}

Samples

audio_sample_load(path)

Decodes a WAV, FLAC, OGG, MP3 or AAC file into memory, mixed down to mono. If the path doesn’t exist as given, it is tried relative to the script’s folder. Returns a sample id (from 0), or -1 on failure or when there is no audio device.

audio_sample_play(id, x, y, z, w, volume, loop, pitch)

Plays a loaded sample at a world position, panned and attenuated relative to the listener. volume defaults to 1, loop above 0.5 loops, and pitch is a playback-rate multiplier (2 is an octave up, 0.5 an octave down). w has no audible effect on samples. Returns a voice id, or 0 on failure. In the browser build the signature is (id, x, y, z, w, volume, loop), without pitch.

audio_sample_play_flat(id, volume, loop, pitch)

Plays a sample with no pan and no distance falloff. Use it for narration, voice-over and interface cues. Returns a voice id, or 0.

audio_sample_stop(voice) and audio_sample_duration(id)

audio_sample_stop stops a voice returned by a play call. audio_sample_duration returns a sample’s length in seconds (0 for an unknown id), handy for pacing a cut-scene to the clip that was actually loaded.

bind start = do {
    bind step = audio_sample_load("step.ogg")
    bind hum = audio_sample_load("hum.wav")
    audio_sample_play(step, 1.0, 0.0, 3.0, 1.0, 0.8, 0, 1.2)
    bind v = audio_sample_play_flat(hum, 0.5, 1, 1.0)
    print(audio_sample_duration(hum))
    audio_sample_stop(v)
}

Master effects

The master chain is delay, then reverb, then a low-pass filter. All three start off or fully open.

BuiltinParameters
audio_fx_delay(time, feedback, mix)Echo time in seconds (default 0.3), feedback 0 to 0.95 (default 0.3), wet mix 0 to 1 (default 0.3; 0 turns it off).
audio_fx_reverb(mix)Reverb wet mix, 0 to 1 (default 0.3).
audio_fx_lowpass(cutoff)0 to 1. 1 is open; lower values muffle the mix, for an underwater feel. The filter glides to the new value.
bind start = do {
    audio_fx_delay(0.35, 0.4, 0.25)
    audio_fx_reverb(0.4)
    audio_fx_lowpass(0.15)
}

FFT analysis

The FFT analyser works on samples you give it. Push a block of mono samples (numbers between -1 and 1, at 44.1 kHz) with fft_push, then read the results:

BuiltinReturns
fft_bands(n)A list of n log-spaced magnitude bands (default 32), bass first.
fft_beat()true when the latest block is a beat.
fft_beat_ratio()Beat strength: 1 is at the detection threshold, above 1 is a strong beat.
fft_rms()Root-mean-square level of the signal.
fft_dominant_freq()The strongest frequency in Hz.

This program builds a 1000 Hz sine wave and analyses it. The answer is close to 1000, limited by the analyser’s frequency resolution:

bind start = do {
    bind samples = []
    bind i = 0
    while i < 4096 {
        bind samples = samples.push(sin(i * 6.2831853 * 1000 / 44100))
        bind i = i + 1
    }
    fft_push(samples)
    print(round(fft_dominant_freq()))
    print(round(fft_rms() * 1000) / 1000)
    bind bands = fft_bands(8)
    bind loudest = 0
    bind k = 1
    while k < len(bands) {
        if bands[k] > bands[loudest] {
            bind loudest = k
        }
        bind k = k + 1
    }
    print("loudest band: " + str(loudest))
}
991
0.707
loudest band: 4

To react to a song that is playing, use music_fft(track, bands) on the Music page; for the microphone, mic_fft on Input and Microphone.

Music

The music_* builtins work with whole pieces of music. They decode and analyse audio files, play one track at a time, play notes on instrument patches, convert between notes and frequencies, read MIDI and .lrc lyric files, and judge rhythm-game hits. The daw_* builtins go further: they drive the engine of the LingStationX digital audio workstation, so a script can build a song, add effects and render it to a file.

For tones, sound effects and sample files, see Audio.

Conventions:

  • Track, patch, MIDI and lyric handles are small integers counting from 0. A failed load returns -1. An unknown handle gives 0, an empty string or an empty list, never an error.
  • Paths are used as given if the file exists, otherwise relative to the running script’s folder.
  • A pitch is a MIDI number (60 is middle C, 69 is A4) or a note name such as "C4", "A#3" or "Db5".
  • Analysis, MIDI, lyrics and offline DAW work need no audio device, so those examples run anywhere.

Summary

Builtin中文日本語한국어ไทยPurpose
music_load(path)载入音乐音楽読込음악로드โหลดเพลงDecode an audio file
music_duration(track)音乐时长音楽長さ음악길이ความยาวเพลงLength in seconds
music_bpm(track)节拍速度テンポ템포จังหวะต่อนาทีEstimated tempo
music_key(track)调性調性조성คีย์เพลงEstimated key
music_onsets(track)音符起点オンセット온셋จุดเริ่มเสียงTimes of hits and note starts
music_beat_grid(track)节拍网格ビートグリッド비트그리드กริดจังหวะRegular beat times
music_fft(track, bands)音乐频谱音楽スペクトル음악스펙트럼สเปกตรัมเพลงSpectrum at the playback position
music_fft_groups(track, size, groups)————Loudness groups from one large FFT
music_play(track)播放音乐音楽再生음악재생เล่นเพลงPlay a track from the start
music_pause()暂停音乐音楽一時停止음악일시정지หยุดเพลงชั่วคราวPause
music_stop()停止音乐音楽停止음악정지หยุดเพลงStop and rewind
music_seek(seconds)定位音乐音楽シーク음악탐색ค้นหาเพลงJump to a position
music_pos()音乐位置音楽位置음악위치ตำแหน่งเพลงPlayback position
music_volume(level)音乐音量音楽音量음악음량ระดับเพลงMusic-engine volume
music_patch(path)乐器音色音色読込악기패치แพตช์เครื่องดนตรีLoad an instrument patch
music_note(inst, pitch, duration, velocity)弹音符音符演奏음표연주เล่นโน้ตPlay a note
music_note_on(inst, pitch, velocity)音符开始音符オン음표켜기โน้ตเริ่มPress and hold a key
music_note_off(inst, pitch)音符结束音符オフ음표끄기โน้ตจบRelease a key
music_hz(pitch)音符频率音符周波数음표주파수ความถี่โน้ตPitch to frequency
music_note_name(hz)音名音名称음이름ชื่อโน้ตFrequency to note name
music_pitch_score(sung_hz, target_hz)音准评分音程スコア음정점수คะแนนเสียงScore a sung pitch
music_mic_pitch()麦克风音高マイク音程마이크음정ระดับเสียงไมค์Pitch heard on the microphone
music_judge(delta_ms)判定判定する판정ตัดสินจังหวะGrade a rhythm-game hit
music_grade_name(index)判定名判定名称판정이름ชื่อการตัดสินName of a grade
music_lrc(path)载入歌词歌詞読込가사로드โหลดเนื้อเพลงLoad .lrc lyrics
music_lyric(lyrics, time)当前歌词現在歌詞현재가사เนื้อเพลงปัจจุบันLyric line at a time
music_midi_load(path)载入MIDIMIDI読込미디로드โหลดมิดีLoad a MIDI file
music_midi_count(midi)MIDI数量MIDI数미디수จำนวนมิดีNumber of notes
music_midi_notes(midi)MIDI音符MIDIノート미디음표โน้ตมิดีNote onsets [time, key, ...]
music_midi_bars(midi)MIDI音条MIDIバー미디바แท่งมิดีNotes with lengths [time, key, length, ...]

The daw_* builtins have no localized names.

Notes and frequencies

music_hz(pitch) converts a MIDI number or note name to Hz; A4 (69) is 440. An unreadable name counts as 69. music_note_name(hz) gives the nearest note with sharp spelling, or an empty string if hz is not positive. Octaves follow the scientific convention, where C4 is MIDI 60.

bind start = do {
    print(music_hz("A4"))
    print(round(music_hz(60) * 100) / 100)
    print(round(music_hz("C5") * 100) / 100)
    print(music_note_name(440.0))
    print(music_note_name(262.0))
    print(music_note_name(466.2))
}
440
261.63
523.25
A4
C4
A#4

There are no scale builtins, but a scale is just a list of semitone steps. This prints a C major pentatonic scale:

bind start = do {
    bind steps = [0, 2, 4, 7, 9]
    bind out = []
    bind i = 0
    while i < len(steps) {
        bind out = out.push(music_note_name(music_hz(60 + steps[i])))
        bind i = i + 1
    }
    print(out)
}
[C4, D4, E4, G4, A4]

Loading and analysis

BuiltinReturns
music_load(path)A track handle, or -1. Accepts WAV, FLAC, OGG (Vorbis), MP3 and AAC/M4A. The whole file is decoded into memory.
music_duration(track)Length in seconds.
music_bpm(track)Tempo estimate, rounded to 0.1 and folded into 70 to 170 BPM. It can be off by an octave on some material.
music_key(track)A string such as "A minor" or "C major" (major and minor only).
music_onsets(track)A list of times (seconds) where notes or hits begin.
music_beat_grid(track)A regular grid of beat times at the detected tempo, starting at the first onset. It does not follow tempo changes.
music_fft(track, bands)bands log-spaced, smoothed magnitudes (default 16), bass first, from a 2048-sample window at the current playback position. Silent until music_play has started.
music_fft_groups(track, size, groups)groups loudness values (default 7) between 30 Hz and 16 kHz from one FFT of size samples (default 8192). A full-scale sine reads about 0.5; quiet passages stay quiet.

This example needs no files: it renders a two-bar kick-drum loop with the DAW (see below), then analyses it.

bind start = do {
    daw_new()
    daw_set_bpm(120)
    bind drums = daw_track_add("drums")
    bind clip = daw_clip_add_midi(drums, 0, 8)
    bind beat = 0
    while beat < 16 {
        daw_note_add(drums, clip, beat * 0.5, 0.25, 36, 0.9)
        bind beat = beat + 1
    }
    daw_bounce("loop.wav", 0, 8, 0.0, 16, "wav", 0.5)

    bind track = music_load("loop.wav")
    print("seconds: " + str(round(music_duration(track))))
    print("bpm: " + str(round(music_bpm(track))))
    print("onsets: " + str(len(music_onsets(track))))
    print("beats in grid: " + str(len(music_beat_grid(track))))
    print(music_load("missing.wav"))
}
seconds: 4
bpm: 120
onsets: 15
beats in grid: 8
-1

Playback

The music engine opens its own output stream on first use, separate from the Audio engine, and plays one track at a time.

  • music_play(track) makes track current and starts it from the beginning; calling it again restarts. Playback stops at the end (no loop).
  • music_pause() pauses and keeps the position. To resume, call music_play(-1): an id that is not a loaded track continues the current one.
  • music_stop() stops and rewinds. music_seek(seconds) jumps. music_pos() returns the position in seconds.
  • music_volume(level) sets the volume of the music engine, tracks and synthesiser together (default 0.8, clamped to 0..2). Output is soft-clipped, so levels above 1 distort gently.
bind start = do {
    open_window(640, 360, "Visualizer")
    bind song = music_load("song.ogg")
    music_volume(0.8)
    music_play(song)
    while window_is_open() {
        fill(10, 10, 20)
        bind bars = music_fft(song, 16)
        bind i = 0
        while i < 16 {
            bind h = min(300, bars[i] * 40)
            set_color(80 + i * 10, 200, 255)
            draw_line(30 + i * 38, 340, 30 + i * 38, 340 - h)
            bind i = i + 1
        }
        present()
    }
}

Synthesis

The music engine includes a polyphonic FM/subtractive synthesiser. An instrument is a patch file: plain key=value tokens, with # starting a comment. Operators are numbered from 1, and an operator can frequency-modulate another with opN.fm.

name = "Rhodes EP"
poly = 16
op1.wave=sine  op1.ratio=1.0  op1.level=1.0  op1.adsr=0.002,1.2,0.0,0.4
op2.wave=sine  op2.ratio=14.0 op2.level=0.5  op2.fm=op1  op2.adsr=0.001,0.2,0.0,0.2
filter.cutoff=0.8 filter.reso=0.2 filter.env=0.3 filter.adsr=0,0.5,0.2,0.3
lfo.rate=5.0 lfo.pitch=0.05
amp = 0.7

Keys: name, gm (General MIDI program), poly (voices, default 16), amp, lfo.rate, lfo.pitch, lfo.cutoff, lfo.amp, filter.cutoff, filter.reso, filter.env, filter.adsr, filter.on, and per operator opN.wave (sine, saw, square/pulse, tri, noise), opN.ratio, opN.fixed (Hz), opN.level, opN.detune, opN.adsr (attack, decay, sustain, release) and opN.fm. Unknown keys are ignored. Ready-made patches ship in the repository’s instruments/ folder.

  • music_patch(path) loads a patch and returns an instrument handle (separate from track handles), or -1.
  • music_note(inst, pitch, duration, velocity) plays a note held for duration seconds (default 0.5) at velocity 0 to 1 (default 0.9); the patch’s release follows.
  • music_note_on(inst, pitch, velocity) presses a key; music_note_off(inst, pitch) releases it. Pair them.
bind start = do {
    bind piano = music_patch("instruments/grand_piano.ling")
    music_note(piano, "C4", 0.5, 0.9)
    music_note(piano, "E4", 0.5, 0.8)
    music_note_on(piano, 55, 0.7)
    sleep(1000)
    music_note_off(piano, 55)
}

Singing and rhythm games

music_mic_pitch() returns the fundamental frequency heard on the microphone (55 to 1000 Hz), or 0 if the microphone is closed, the signal is too quiet or no clear pitch is found. Open the microphone with mic_open() first.

music_pitch_score(sung_hz, target_hz) scores a sung pitch from 0 to 1: 1 is exactly on pitch, 0 is a semitone or more off. The error is folded to the nearest octave, so singing an octave away still scores well.

music_judge(delta_ms) grades a hit by its timing error in milliseconds (the sign is ignored): 0 Perfect (up to 30 ms), 1 Great (60), 2 Good (100), 3 Ok (140), 4 Miss. music_grade_name(index) returns "PERFECT", "GREAT", "GOOD", "OK" or "MISS".

bind start = do {
    print(music_pitch_score(440.0, 440.0))
    print(round(music_pitch_score(450.0, 440.0) * 100) / 100)
    print(music_judge(12.0))
    print(music_grade_name(music_judge(-45.0)))
    print(music_grade_name(music_judge(500.0)))
}
1
0.61
0
GREAT
MISS

Lyrics and MIDI files

music_lrc(path) loads a timed-lyrics file whose lines look like [mm:ss.xx] text, and returns a handle. music_lyric(lyrics, time) returns the latest line whose time is not after time (usually music_pos()), or an empty string before the first line.

bind start = do {
    write_file("song.lrc", "[00:01.00] First line\n[00:03.50] Second line\n")
    bind lyrics = music_lrc("song.lrc")
    print("[" + music_lyric(lyrics, 0.5) + "]")
    print(music_lyric(lyrics, 2.0))
    print(music_lyric(lyrics, 99.0))
}
[]
First line
Second line

music_midi_load(path) loads a Standard MIDI File as data; nothing plays. Use the notes to spawn coins, draw falling bars or trigger cues. music_midi_count returns the number of notes, music_midi_notes a flat list [time, key, time, key, ...] and music_midi_bars a flat list [time, key, length, ...], all in seconds.

bind start = do {
    daw_new()
    daw_set_bpm(120)
    bind t = daw_track_add("synth")
    bind c = daw_clip_add_midi(t, 0, 4)
    daw_note_add(t, c, 0, 1, 60, 0.8)
    daw_note_add(t, c, 2, 2, 67, 0.8)
    daw_midi_export_project("song.mid")

    bind m = music_midi_load("song.mid")
    print(music_midi_count(m))
    print(music_midi_notes(m))
    print(music_midi_bars(m))
}
2
[0, 60, 1, 67]
[0, 60, 0.5, 1, 67, 1]

The DAW

The daw_* builtins drive the engine of LingStationX, the digital audio workstation that ships with Ling. Any script can use it, with or without a window: build a project, edit notes, add effects and render audio. The engine is created the first time a daw_* builtin is called.

Things to know:

  • Clip positions, lengths, loop points and render ranges are in beats. daw_secs_at(beat) converts to seconds.
  • Tracks, clips, notes and effects are addressed by zero-based index. Indices shift when you insert or remove items.
  • Yes/no answers come back as 1 and 0. Builtins that create something return its index, or -1.
  • Editing and rendering need no audio device. daw_play() plays in real time when a device exists.
  • daw_status() returns the message left by the last operation.
  • An effect target is a track index, or -1 for the master bus.

The main groups:

GroupBuiltins
Projectdaw_new, daw_project_save(path), daw_project_load(path), daw_set_project_name(name), daw_status
Transport and tempodaw_play, daw_pause, daw_stop, daw_seek(beat), daw_position, daw_bpm, daw_set_bpm(bpm), daw_set_loop(on, start, end), daw_end_beat, daw_tempo_add(beat, bpm), daw_secs_at(beat)
Tracksdaw_track_add(kind, path), daw_track_count, daw_track_remove(track), daw_track_name(track), daw_track_set_name(track, name), daw_track_get(track, field), daw_track_set(track, field, value)
Clips and notesdaw_clip_add_midi(track, start, length), daw_clip_add_audio(track, path, start), daw_clip_notes(track, clip), daw_note_add(track, clip, start, length, key, velocity), daw_note_remove(track, clip, note)
Instrumentsdaw_inst_presets(track), daw_inst_preset(track, name), daw_inst_params(track), daw_inst_set(track, name, value)
Effectsdaw_fx_types, daw_fx_add(target, name), daw_fx_params(target, index), daw_fx_set(target, index, param, value), daw_fx_set_wet(target, index, wet), daw_fx_bypass(target, index, on)
Rendering and undodaw_bounce(path, start, end, tail, bits, format, quality), daw_render_start(...), daw_undo_push, daw_undo, daw_redo
MIDIdaw_midi_import(path, beat), daw_midi_export(track, path), daw_midi_export_project(path), daw_midi_inputs, daw_midi_open(index)

Track kinds for daw_track_add are "synth", "drums", "audio", "sf2" (with a SoundFont path), "growl", "voice", "prism", "sampler", "pluck", "chip", "cinema" and "script". The engine has several hundred more daw_* builtins for automation, vocals, song generation, mixing and export; they mostly serve the LingStationX application itself.

A complete offline session:

bind start = do {
    daw_new()
    daw_set_project_name("Demo")
    daw_set_bpm(100)

    bind lead = daw_track_add("synth")
    daw_inst_preset(lead, "FM Bell")
    bind clip = daw_clip_add_midi(lead, 0, 4)
    bind pitches = [60, 64, 67, 72]
    bind i = 0
    while i < 4 {
        daw_note_add(lead, clip, i, 0.75, pitches[i], 0.8)
        bind i = i + 1
    }

    bind verb = daw_fx_add(lead, "Reverb")
    daw_fx_set_wet(lead, verb, 0.3)

    print("tracks: " + str(daw_track_count()))
    print("project ends at beat " + str(daw_end_beat()))
    print("render ok: " + str(daw_bounce("demo.wav", 0, 4, 1.0, 16, "wav", 0.5)))
}
tracks: 1
project ends at beat 4
render ok: 1

Physics

Ling ships a small physics engine, the ling-physics crate, and drives it from script. You get three independent simulations: soft bodies that squash and stretch, a rigid-body world with spin and torque, and a fast 2D liquid of water and oil that you can wrap onto 3D shapes. On top of that, coll_* turns a mesh into a static collision shape for spheres and rays, and the glTF loader that the animation builtins use lives in the same crate.

All simulation builtins run without a window, so you can test physics headless and print the numbers. Only the *_draw* builtins need an open window.

Conventions:

  • Handles are integers counting from 0 in creation order. An unknown handle does nothing and returns 0, an empty list or nothing. It never raises an error.
  • Defaults. An omitted argument takes the default given in its entry.
  • Names. soft_*, rb_* and liquid_* have names in all five languages. coll_* and gltf_* are English only.

Which way is up

Two coordinate conventions meet here, and mixing them up is the usual cause of “my body falls through the floor”.

  • The renderer is y-down: positive y points to the bottom of the screen. Soft bodies follow it. A floor is the largest y a body may reach, and gravity is a positive number.
  • The rigid-body world is y-up: its default gravity is (0, -9.81, 0), and rb_floor catches a body that is above the floor and falling toward negative y.

Keep rigid bodies y-up and flip y when you draw them. If you set a positive rb_gravity to match the screen, rb_floor stops working.

Summary

Builtin中文日本語한국어ไทยPurpose
soft_ball(x, y, z, r)软球ソフトボール소프트볼ลูกบอลนุ่มCreate a deformable ball.
soft_step(id, dt, gravity)软体步进ソフト更新소프트스텝ก้าวนุ่มAdvance one soft body.
soft_bounce(id, floor_y, restitution)软体落地ソフト着地소프트바운스เด้งนุ่มCollide with a horizontal floor.
soft_contain(id, x0, y0, z0, x1, y1, z1, restitution)软体边界ソフト箱소프트경계กล่องนุ่มKeep the body inside a box.
soft_kick(id, dx, dy, dz, strength)软体踢ソフト衝撃소프트킥เตะนุ่มPush the whole body.
soft_spin(id, ax, ay, az, rate)软体自旋ソフト回転소프트회전หมุนนุ่มSpin about an axis through the centre.
soft_deform(id)形变量変形量변형량ความบิดเบี้ยวHow squashed it is, 0 to 1.
soft_angular_speed(id)软体角速ソフト角速度소프트각속도ความเร็วเชิงมุมนุ่มTumbling speed.
soft_centroid(id)软体质心ソフト重心소프트중심จุดศูนย์กลางนุ่มCentre of mass [x, y, z].
soft_nodes(id)软体节点ソフト節点소프트노드จุดนุ่มEvery node as a flat list.
rb_add(x, y, z, mass)刚体添加剛体追加강체추가เพิ่มวัตถุแข็งAdd a rigid body.
rb_gravity(gx, gy, gz)刚体重力剛体重力강체중력แรงโน้มถ่วงแข็งSet world gravity.
rb_step(dt)刚体步进剛体更新강체스텝ก้าวแข็งStep the whole world.
rb_floor(i, floor_y, restitution, friction)刚体落地剛体着地강체바닥พื้นแข็งBounce a body off a floor.
rb_impulse(i, ix, iy, iz)刚体冲量剛体インパルス강체충격แรงดลแข็งApply a linear impulse.
rb_torque(i, tx, ty, tz)扭矩トルク토크แรงบิดApply torque for the next step.
rb_spin(i, wx, wy, wz)自旋スピン스핀หมุนAdd angular velocity.
rb_pos(i)刚体位置剛体位置강체위치ตำแหน่งแข็งPosition [x, y, z].
rb_rot(i)刚体旋转剛体回転강체회전การหมุนแข็งOrientation quaternion [x, y, z, w].
liquid_new(w, h)新建液体液体新規액체생성สร้างของเหลวCreate a fluid grid.
liquid_splat(id, x, y, kind, amount, radius)液体注入液体追加액체분사หยดของเหลวAdd water or oil in a disc.
liquid_gravity(id, gx, gy)液体重力液体重力ベクトル액체중력แรงโน้มถ่วงเหลวSet the grid’s gravity.
liquid_step(id, dt)液体步进液体更新액체스텝ก้าวของเหลวAdvance one grid.
liquid_step_all(dt)液体全步进液体全更新전체액체스텝ก้าวของเหลวทั้งหมดAdvance every grid in parallel.
liquid_mix(id)液体混合液体混合度액체혼합การผสมของเหลวHow mixed the liquids are, 0 to 1.
liquid_set_colors(id, wr, wg, wb, or, og, ob)液体颜色液体配色액체색상สีของเหลวWater and oil colours.
liquid_rainbow(id, on)液体彩虹液体虹액체무지개ของเหลวสายรุ้งRainbow marble colouring.
liquid_draw(id, x, y, scale)绘制液体液体描画액체그리기วาดของเหลวBlit the grid in 2D.
liquid_draw_surface(id, kind, cx, cy, cz, radius, height)液体贴面液体曲面액체곡면ของเหลวบนพื้นผิวWrap the grid onto a 3D surface.
coll_build(mesh, group, x, y, z, scale, rot, cell)————Build a collision shape from a mesh.
coll_tris(id)————Triangle count of a shape.
coll_sphere(id, x, y, z, radius)————Push a sphere out of a shape.
coll_ray(id, ox, oy, oz, dx, dy, dz, max_t)————Cast a ray against a shape.
gltf_load(path)————Load a .glb/.gltf model.
gltf_tris(h)————Triangle count of a model.
gltf_bounds(h, clip, time)————Bounding box of a posed model.

Soft bodies

A soft body is a spring-mass sphere of 86 nodes. It squashes on impact and springs back. Soft bodies are independent: they don’t collide with each other or with the rigid world.

soft_ball(x, y, z, r)

Creates a ball centred at (x, y, z) (default 0) with radius r (default 1.0). Returns its id.

soft_step(id, dt, gravity)

Advances the body by dt seconds (default 0.016) under gravity along +y (default 15.0; positive pulls toward the bottom of the screen). Each call runs four internal sub-steps. Call it once per frame.

soft_bounce(id, floor_y, restitution) and soft_contain(...)

soft_bounce collides the body with the floor plane floor_y (default 0). In y-down terms the body lives at y <= floor_y. restitution (default 0.5, limited to 0..0.99) is the bounciness. A slow contact settles instead of bouncing, so a resting ball doesn’t creep.

soft_contain(id, min_x, min_y, min_z, max_x, max_y, max_z, restitution) keeps the body inside a box (default -5 to 5 on every axis, restitution 0.6) and squashes it against every wall.

bind start = do {
  bind ball = soft_ball(0.0, 0.0 - 3.0, 0.0, 1.0)
  print(len(soft_nodes(ball)) / 3)
  bind frame = 0
  while frame < 300 {
    soft_step(ball, 0.016, 9.8)
    soft_bounce(ball, 2.0, 0.5)
    bind frame = frame + 1
  }
  bind c = soft_centroid(ball)
  print("rests at y = " + str(round(c[1] * 100) / 100))
}
86
rests at y = 1.09

The ball has radius 1 and the floor is at y = 2. A rigid ball would rest at 1.0; this one rests at 1.09 because its weight squashes it slightly.

soft_kick(id, dx, dy, dz, strength) and soft_spin(id, ax, ay, az, rate)

soft_kick adds strength (default 0.1) of speed along the direction (dx, dy, dz), which is normalised. A zero vector does nothing. soft_spin adds angular velocity about an axis through the centroid. rate (default 0.1) is radians per step. To roll without slipping, use surface speed divided by radius.

Reading a soft body

  • soft_deform(id): 0 for a perfect sphere, rising toward 1 when squished.
  • soft_angular_speed(id): size of the angular velocity.
  • soft_centroid(id): [x, y, z], or [0, 0, 0] for an unknown id.
  • soft_nodes(id): [x, y, z, x, y, z, ...] for all 86 nodes. Draw these points or a mesh through them to show the deformed surface.

Rigid bodies

One shared world of unit cubes (half-size 0.5) with linear and angular motion. Bodies collide with each other, and rb_floor gives them a floor. Friction on the floor turns sliding into rolling, so boxes tumble.

rb_add(x, y, z, mass)

Adds a body at (x, y, z) with mass (default 1.0) and returns its index. New bodies have a restitution of 0.6.

rb_gravity(gx, gy, gz)

Sets gravity for the whole world. Mind the sign: before any call, gravity is (0, -9.81, 0), but an omitted gy in this call becomes +9.81. Pass all three values.

rb_step(dt)

Advances every body by dt seconds (default 0.016), including rotation, and resolves body-to-body collisions.

rb_floor(i, floor_y, restitution, friction)

Bounces body i off the floor at floor_y (default 0). restitution and friction both default to 0.6. Call it every frame, after rb_step, for each body that can hit the floor. It acts only when the body’s lower face is below floor_y and it’s moving toward negative y.

bind start = do {
  bind box = rb_add(0.0, 5.0, 0.0, 1.0)
  rb_impulse(box, 2.0, 0.0, 0.0)
  bind frame = 0
  while frame < 240 {
    rb_step(0.016)
    rb_floor(box, 0.0, 0.5, 0.6)
    bind frame = frame + 1
  }
  bind p = rb_pos(box)
  print("x = " + str(round(p[0] * 100) / 100))
  print("y = " + str(round(p[1] * 100) / 100))
}
x = 4.5
y = 0.5

The box falls from y = 5 and comes to rest with its centre at 0.5, sitting on the floor, after sliding 4.5 units.

Forces and state

  • rb_impulse(i, ix, iy, iz): an instant change of velocity times mass.
  • rb_torque(i, tx, ty, tz): a torque about the world axes, applied on the next step.
  • rb_spin(i, wx, wy, wz): add radians per second of angular velocity.
  • rb_pos(i): [x, y, z].
  • rb_rot(i): a quaternion [x, y, z, w]. [0, 0, 0, 1] is no rotation. Rotate your mesh by it to draw a tumbling body.

Liquid

A fast 2D grid with two liquids that don’t mix, water and oil, moved by one incompressible velocity field. They blend only where they meet, so the physics decides where the colours swirl. The grid wraps at its edges, which makes it seamless on a sphere or cylinder.

liquid_new(w, h)

Creates a grid of w by h cells (default 64, at least 2) and returns its id.

liquid_splat(id, x, y, kind, amount, radius)

Adds liquid in a disc centred at cell (x, y). kind is 0 for water or 1 for oil, amount defaults to 1.0 and radius to 4.0 cells.

liquid_gravity(id, gx, gy)

Sets the gravity vector of one grid (default (0, 60)). Rotate it over time to make the liquids slosh.

liquid_step(id, dt) and liquid_step_all(dt)

liquid_step advances one grid by dt (default 0.016). Grids share no state, so liquid_step_all advances every grid at once, spread across all CPU cores. Use it when a scene has many liquid surfaces.

liquid_mix(id)

How intermixed the two liquids are: 0 fully separated, up to 1 fully mixed.

bind start = do {
  bind pool = liquid_new(16, 16)
  liquid_splat(pool, 8.0, 4.0, 1, 1.0, 3.0)
  liquid_splat(pool, 8.0, 12.0, 0, 1.0, 3.0)
  print(liquid_mix(pool))
  bind frame = 0
  while frame < 50 {
    liquid_step(pool, 0.016)
    bind frame = frame + 1
  }
  print(round(liquid_mix(pool) * 1000) / 1000)
}
0
0.138

Colours and drawing

  • liquid_set_colors(id, wr, wg, wb, or, og, ob): water and oil colours, 0 to 255 (defaults blue 40, 110, 235 and amber 240, 175, 45).
  • liquid_rainbow(id, on): colour the fluid as a flowing seven-colour marble (on above 0.5 turns it on).
  • liquid_draw(id, x, y, scale): copy the grid to the window at pixel (x, y), scale pixels per cell (default 4). It writes straight into the frame and ignores 3D depth.
  • liquid_draw_surface(id, kind, cx, cy, cz, radius, height): wrap the grid onto a 3D surface centred at (cx, cy, cz). kind is 0 plane, 1 sphere (default), 2 cylinder, 3 cone or 4 dome.
bind start = do {
  open_window(640, 480)
  bind pool = liquid_new(84, 84)
  liquid_splat(pool, 42.0, 25.0, 1, 1.0, 3.0)
  liquid_splat(pool, 42.0, 58.0, 0, 1.0, 3.0)
  while window_is_open() {
    bind t = time_now()
    liquid_gravity(pool, sin(t) * 55.0, cos(t) * 55.0)
    liquid_step(pool, 0.016)
    fill(0, 0, 0)
    set_camera(cos(t * 0.3), sin(t * 0.3), cos(0.4), sin(0.4))
    liquid_draw_surface(pool, 1, 0.0, 0.0, 0.0, 2.2, 3.2)
    present()
  }
}

Collision shapes

coll_* turns a loaded mesh into a static triangle soup in a uniform grid, then tests spheres and rays against it. Use it for level geometry: walls, floors, ramps.

coll_build(mesh, group, x, y, z, scale, rot, cell)

Builds a shape from a tm_load mesh. group is one group or -1 for all. (x, y, z), scale and rot (a yaw in radians or a row-major 3x3 matrix) place it in the world. cell (default 8) is the lookup grid size. Returns the shape id, or -1 for an unknown mesh. The shape is static, so build it once with its final transform.

coll_sphere(id, x, y, z, radius)

Pushes a sphere out of the shape, with up to four passes. Returns [x, y, z, nx, ny, nz, contacts, deepest]: the corrected centre, the summed contact normal (zeros if nothing touched), the number of contacts and the deepest penetration. Feed the corrected centre back into your player position.

coll_ray(id, ox, oy, oz, dx, dy, dz, max_t)

Casts a ray from (ox, oy, oz) along (dx, dy, dz) (normalised) up to max_t (default 1000). Returns [t, nx, ny, nz], the distance and the surface normal, or [-1, 0, 0, 0] for no hit. coll_tris(id) returns the triangle count.

bind start = do {
  file_write_hex("floor.ltm", "4c544d310100000005666c6f6f7204000000020000000000a0c0000000000000a0c0000000000000000000000000000080bf000000000000a040000000000000a0c00000803f0000000000000000000080bf000000000000a040000000000000a0400000803f0000803f00000000000080bf000000000000a0c0000000000000a040000000000000803f00000000000080bf00000000000000000100000002000000000000000200000003000000")
  bind mesh = tm_load("floor.ltm")
  bind floor = coll_build(mesh, -1, 0.0, 0.0, 0.0, 1.0, 0.0, 8.0)
  print("triangles: " + str(coll_tris(floor)))
  print(coll_ray(floor, 0.0, -3.0, 0.0, 0.0, 1.0, 0.0, 10.0))
  print(coll_ray(floor, 0.0, -3.0, 0.0, 0.0, 1.0, 0.0, 1.0))
}
triangles: 2
[3, 0, -1, 0]
[-1, 0, 0, 0]

The hex string is a tiny two-triangle floor in Ling’s .ltm mesh format. The first ray hits it 3 units away; the second stops after 1 unit and misses.

glTF models

The glTF loader is part of ling-physics too. gltf_load(path) reads a .glb or .gltf file (meshes, skeleton, skin and animation clips) and returns a handle, or -1 on failure with the reason on standard error.

  • gltf_tris(h): total triangle count, a quick performance check.
  • gltf_bounds(h, clip, time): [min_x, min_y, min_z, max_x, max_y, max_z] of the model as drawn with that animation clip (default 0) at that time (default 0), in glTF space (y-up, unscaled). All zeros for a bad handle. Use it to stand a model on the ground or size a collision sphere.
bind start = do {
  bind model = gltf_load("missing.glb")
  print(model)
  print(gltf_tris(model))
  print(gltf_bounds(model))
}
-1
0
[0, 0, 0, 0, 0, 0]

Drawing, posing and playing clips are covered in Animation.

See also

Acoustic Bodies

The body_* builtins expose ling-body, a toolkit that grows a humanoid skin from sound. A body scaffold (a parametric T-pose figure, or an imported model) is voxelised into a signed distance field. Acoustic sources placed on the body excite a pressure wave inside and around it. A thin elastic membrane responds to the wave, and its surface is extracted as a watertight triangle mesh.

The recipe round-trips through WAV files: an exported WAV plays as sound and also carries the parameters and the mesh, so it loads back as the same body. Any other audio file can be analysed into source parameters.

Things to know:

  • There is one toolkit per program; every body_* call works on it.
  • Operations that can fail return 1 for success and 0 for failure, and leave a message you read with body_message().
  • Values cross the boundary as numbers, strings and flat lists.
  • Units are metres. The mesh is Y-up, the figure faces +Z and its left side is +X.
  • Everything except body_draw and body_draw_creases runs without a window.
  • These builtins have no localized names.

A first body

Set a few parameters, add a source, run the simulation in slices, then read and export the mesh:

bind start = do {
    body_param_set("sr", 8000)
    body_param_set("steps", 60)
    body_param_set("seal", 1)
    body_src_add(0.0, 1.0, 0.0, 0, 220)
    print("steps: " + str(body_sim_begin()))

    bind progress = [0, 1]
    while progress[0] < progress[1] {
        bind progress = body_sim_step(40)
    }
    print("done: " + str(body_sim_done()))
    print("mesh: " + str(body_mesh_update()) + " " + body_message())
    bind counts = body_mesh_counts()
    print("watertight: " + str(counts[2]))
    print(body_grid_info())
    print("exported: " + str(body_export_mesh("body.obj")) + " " + body_message())
}
steps: 60
done: 1
mesh: 1 mesh updated
watertight: 1
109x107x75 @ 41.3 mm
exported: 1 10008 triangles → body.obj

Summary

BuiltinPurpose
body_message()Message from the last operation
body_grid_info()Grid size and spacing, such as "109x107x75 @ 41.3 mm"
body_notes()Notes from the last listening pass or WAV analysis
body_param_get(name) / body_param_set(name, v)Read or set a parameter
body_param_reset()Restore all parameters and remove all sources
body_param_count(), body_param_name(i), body_param_group(i)List the parameters
body_param_min(i), body_param_max(i), body_param_default(i)A parameter’s range and default
body_src_add(x, y, z, wave, freq)Add a source at a position
body_src_at_joint(joint, wave, freq)Add a source at a scaffold joint
body_src_count(), body_src_name(i), body_src_del(i), body_src_clear()Manage sources
body_src_get(i, field) / body_src_set(i, field, v)Read or change a source field
body_joint_count(), body_joint_name(i), body_joint_pos(i), body_joint_parent(i)The scaffold’s joints
body_model_load(path), body_model_use(h), body_model_active()Use an imported model as the body
body_model_part_count(h), body_model_part_name(h, i), body_model_part_tris(h, i)Inspect model parts
body_model_part_enabled(h, i), body_model_part_set(h, i, on)Include or exclude a part
body_preview()Voxelise and show the rest shape without simulating
body_sim_begin(), body_sim_step(ms)Start and advance the simulation
body_sim_active(), body_sim_done()Simulation state
body_mesh_update()Extract the membrane as the working mesh
body_displacement(), body_slice(axis, frac), body_mic_tail(n)Inspect the simulation
body_mesh_counts(), body_mesh_bounds()Mesh statistics
body_mesh_positions(), body_mesh_normals(), body_mesh_indices()Raw mesh data
body_crease_detect(), body_crease_apply(), body_detail_reset()Carve creases from the sound field
body_crease_count(), body_crease_segments(), body_crease_clear(), body_crease_export(path)Work with crease curves
body_listen_begin(), body_listen_step(ms), body_listen_done(), body_listen_finish(path)Record the body’s acoustic signature
body_listen_spectrum()48 log-spaced bands of the signature
body_export_mesh(path), body_export_wav(path), body_import_wav(path, analyze_only)Files
body_project_save(path), body_project_load(path)Save and load the recipe as JSON
body_draw(mode, yaw, x, y, z, scale, extra), body_draw_creases(yaw, x, y, z, scale)Draw into the window

Parameters

Parameters are a fixed table of 47 named numbers. Each has a group, a default and a range, and setting a value clamps it to the range. body_param_set returns 1 for a known name and 0 otherwise. The listing builtins take an index from 0 to 46 or a name.

GroupNames (defaults)Meaning
bodyheight (1.7), build (1), arm_span (1), head_scale (1)Scaffold proportions; height also scales imported models
bodyseal (3)Voxel radius used to close openings in imported models
simsr (22050), steps (800), margin (16), up (2)Sample rate, time steps, air margin in cells, membrane grid refinement
mediumc_air (343), c_body (1), rho_body (4), damping (0.002), sponge (8)Sound speed, body speed and density ratios, loss, absorbing layer
micmic_sep (0.18), mic_dist (0.15)Ear spacing and distance in front of the face
membranerelief, coupling, threshold, tension, stiffness, mem_time, mem_every, reinit_every, band, drive_mode, drive_tauHow the skin follows the wave
meshsmooth (3), decimate (0), iso (0)Smoothing passes, vertex-merge cell size in metres, surface level offset
audiowav_bits (16), wav_gain (0.9), wav_repeat (4), wav_gap (0.25)WAV export
detailcrease_mode, crease_levels, crease_tol, crease_min, detail_level, crease_depth, crease_width, noise_amp, noise_freqCrease detection and carving
listensig_dur, sig_sr, sig_rho, sig_exciteThe listening pass
bind start = do {
    print(body_param_count())
    print(body_param_get("height"))
    print(body_param_set("height", 5))
    print(body_param_get("height"))
    print(body_param_set("nope", 1))
    print(body_joint_count())
    print(body_joint_name(4))
}
47
1.7
1
2.4
0
21
head

height only goes up to 2.4, so setting 5 stores 2.4.

Sources and joints

A source is an excitation in space. Its fields are x, y, z (metres), wave (0 Ricker wavelet, 1 sine burst, 2 impulse), freq (Hz), amp, phase, start and dur (seconds).

  • body_src_add(x, y, z, wave, freq) adds one (defaults 0, 1, 0, wave 0, 220 Hz) and returns its index.
  • body_src_at_joint(joint, wave, freq) adds one at a named joint and names the source after it. It returns -1 for an unknown joint.

The scaffold has 21 joints: hips, spine, chest, neck, head, and l_ / r_ versions of shoulder, elbow, wrist, hand, hip, knee, ankle and toe. body_joint_pos(i) returns [x, y, z], fitted to the current body size, and body_joint_parent(i) returns the parent index (-1 for the root).

Imported models

body_model_load(path) loads a .glb, .gltf, .lmesh or .obj file and returns a handle (or -1). Loading does not select it: call body_model_use(h), or pass a negative handle to go back to the scaffold. glTF files are read for geometry and node transforms only, so files that need texture extensions still load. Accessory parts such as flowers and cubes start disabled; switch parts with body_model_part_set(h, i, on).

Simulation

The simulation runs in time-boxed slices so a window can keep updating.

  • body_preview() voxelises the body and extracts its undisturbed shape without simulating.
  • body_sim_begin() starts a simulation and returns the total number of steps, or -1.
  • body_sim_step(ms) works for about ms milliseconds (default 30) and returns [steps_done, total].
  • body_mesh_update() extracts the membrane as it is now. You can call it while the simulation runs to watch the skin grow.
  • body_displacement() returns [inward_mm, outward_mm]. body_slice(axis, frac) returns [w, h, v0, v1, ...], a slice of the pressure field normalised to -1..1. body_mic_tail(n) returns the last n samples of the first microphone.

Creases and detail

After a finished simulation, body_crease_detect() samples the sound field on the mesh, traces its contour lines and fits them with cubic Bézier curves. body_crease_apply() subdivides the mesh and carves a soft groove along every curve, plus fine noise weighted by the field. body_detail_reset() restores the smooth mesh. body_crease_export(path) writes the curves as .json, or as a .py Blender script that builds curve objects.

Listening

body_listen_begin() fires an impulse in front of the mouth and records two microphones beside the head. Call body_listen_step(ms) until it finishes (it returns [done, total]), then body_listen_finish(path) writes a WAV of the body’s sound and fills body_listen_spectrum() and body_notes() (the strongest resonances).

Files

  • body_export_mesh(path) writes OBJ, STL or GLB, chosen by extension. The GLB carries the T-pose skeleton and skin weights.
  • body_export_wav(path) writes the stereo microphone signal with two extra chunks holding the full recipe and the compressed mesh.
  • body_import_wav(path, analyze_only) restores both chunks when present. With analyze_only set to 1, or when the chunks are missing, it estimates sources from the audio instead, and body_notes() explains each estimate. WAV, FLAC, Ogg and MP3 are accepted.
  • body_project_save(path) and body_project_load(path) keep the parameters, sources and chosen body as JSON.

Drawing

body_draw(mode, yaw, x, y, z, scale, extra) draws the working mesh with the pen colour, flipped into the renderer’s y-down space. Modes:

ModeLook
0Solid, smoothed normals
1Wireframe of every extra-th triangle
2Tinted by skin displacement; extra is the full-scale push in millimetres (default 10)
3Coloured by surface normal
4Single-light clay shading

Modes 3 and 4 make fine relief easy to judge. body_draw_creases(yaw, x, y, z, scale) draws the detected crease curves on top.

This window grows a body while you watch:

bind start = do {
    open_window(640, 480, "Body")
    body_param_set("steps", 400)
    body_src_at_joint("chest", 1, 180)
    body_sim_begin()
    bind yaw = 0.0
    while window_is_open() {
        if body_sim_done() == 0 {
            body_sim_step(20)
            body_mesh_update()
        }
        fill(16, 16, 24)
        set_color(220, 200, 180)
        body_draw(2, yaw, 0, 1, 4, 1, 10)
        flush_3d()
        present()
        bind yaw = yaw + 0.01
    }
}

See also: Physics, Music.

Input and Microphone

Ling reads input by polling: once per frame, inside your loop, you ask what the player is doing right now. There are no callbacks. This page covers the keyboard and mouse, typed text, game controllers (through the gilrs library and the ling-input crate) and the microphone (the ling-mic crate).

Every input builtin is safe to call when the device is missing: keys and buttons read as not pressed, axes as 0, and the microphone as silence. A game can therefore fall back to the keyboard without special cases. To find out whether hardware is present, check the return value of mic_open or pad_poll.

Keyboard, mouse and text input need an open window to receive events. Without one, they simply read as idle:

bind start = do {
  print(key_down("space"))
  print(key_pressed("enter"))
  print(mouse_down())
  print(mouse_scroll())
  print(mic_rms())
  print(mic_fft(4))
}
false
false
false
0
0
[0, 0, 0, 0]

Summary

Builtin中文日本語한국어ไทยPurpose
key_down(name)按键キー押す키누름กดค้างTrue while a key is held.
key_pressed(name)键按キー押した키눌림กดปุ่มTrue only on the frame a key went down.
mouse_x(), mouse_y()————Cursor position in pixels.
mouse_down()————Left button held.
mouse_down_right()———เมาส์ขวาRight button held.
mouse_down_middle()———เมาส์กลางMiddle button held.
mouse_dx()鼠ΔXマウスΔX마우스ΔXเมาส์XHorizontal movement while captured.
mouse_dy()鼠ΔYマウスΔY마우스ΔYเมาส์YVertical movement while captured.
mouse_scroll()滚轮ホイール스크롤ล้อเมาส์Vertical wheel movement this frame.
mouse_scroll_x()————Horizontal wheel movement this frame.
capture_mouse()捕鼠マウス捕捉마우스잡기จับเมาส์Hide the cursor and switch to relative motion.
release_mouse()————Undo capture_mouse.
cursor_hide(), cursor_show()————Hide or show the pointer only.
text_poll()————Add newly typed characters to the text buffer and return it.
text_get(), text_set(s), text_clear()————Read, replace or empty the text buffer.
pad_poll()手柄轮询パッド更新패드폴링อัปเดตแพดAdvance controller input one frame. Returns the pad count.
pad_count()手柄数パッド数패드수จำนวนแพดConnected pads, as of the last poll.
pad_connected(player)手柄连接パッド接続패드연결แพดเชื่อมWhether a player slot has a pad.
pad_button(player, name)手柄按键パッドボタン패드버튼ปุ่มแพดTrue while a button is held.
pad_pressed(player, name)手柄按下パッド押下패드눌림แพดกดTrue only on the frame a button went down.
pad_lx(player), pad_ly(player)手柄左X, 手柄左Yパッド左X, パッド左Y패드왼X, 패드왼Yแพดซ้ายX, แพดซ้ายYLeft stick, -1 to 1.
pad_rx(player), pad_ry(player)手柄右X, 手柄右Yパッド右X, パッド右Y패드오X, 패드오YแพดขวาX, แพดขวาYRight stick, -1 to 1.
pad_lt(player), pad_rt(player)手柄左扳机, 手柄右扳机パッド左トリガー, パッド右トリガー패드왼트리거, 패드오트리거ไกแพดซ้าย, ไกแพดขวาAnalog triggers, 0 to 1.
pad_rumble(player, low, high)手柄震动パッド振動패드진동แพดสั่นRequest vibration (currently inert).
gamepad_poll()———จอยโพลPump controller events (older family).
gamepad_button(name)———จอยปุ่ม1 while a named button is held.
gamepad_axis(name)———จอยแกนValue of a named axis.
gamepad_rumble(low, high, ms)———จอยสั่นVibrate the current controller.
gamepad_list()———จอยรายการDescribe the controllers the system sees.
gamepad_any()———จอยใดๆ1 if any button is down.
mic_open()开麦克风マイク開く마이크열기เปิดไมค์Open the default microphone.
mic_rms()麦克风音量マイクRMS마이크RMSเสียงRMSLoudness of the latest buffer, 0 to 1.
mic_peak()麦克风峰值マイクピーク마이크피크เสียงพีคPeak level of the latest buffer, 0 to 1.
mic_fft(bands)实时频谱リアルタイムFFT실시간FFTวิเคราะห์เสียงสดSpectrum in bands bands, bass first.
mic_capture()————Append the latest samples to the record buffer.
mic_seed()————SHA3-256 of the recorded audio, as hex.
mic_clear()————Empty the record buffer.

Keyboard

key_down(name) and key_pressed(name)

key_down is true for as long as the key is held: use it for movement. key_pressed is true only on the single frame the key went down, so holding the key doesn’t repeat: use it for toggles, menus and firing once per press.

Both take a lower-case key name. An unknown name is simply false. Both read false while another window has focus. Pressing Start on a game controller also counts as key_pressed("enter"), so menus that wait for Enter work with a pad.

GroupNames
Letters, digits"a" to "z", "0" to "9"
Arrows and navigation"left", "right", "up", "down", "home", "end", "pageup", "pagedown", "insert", "delete"
Editing"space", "enter", "escape", "tab", "backspace", "capslock"
Modifiers"lshift", "rshift", "lctrl", "rctrl", "lalt", "ralt"
Function keys"f1" to "f12"
Number pad"numpad0" to "numpad9" (or "kp0" to "kp9"), "numpad+", "numpad-", "numpad*", "numpad/"
Punctuation"minus", "equals", "comma", "period", "slash", "semicolon", "quote", "lbracket", "rbracket", "backslash", "grave" (the symbols themselves also work)
bind start = do {
  open_window(800, 600)
  bind x = 400
  bind paused = 0
  while window_is_open() {
    if key_pressed("p") { bind paused = 1 - paused }
    if paused == 0 {
      if key_down("left") { bind x = x - 4 }
      if key_down("right") { bind x = x + 4 }
    }
    fill(0, 0, 0)
    set_color(255, 255, 255)
    draw_disc(x, 300, 20)
    present()
  }
}

Typed text

For name entry and chat, let Ling collect characters for you. text_poll() adds the keys typed since the last call to a text buffer (Backspace deletes, and holding a key repeats) and returns the whole buffer. Call it once per frame while the field is active. text_get() reads the buffer without polling, text_set(s) replaces it, and text_clear() empties it.

bind start = do {
  text_set("Ada")
  print(text_get())
  text_clear()
  print("[" + text_get() + "]")
}
Ada
[]

Mouse

  • mouse_x(), mouse_y(): the cursor position inside the window, in pixels. Both are 0 until a window exists.
  • mouse_down(), mouse_down_right(), mouse_down_middle(): true while that button is held. They are level checks: for a click, compare with last frame’s value.
  • mouse_scroll(), mouse_scroll_x(): wheel movement during the last frame, 0 when idle.
  • mouse_dx(), mouse_dy(): how far the mouse moved since the last frame. Positive dx is right, positive dy is down. They are only non-zero while the mouse is captured.
  • capture_mouse() hides the cursor and switches to relative motion, so mouse_dx and mouse_dy keep reporting however far the mouse travels. This is the basis of first-person look. release_mouse() undoes it. Escape still closes the window.
  • cursor_hide(), cursor_show() hide or show only the pointer. The position keeps tracking normally, which suits games that draw their own cursor.
bind start = do {
  open_window(800, 600)
  bind was = false
  while window_is_open() {
    bind now = mouse_down()
    if now && !was {
      print("click at " + str(mouse_x()) + ", " + str(mouse_y()))
    }
    bind was = now
    fill(0, 0, 0)
    present()
  }
}

Game controllers

There are two families. The pad_* family is the one to use: up to four players, edge-detected buttons, analog triggers, and the same code on the desktop and in the browser (where it uses the W3C Gamepad API). The older gamepad_* family reads the most recently used controller by name and is the one that can make a controller vibrate.

The pad_* family

Call pad_poll() once per frame, before reading anything. It drains controller events, advances the edge detection and returns the number of connected pads. Player slots are 0 to 3. The first call opens the controller backend; if that fails, it returns 0 and every read stays neutral.

  • pad_button(player, name): true while the button is held.
  • pad_pressed(player, name): true only on the frame of the press. In a browser build only the current state is known, so it behaves like pad_button there.
  • pad_lx, pad_ly, pad_rx, pad_ry: stick axes, -1 to 1. Pushing a stick up gives a negative y, matching the screen. No dead zone is applied, so ignore small values yourself.
  • pad_lt, pad_rt: analog triggers, 0 (released) to 1 (fully pulled).
  • pad_connected(player), pad_count(): which slots are filled.
  • pad_rumble(player, low, high): currently does nothing on desktop or in the browser. Use gamepad_rumble to vibrate.

Button names are case-insensitive, and several names mean the same button. On the desktop the face buttons are positional: the bottom one is a on every brand.

ButtonNames
bottom facea, south, cross
right faceb, east, circle
left facex, west, square
top facey, north, triangle
shoulderslb, l1, left_shoulder; rb, r1, right_shoulder
triggers (digital)lt, l2, left_trigger; rt, r2, right_trigger
start / selectstart, menu, options; select, back, share, view
guideguide, home
stick clicksl3, left_stick; r3, right_stick
d-padup/dpad_up, down/dpad_down, left/dpad_left, right/dpad_right
bind start = do {
  open_window(800, 600)
  bind x = 400.0
  bind y = 300.0
  while window_is_open() {
    pad_poll()
    if pad_connected(0) {
      bind x = x + pad_lx(0) * 5.0
      bind y = y + pad_ly(0) * 5.0
      if pad_pressed(0, "a") { print("jump") }
    }
    fill(0, 0, 0)
    set_color(255, 255, 255)
    draw_disc(x, y, 20)
    present()
  }
}

The gamepad_* family

Call gamepad_poll() once per frame; the most recently active controller becomes the current one. In a browser build gamepad_poll and gamepad_rumble do nothing, so use pad_* there.

  • gamepad_button(name): 1 while held, else 0. Names: a, b, x, y, l1, r1, l2, r2, l3, r3, start, select, dup, ddown, dleft, dright.
  • gamepad_axis(name): lx, ly, rx, ry (sticks, -1 to 1) and l2, r2 (triggers). Here pushing a stick up gives a positive y, the opposite of pad_ly.
  • gamepad_rumble(low, high, ms): vibrate the heavy (low) and light (high) motors, each 0 to 1, for ms milliseconds (default 200). Nothing happens if the controller has no force feedback.
  • gamepad_list(): one line per controller the system can see: name, whether it’s connected, whether it can rumble, and where its button mapping came from. Use it to diagnose a controller that behaves oddly.
  • gamepad_any(): 1 if any standard button is down.
bind start = do {
  print(gamepad_list())
  gamepad_poll()
  if gamepad_button("a") == 1 {
    gamepad_rumble(0.4, 0.8, 250)
  }
}

Microphone

mic_open() starts capturing from the default input device at 44.1 kHz mono and returns 1, or 0 if there is no device or access was refused. Call it once; reading levels afterwards costs almost nothing.

  • mic_rms(): loudness of the latest buffer (root mean square), 0 to 1.
  • mic_peak(): the highest absolute sample in the latest buffer, 0 to 1.
  • mic_fft(bands): a list of bands (default 8) smoothed magnitudes in logarithmically spaced bands from 20 Hz up, bass first. All zeros while the microphone is closed.
bind start = do {
  open_window(640, 240)
  if mic_open() == 0 { print("no microphone") }
  while window_is_open() {
    bind bars = mic_fft(16)
    fill(0, 0, 0)
    set_color(80, 200, 255)
    bind i = 0
    while i < len(bars) {
      bind h = bars[i] * 200.0
      bind x = i * 40
      triangle(x, 230, x + 30, 230, x + 30, 230 - h)
      triangle(x, 230, x + 30, 230 - h, x, 230 - h)
      bind i = i + 1
    }
    present()
  }
}

For sing-along scoring, combine the microphone with the music builtins: music_mic_pitch() gives the sung frequency each frame. See Music.

Recording a seed

mic_capture() appends the latest samples to a record buffer (the most recent 96000 samples are kept) and returns its length. Call it every frame while recording. mic_seed() returns the SHA3-256 hash of the buffered audio as 64 hex characters, ready to seed a random generator. mic_clear() empties the buffer. With the microphone closed the buffer stays empty, and the seed is the hash of empty input:

bind start = do {
  print(mic_capture())
  print(mic_seed())
  print(mic_clear())
}
0
d75a5e3ee36c258bec7dced963d55ef24bda7d06d0cef7708f2ecca8371a95f7
0

See also

Dialog

Ling has two dialog tools. Dialog boxes show what a character says: an adventure-game text box that types out letter by letter, pages, and highlights names, places and items in colour. Dialog models decide what a character says: a tiny language model, trained in a second from that character’s own lines, that every NPC can carry. Its training data uses a plain text format, the Ling Dialog Standard (.lingdialog).

Both work without a window except dialog_draw, so you can test a whole conversation headless.

Summary

Builtin中文日本語한국어ไทยPurpose
dialog_show(text, cps)对话显示会話表示대화표시แสดงบทสนทนาOpen a dialog box with marked-up text.
dialog_step(dt)对话步进会話更新대화스텝ก้าวบทสนทนาAdvance the typewriter and auto-advance timer.
dialog_advance()对话推进会話送り대화진행เลื่อนบทสนทนาThe player pressed confirm.
dialog_active()对话激活会話中대화중บทสนทนาทำงานWhether a box is open.
dialog_typing()对话打字会話タイプ中대화타이핑กำลังพิมพ์บทสนทนาWhether the page is still typing.
dialog_close()对话关闭会話閉じる대화닫기ปิดบทสนทนาClose the box at once.
dialog_color(role, r, g, b)对话颜色会話色대화색สีบทสนทนาColour of a text role.
dialog_draw(x, y, w, h, font)对话绘制会話描画대화그리기วาดบทสนทนาDraw the box and its revealed text.
dialog_new(ctx, embed, hidden, seed)建对话模型対話モデル作成대화모델생성สร้างโมเดลสนทนาCreate an empty dialog model.
dialog_learn(m, text)对话学习対話学習대화학습เรียนรู้สนทนาAdd one line to the model’s corpus.
dialog_load(m, path)对话载入対話読込대화불러오기โหลดชุดสนทนาAdd a .lingdialog file to the corpus.
dialog_train(m, epochs, lr)对话训练対話訓練대화훈련ฝึกสนทนาTrain on the corpus. Returns the loss.
dialog_say(m, prompt, max, temp)对话生成対話生成대화생성พูดสนทนาGenerate a reply.
dialog_save(m, path)对话存模対話モデル保存대화모델저장บันทึกโมเดลสนทนาSave the trained model.
dialog_load_model(path)对话载模対話モデル読込대화모델불러오기โหลดโมเดลสนทนาLoad a saved model.

Dialog boxes

The box state lives in the runtime, separate from drawing: dialog_show opens it, dialog_step moves time forward, dialog_advance reacts to the player, and dialog_draw paints it. While dialog_active() is true, pause your game world.

Markup

MarkupMeaning
{n}...{/}A character name (colour role 1).
{p}...{/}A place (role 2).
{i}...{/}An item (role 3).
a newline characterA new line in the box.
||A page break.

A tag is exactly three characters, {, a letter and }, and {/} returns to plain text (role 0). Anything else is shown as written.

A page that has finished typing advances by itself after 1.4 seconds, and the last page then closes the box.

dialog_show(text, cps)

Opens a box with text, typed at cps characters per second (default 32, at least 1). It replaces any box already open.

dialog_step(dt)

Advances the typewriter and the auto-advance timer by dt seconds (default 0.016). Call it every frame while the box is active.

dialog_advance()

Call it when the player presses the confirm key. If the page is still typing, the rest of the page appears at once; otherwise the box moves to the next page, or closes after the last one. Drive it from a key press (key_pressed), not a held key, so one press doesn’t skip several pages.

dialog_active(), dialog_typing() and dialog_close()

dialog_active() is true while a box is open. dialog_typing() is true while the current page is still appearing. dialog_close() closes the box immediately.

bind start = do {
  dialog_show("Hello {n}Ling{/}.||Second page.", 100)
  print("active: " + str(dialog_active()))
  print("typing: " + str(dialog_typing()))
  dialog_step(0.5)
  print("typing after 0.5 s: " + str(dialog_typing()))
  dialog_advance()
  print("page 2 typing: " + str(dialog_typing()))
  dialog_advance()
  dialog_advance()
  print("active at the end: " + str(dialog_active()))
}
active: true
typing: true
typing after 0.5 s: false
page 2 typing: true
active at the end: false

At 100 characters per second the first page is fully typed after 0.5 s. The first dialog_advance turns to page 2, the second reveals all of page 2, and the third closes the box.

dialog_color(role, r, g, b)

Sets the colour of a role: 0 plain text, 1 name, 2 place, 3 item (values above 3 count as 3). r, g and b are 0 to 255 (default 255).

dialog_draw(x, y, w, h, font)

Draws the bevelled box with its top-left corner at (x, y) (default 40, 0), size w by h (default 720 by 150), and the text revealed so far. font is a handle from font_load; leave it out or pass -1 to use the built-in text drawing.

bind start = do {
  open_window(800, 600)
  bind ui = font_load("assets/fonts/Exo2.ttf", 600.0)
  bind line = "Hey {n}Link{/}! Take the {i}Master Sword{/} to {p}Hyrule Field{/}.||Beware the night."
  dialog_color(1, 255, 210, 80)
  while window_is_open() {
    if key_pressed("space") {
      if dialog_active() { dialog_advance() } else { dialog_show(line, 34.0) }
    }
    fill(10, 10, 20)
    if dialog_active() {
      dialog_step(0.016)
      dialog_draw(50.0, 420.0, 700.0, 150.0, ui)
    } else {
      // normal game update here
    }
    present()
  }
}

Dialog models

A dialog model is a miniature next-word language model, a few kilobytes in size, built into Ling (ling_ai::dialog_lm). You give it a character’s lines, train it, and ask it to continue a prompt. It learns cadence and vocabulary, not facts, so it suits ambient chatter, barks and flavour text. Training a small corpus takes well under a second. With temperature 0 the output is deterministic.

bind start = do {
  bind npc = dialog_new(3, 32, 64, 1)
  dialog_learn(npc, "welcome traveler")
  dialog_learn(npc, "keep your blade sharp")
  dialog_learn(npc, "welcome back traveler")
  bind loss = dialog_train(npc, 60, 0.1)
  print(loss < 2.0)
  print(dialog_say(npc, "welcome", 6, 0.0))
}
true
back traveler

dialog_new(ctx, embed, hidden, seed)

Creates an empty model and returns its handle. ctx (default 3) is how many previous words it looks at, embed (default 32) and hidden (default 64) are the network sizes, and seed (default 1) makes training repeatable.

dialog_learn(m, text) and dialog_load(m, path)

dialog_learn adds one line to the corpus. dialog_load adds a whole .lingdialog file and returns the number of training lines it added (one per conversation), or -1 if the file can’t be read.

dialog_train(m, epochs, lr)

Trains on everything in the corpus for epochs passes (default 20) at learning rate lr (default 0.1). Returns the final loss: lower means the model fits its lines better.

dialog_say(m, prompt, max, temp)

Continues prompt for up to max words (default 24) and returns only the new words. It stops early at the end of a turn. temp (default 0.8) is the temperature: 0 always picks the likeliest word, higher values are more varied.

The tokenizer splits text at spaces and punctuation and lower-cases it. For languages written without spaces, put a space between words in your corpus and prompts; the reply comes back with spaces between words.

dialog_save(m, path) and dialog_load_model(path)

dialog_save writes the trained model to a file (default "model.llm") and returns true on success. dialog_load_model reads one back and returns a new handle, or -1 on failure. Train once while building your game, then ship and load the small model file.

The Ling Dialog Standard

.lingdialog is a line-based, human-writable corpus format. Writers edit it by hand or generate it from a spreadsheet; it diffs cleanly in reviews and can be localized like any text file.

# Ling Dialog Standard v1
@meta title: Tavern Keeper
@meta speaker: Bram

= welcome
bram: welcome traveler
hero: any news from the road
bram: bandits on the north pass
      nothing my stew cannot cure

= rumors
bram: keep your blade sharp
LineMeaning
# ...Comment to the end of the line.
@meta key: valueMetadata about the dataset. Repeatable.
= labelStart a new conversation. The label is optional.
speaker: textOne turn. The speaker is the text before the first colon.
a line without :Continues the previous turn (joined with a space).
a blank lineIgnored.

Parsing never fails: a malformed line is skipped, so one stray character can’t break a training run. Turns before the first = form an implicit conversation.

Each conversation becomes one training line, with its turns joined by the reserved <eos> token, so the model learns to continue across turns. Writing <eos> yourself also marks a turn boundary. The reserved tokens are <pad>, <bos>, <eos> and <unk>.

bind start = do {
  write_file("bram.lingdialog", "# Ling Dialog Standard v1\n@meta speaker: Bram\n\n= welcome\nbram: welcome traveler\nhero: any news from the road\nbram: bandits on the north pass\n\n= rumors\nbram: keep your blade sharp\n")
  bind npc = dialog_new(3, 32, 64, 1)
  print(dialog_load(npc, "bram.lingdialog"))
  dialog_train(npc, 80, 0.1)
  print(dialog_say(npc, "bandits on the", 8, 0.0))
  print(dialog_save(npc, "bram.llm"))
  bind again = dialog_load_model("bram.llm")
  print(dialog_say(again, "keep your", 8, 0.0))
}
2
north pass
true
blade sharp

Writing a good corpus

  • Consistency beats volume. A small corpus in one clear voice gives a more recognisable character than a large generic one.
  • Repeat signature phrases. Lines you want the character to favour should appear a few times across conversations.
  • One file per voice. Keep each character in its own file, so each gets its own model and personality.
  • Write naturally. Case and punctuation are handled by the tokenizer.

Putting them together

The model writes the line; the box shows it:

bind start = do {
  open_window(800, 600)
  bind bram = dialog_load_model("npc/bram.llm")
  while window_is_open() {
    if key_pressed("e") && !dialog_active() {
      dialog_show("{n}Bram{/}: " + dialog_say(bram, "welcome", 12, 0.7))
    }
    if key_pressed("space") && dialog_active() { dialog_advance() }
    fill(10, 10, 20)
    dialog_step(0.016)
    if dialog_active() { dialog_draw(50, 420, 700, 150) }
    present()
  }
}

See also

Web Server and HTTP

Ling ships a small, fast web server. You register routes, static folders and virtual hosts, then call http_serve, which blocks and answers requests. The http_* builtins drive ling-http (axum and tokio) from Ling code. The same family has an HTTP client (http_get and friends) and helpers for query strings, cookies and escaping.

ling-lang.org runs on this. Its server is one Ling file, site.ling. It serves the landing page, these docs under /docs/, the Ling Book PDFs and the example SVGs, and uses http_vhost to send the retired docs.ling-lang.org subdomain to /docs/.

Install profile. The server and client builtins are part of the web profile (and full, the default). A ling built with --no-default-features --features core stops with unknown function 'http_static'. Reinstall with cargo install ling-lang or add --features web.

How a request is answered

  1. Virtual hosts (http_vhost) come first. If the Host header names a registered host, the request is answered from that host’s folder, or redirected if the target is a URL.
  2. Static prefixes (http_static) come next. /css/style.css under a /css prefix is read from disk byte for byte.
  3. Routes (http_route) come last: method plus exact path. The handler is a Ling function that receives a Request and returns text or a response record.
  4. Anything else gets 404 with the body not found.

Steps 1 and 2 run on the async runtime and never touch the interpreter, so big files (videos, PDFs, zips) stream concurrently and support HTTP range requests. Ling handlers run one at a time on the interpreter unless you pass workers to http_serve.

Programs that call http_serve always run on the interpreter, even under plain ling run, because handlers are functions passed as arguments.

Summary

Builtin中文日本語한국어ไทยPurpose
http_route(method, path, handler)———เว็บเส้นทางHandle one method and exact path.
http_static(prefix, dir)———เว็บสแตติกServe a folder at a URL prefix, byte for byte.
http_vhost(host, target)————Serve a folder at the root of a hostname, or redirect that hostname.
http_serve(host, port, workers)———เว็บเสิร์ฟStart HTTP and run the request loop. Blocks.
http_serve_tls(host, port, cert, key, workers)————HTTPS with PEM certificate and key files.
http_serve_dev_tls(host, port, workers)————HTTPS with a throwaway self-signed certificate.
http_get(url)———เว็บรับFetch a URL and wait for the body.
http_get_status()————Status of the last http_get.
http_get_all(urls)————Fetch several URLs at once.
http_get_async(url)————Start a GET in the background. Returns a job id.
http_post_async(url, body, type)———เว็บโพสต์ไม่บล็อกStart a POST in the background. Returns a job id.
http_job_poll(id)———เว็บงานสำรวจ"" while a job runs, then its result.
query_param(qs, name, default)———พารามิเตอร์One value from a=1&b=2, decoded.
cookie_get(header, name, default)———รับคุกกี้One cookie from a Cookie header.
html_escape(text)———กันเอชทีเอ็มแอลEscape & < > " ' for HTML.
json_escape(text)———หนีเจสันEscape text for a JSON string.
url_decode(text)网址解码———Decode %XX and +.
cli_arg(name, default)———อาร์กิวเมนต์--name value from the command line, as text.
env_get(name, default)———รับตัวแปรแวดล้อมAn environment variable.

Server builtins

http_route(method, path, handler)

Registers handler for method (case-insensitive, default "GET") and path (default "/"). Paths match exactly and exclude the query string, so there are no path parameters: pass ids in the query (/note?id=2) and read them with query_param(req.query, "id", ""). Register every route before calling http_serve.

A handler that raises an error answers 500 with handler error: ... in the body, which can reveal internals. Validate input so errors don’t escape.

http_static(prefix, dir)

Serves the folder dir (default "static") at prefix (default "/static"): http_static("/css", "css") maps /css/a.css to css/a.css. A request for a folder serves its index.html. Use it for everything binary, because route handlers can only return text.

http_vhost(host, target)

Gives a whole hostname its own behaviour. target is either a folder or a URL.

  • A folder: that hostname is served from the folder at its root, byte for byte like http_static. A missing file answers 404 with the folder’s own 404.html when it has one (mdBook and most static-site generators write one). Use it to put a static site on its own subdomain.
  • An http:// or https:// URL: every request to that hostname answers 301 Moved Permanently to the target plus the request’s path and query. Use it to retire a subdomain without breaking old links.

Details:

  • host is matched against the Host header case-insensitively, with any port ignored.
  • Vhosts are checked before every http_static prefix and route, so a vhost request never reaches your handlers.
  • Registering several vhosts is fine; each Host matches at most one.
bind start = do {
  http_vhost("docs.example.org", "../docs/book")              // a static site at the root of the subdomain
  http_vhost("old.example.org", "https://example.org/docs")   // old.example.org/a.html -> https://example.org/docs/a.html
  http_static("/docs", "../docs/book")                        // the same site under /docs/ on the main host
  http_serve("0.0.0.0", 8080)
}

This is how ling-lang.org retires its old docs subdomain in site.ling:

fn register_docs_hosts(port) {
  http_vhost("docs.ling-lang.org", "https://ling-lang.org/docs")
  http_vhost("docs.localhost", "http://localhost:" + str(port) + "/docs")
  return true
}

To try a vhost locally without DNS, send the header yourself:

curl -i -H "Host: docs.localhost" http://127.0.0.1:8080/

Most browsers also resolve *.localhost to your own machine, so http://docs.localhost:8080/ works too.

http_serve(host, port, workers)

Starts the server and answers requests until the program is stopped. It never returns.

  • host: "127.0.0.1" (default) for this machine only, "0.0.0.0" to accept connections from the network.
  • port: default 8080.
  • workers: default 1. See the Workers section below.

A banner prints once the socket is bound. If the port is busy, the error goes to standard error and the program keeps waiting, so check the log when nothing answers.

http_serve_tls(host, port, cert, key, workers)

Serves HTTPS directly, no reverse proxy needed. cert and key are paths to PEM files, for example Let’s Encrypt’s fullchain.pem and privkey.pem. Keep the key file readable only by the server’s user. Otherwise it works like http_serve.

http_serve_dev_tls(host, port, workers)

Serves HTTPS with a self-signed certificate generated at start-up. Browsers and curl reject it (use curl -k locally). For local development only; never expose it to the internet.

The request

A handler receives one argument, a Request record with these text fields:

FieldContent
methodUpper-case method, such as GET.
pathPath without the query string.
queryRaw query string, without the ?. Read it with query_param.
bodyBody as UTF-8. Up to 32 MiB, except multipart uploads (below).
cookieRaw Cookie header, or "". Read it with cookie_get.
authorizationRaw Authorization header, or "".
client_ipFirst X-Forwarded-For hop, else X-Real-IP, else "".

client_ip comes from headers that any client can set. Trust it only behind your own reverse proxy; it is empty for direct connections.

A multipart/form-data upload streams its file to disk under storage/tmp/. The handler then gets a form-encoded body with the text fields plus artifact_path and artifact_size; read them with query_param(req.body, ...).

The response

Return text for 200 with text/html; charset=utf-8. Any other value that isn’t a record is turned into text and sent as text/plain.

For anything else, return a record with any of the fields status, content_type, body, set_cookie and location. Missing fields default to status 200, an empty body and text/html. Records are built positionally, and the field names are what count; the record’s own name doesn’t matter:

form Response { status, content_type, body, set_cookie, location }

fn api_status(req) {
  return Response(200, "application/json", "{\"ok\":true}", "", "")
}

fn old_page(req) {
  return Response(301, "text/plain", "", "", "/new")
}

fn login(req) {
  bind cookie = "sid=" + random_hex(16) + "; HttpOnly; Secure; SameSite=Lax; Path=/"
  return Response(303, "text/plain", "", cookie, "/me")
}

bind start = do {
  http_route("GET", "/api/status", api_status)
  http_route("GET", "/old", old_page)
  http_route("POST", "/login", login)
  http_serve("127.0.0.1", 8080)
}

Responses from Ling routes carry X-Frame-Options: DENY and Content-Security-Policy: frame-ancestors 'none', except for paths under /embed. Nothing else is added: set Secure, HttpOnly and SameSite on cookies yourself, and add other security headers (HSTS, a full content security policy) at your reverse proxy.

Workers

By default one interpreter answers every request, one at a time. A slow handler makes every other visitor wait.

With http_serve(host, port, N) and N above 1, N interpreters take requests from one queue. ling-lang.org reads the number from the command line (--workers 4). Rules:

  • Handlers must be named top-level functions. An inline closure handler is an error at start-up.
  • The start block runs once, on the main interpreter. Workers only see the program’s declarations, so keep configuration in functions, not in top-level binds that start changes.
  • Each worker opens its own connection to the db_open database. See Database (SQLite).
  • Async jobs are shared: a job started on one worker can be polled from another.

Request helpers

These work anywhere, not only in handlers, so you can try them headless:

bind start = do {
  bind qs = "q=a%20b&page=2&tag=x+y"
  print(query_param(qs, "q", ""))
  print(query_param(qs, "page", "1"))
  print(query_param(qs, "tag", ""))
  print(query_param(qs, "sort", "new"))
  print(cookie_get("sid=abc123; theme=dark", "theme", "light"))
  print(html_escape("<b>Ada & 'Bob'</b>"))
  print("{\"name\":\"" + json_escape("say \"hi\"\n") + "\"}")
  print(url_decode("a%20b+c%41"))
  print(cli_arg("port", "8080"))
}
a b
2
x y
new
dark
&lt;b&gt;Ada &amp; &#39;Bob&#39;&lt;/b&gt;
{"name":"say \"hi\"\n"}
a b cA
8080
  • query_param(qs, name, default): the first value for name, with %XX and + decoded. Works on req.query and on form bodies (req.body).
  • cookie_get(header, name, default): one cookie from req.cookie, not decoded.
  • html_escape(text): escape every untrusted value where you build HTML. It is enough for element content and quoted attributes, not inside <script> or unquoted attributes.
  • json_escape(text): escapes ", \ and control characters, without adding the surrounding quotes. Ling builds JSON by concatenation, so always pass text through it.
  • url_decode(text): decode %XX and +.
  • cli_arg(name, default): --name value from the command line, as text. Convert with to_number: cli_arg("port", "8080") + 0 gives "80800".
  • env_get(name, default): an environment variable. Load secrets this way, not from source.

HTTP client

http_get(url) and http_get_status()

http_get fetches an http:// or https:// URL and waits for the body. It returns the body even for an error status. http_get_status() gives the status of the last http_get; 0 means no response at all (DNS, connection or TLS failure), and the body is then "". Check the status before trusting the body.

http_get blocks. That’s fine in a tool or at start-up, but inside a handler it stalls every visitor, so use the async versions there.

http_get_all(urls)

Fetches a list of URLs at the same time and waits for all of them. Returns the bodies in the same order, with "" for a failure or an HTTP error status.

http_get_async(url), http_post_async(url, body, type) and http_job_poll(id)

Start a request in the background and return a job id at once. type is the Content-Type of the POST body (default "application/json"). Call http_job_poll(id) later: it returns "" while the job runs, then the response body. A failed GET gives text starting with ERROR:; a failed POST gives {"error":"..."}.

bind start = do {
  bind job = http_get_async("https://ling-lang.org/api/books.json")
  bind body = ""
  bind tries = 0
  while body == "" && tries < 100 {
    bind body = http_job_poll(job)
    sleep(50)
    bind tries = tries + 1
  }
  print(body)
}

Worked example: a small site

form Response { status, content_type, body, set_cookie, location }

fn page_index(req) {
  return read_file("index.html")
}

fn api_hello(req) {
  bind name = query_param(req.query, "name", "world")
  return Response(200, "application/json", "{\"hello\":\"" + json_escape(name) + "\"}", "", "")
}

bind start = do {
  http_static("/css", "css")
  http_static("/images", "images")
  http_route("GET", "/", page_index)
  http_route("GET", "/api/hello", api_hello)
  http_serve(cli_arg("host", "127.0.0.1"), to_number(cli_arg("port", "8080")), 4)
}

Run it with ling run site.ling --port 8080, then open http://127.0.0.1:8080/ or http://127.0.0.1:8080/api/hello?name=Ada.

See also

Database (SQLite)

Ling has SQLite built in. Three builtins cover everything: db_open opens a database file, db_exec changes data or schema, and db_query reads rows back as records. SQLite is bundled into ling, so there is nothing to install and no server to run. The database is one ordinary file next to your program.

The builtins are part of the web install profile (and full, the default), because they are usually paired with the web server. They work just as well in a command-line tool.

Summary

Builtin中文日本語한국어ไทยPurpose
db_open(path)———ฐานข้อมูลเปิดOpen or create a database and make it the current connection.
db_exec(sql, params...)———ฐานข้อมูลรันRun one statement that changes data or schema. Returns rows affected.
db_query(sql, params...)———ฐานข้อมูลถามRun a query. Returns a list of Row records.

A first database

bind start = do {
  db_open(":memory:")
  db_exec("CREATE TABLE notes(id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, stars REAL, note TEXT)")
  db_exec("INSERT INTO notes(title, stars) VALUES (?1, ?2)", "first", 4.5)
  db_exec("INSERT INTO notes(title, stars) VALUES (?1, ?2)", "it's safe", 3)
  bind rows = db_query("SELECT id, title, stars, note FROM notes ORDER BY id")
  print(len(rows))
  print(rows[0])
  for row in rows {
    print(str(row.id) + ": " + row.title)
  }
  print("[" + rows[1].note + "]")
}
2
Row { id: 1, title: first, stars: 4.5, note:  }
1: first
2: it's safe
[]

":memory:" makes a database that lives only while the program runs, which is handy for tests and examples. Use a file name such as "app.db" to keep the data.

db_open(path)

Opens the SQLite database at path (default "app.db"), creating the file if it doesn’t exist, and makes it the interpreter’s current connection. Returns nothing.

  • On opening, Ling turns on foreign keys (PRAGMA foreign_keys = ON), write-ahead logging (journal_mode = WAL) and a 5-second busy timeout, so a write that meets another write waits its turn instead of failing with “database is locked”.
  • Each interpreter holds one connection. Calling db_open again replaces it.
  • With WAL, SQLite keeps two helper files next to the database while it’s open (app.db-wal and app.db-shm). Back up all three, or copy the database while no program has it open.
  • If the file can’t be opened, db_open raises an error.

db_exec(sql, params...)

Runs one SQL statement that doesn’t return rows: CREATE, INSERT, UPDATE, DELETE, BEGIN, COMMIT, and so on. Returns the number of rows it changed (0 for schema statements).

  • Put one statement in each call. Two statements separated by ; are an error.
  • On failure it raises an error that includes the SQL text. Calling it before db_open is also an error.

db_query(sql, params...)

Runs a query and returns all rows as a list of Row records. Read a column with a dot: row.title. The field names are the column names from your SELECT, so give computed columns a name with AS:

bind start = do {
  db_open(":memory:")
  db_exec("CREATE TABLE log(n INTEGER)")
  db_exec("BEGIN")
  bind i = 0
  while i < 1000 {
    db_exec("INSERT INTO log(n) VALUES (?1)", i)
    bind i = i + 1
  }
  db_exec("COMMIT")
  bind r = db_query("SELECT count(*) AS n, sum(n) AS total, avg(n) AS mean FROM log")[0]
  print(r.n)
  print(r.total)
  print(r.mean)
}
1000
499500
499.5

Wrapping many inserts in BEGIN and COMMIT makes them one transaction, which is much faster than committing each row separately.

How values come back

SQLite valueLing value
INTEGERnumber
REALnumber
TEXTtext
NULL"" (empty text)
BLOBbase64 text

A query with no matches returns an empty list, so check len(rows) before reading rows[0].

Parameters

Parameters bind positionally to ?1, ?2, ?3, and so on, in the order you pass them after the SQL. Always pass user input as a parameter, never by gluing it into the SQL text. A parameter is only ever a value, so it can’t change the statement:

bind start = do {
  db_open(":memory:")
  db_exec("CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT UNIQUE, admin INTEGER)")
  bind name = "Robert'); DROP TABLE users; --"
  db_exec("INSERT INTO users(name, admin) VALUES (?1, ?2)", name, false)
  db_exec("INSERT INTO users(name, admin) VALUES (?1, ?2)", "ada", true)
  print(db_query("SELECT count(*) AS n FROM users")[0].n)
  print(db_query("SELECT name FROM users WHERE admin = ?1", true)[0].name)
  print(db_query("SELECT last_insert_rowid() AS id")[0].id)
  print(db_exec("UPDATE users SET admin = 0 WHERE name = ?1", "ada"))
  print(db_exec("DELETE FROM users WHERE id > ?1", 100))
}
2
ada
2
1
0

How Ling values bind:

Ling valueBinds as
whole number (3)INTEGER
fractional number (4.5)REAL
true / false1 / 0
anything elseTEXT (the value as text)

To get the id of the row you just inserted, query SELECT last_insert_rowid() AS id on the same connection, as above.

Errors

A failing statement (a syntax error, a missing table, a broken UNIQUE constraint) raises a runtime error whose message starts with db_exec: or db_query: and shows the SQL.

On the interpreter (ling run --interp, and always for programs that call http_serve) the error stops the program, or comes back as bad inside try. With the default JIT backend of ling run, a failing statement is currently skipped without a message, so run database scripts with --interp while you develop them.

fn add_user(name) {
  return db_exec("INSERT INTO users(name) VALUES (?1)", name)
}

fn try_add(name) {
  match try(| | add_user(name)) {
    ok(n) => return "added"
    bad(e) => return "could not add " + name + ": " + e
  }
}

With the web server

The usual shape is: open the database in start, create the tables if needed, register routes, then serve. Handlers call db_query and db_exec directly.

form Response { status, content_type, body, set_cookie, location }

fn list_notes(req) {
  bind rows = db_query("SELECT id, title FROM notes ORDER BY id DESC LIMIT 50")
  bind out = "<ul>"
  for row in rows {
    bind out = out + "<li>" + html_escape(row.title) + "</li>"
  }
  return out + "</ul>"
}

fn add_note(req) {
  bind title = query_param(req.body, "title", "")
  if title == "" {
    return Response(400, "text/plain", "title is required", "", "")
  }
  db_exec("INSERT INTO notes(title) VALUES (?1)", title)
  return Response(303, "text/plain", "", "", "/")
}

bind start = do {
  db_open("notes.db")
  db_exec("CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL)")
  http_route("GET", "/", list_notes)
  http_route("POST", "/add", add_note)
  http_serve("127.0.0.1", 8080, 4)
}

Workers and connections

With http_serve(host, port, 1) (the default) one interpreter answers every request, one at a time, over its one connection.

With workers above 1, each extra worker is its own interpreter with its own connection to the path you gave db_open. Reads run side by side. Writes still happen one at a time: WAL plus the busy timeout make them queue instead of fail. Two things follow:

  • Call db_open in start, before http_serve. Workers open the path that was current when the server started.
  • Don’t use ":memory:" with workers. Each worker would get its own separate, empty in-memory database.

Keep transactions short inside handlers. A BEGIN without a COMMIT in the same handler holds the write lock and makes every other writer wait.

See also

Networking

Ling has four networking families besides HTTP. Pick by what you are building:

You wantUseSecurity
A game lobby or LAN toolnet_*Plain text, no authentication. Trusted LANs only.
To run commands on a server, or accept SSH clientsssh_*SSH-2, host keys pinned, password login.
A private request/response servicelingtp_*Post-quantum handshake, pinned host keys.
A peer-to-peer network of nodes with identitiesp2p_*Post-quantum, authenticated, padded frames.

For HTTP and HTTPS, see Web Server and HTTP. net_* is part of every install; ssh_*, lingtp_* and p2p_* need the privacy profile (included in the default full install).

All of these builtins block or poll; none of them takes a callback. You write a loop that checks for work and calls sleep(ms) between checks. Failures to bind or connect show up in a status number, not as an error, so always check the status.

LAN lobby: net_*

net_* is a small, dependable transport for game state. A process is either a host that accepts up to 64 clients, or a client connected to one host. Each message is one line of UTF-8 text. Sockets run on background threads, so a game loop never blocks: net_send queues a line and net_recv takes one.

Builtin中文日本語한국어ไทยPurpose
net_host(port)———เน็ตโฮสต์Listen on a TCP port (default 7777) and become the host
net_join(ip, port)———เน็ตจอยConnect to a host and become a client
net_send(text)———เน็ตส่งSend one line: host to all clients, client to host
net_send_to(id, text)————Host only: send one line to one client
net_recv()———เน็ตรับOldest queued message, or ""
net_recv_from()————Same, as "id|text"
net_clients()————Host: client ids such as "1,2"
net_client_count()————Number of connected peers
net_events()————Drain connect:<id> / disconnect:<id> lines
net_status()———เน็ตสถานะ0 idle or failed, 1 waiting, 2 connected
net_close()——연결종료—Close the host or client
net_announce(port, info)———เน็ตประกาศHost: broadcast a lobby description on the LAN
net_announce_stop()———เน็ตหยุดประกาศStop broadcasting
net_discover(port)———เน็ตค้นหาClient: hosts heard in the last 5 seconds
net_test(port)———เน็ตทดสอบReport whether the port can be bound and the LAN address
net_local_ip()————This machine’s LAN address, or "" offline
net_upnp_map(port, description)————Ask the router to forward a TCP port (in the background)
net_upnp_poll()————Result of net_upnp_map
net_upnp_unmap()————Remove the forward

Hosting and joining

net_host(port) and net_join(ip, port) return nothing; watch net_status(). On a host, 1 means waiting for a client and 2 means at least one is connected. On a client, 1 means connecting and 2 means connected. If the port can’t be bound or the connection fails, the status goes back to 0. One role per process: calling net_host or net_join again replaces the old role.

# host.ling
bind start = do {
    net_host(17777)
    bind n = 0
    while n < 100 {
        bind m = net_recv()
        if m != "" {
            print("host got: " + m)
            net_send("echo:" + m)
            bind n = 1000
        }
        sleep(50)
        bind n = n + 1
    }
    sleep(300)
    net_close()
}
# client.ling
bind start = do {
    net_join("127.0.0.1", 17777)
    bind n = 0
    while net_status() != 2 && n < 100 {
        sleep(50)
        bind n = n + 1
    }
    net_send("hello")
    bind got = ""
    while got == "" && n < 200 {
        bind got = net_recv()
        sleep(50)
        bind n = n + 1
    }
    print("client got: " + got)
    net_close()
}

Run the host in one terminal and the client in another. The client prints client got: echo:hello.

Messages and events

  • A message must not contain a newline: an embedded newline arrives as two messages.
  • Each inbound queue holds 4096 lines; when it is full, the oldest are dropped.
  • net_recv() and net_recv_from() read the same queue, so use one style per program. net_recv_from() returns "2|hello"; split on the first |, because the message itself may contain |.
  • net_events() keeps the last 256 events, joined with newlines.

Finding hosts on the LAN

net_announce(port, info) broadcasts info over UDP (default port 7778) about once a second. Calling it again updates the text. net_discover(port) returns "ip|info" lines for hosts heard in the last 5 seconds. Its first call starts a listener, so it returns "" until an announcement arrives.

bind start = do {
    bind hosts = ""
    bind n = 0
    while hosts == "" && n < 40 {
        bind hosts = net_discover(7778)
        sleep(250)
        bind n = n + 1
    }
    print(hosts)
}

Router port forwarding

net_upnp_map(port, description) asks the router (UPnP IGD) to forward a TCP port to this machine. net_upnp_poll() returns "" while it works, then "ok|<public ip>", "cgnat|<ip>" (the router is itself behind carrier NAT, so a forward can’t reach you), or "fail|<reason>". net_upnp_unmap() removes the forward.

Security

The host listens on all interfaces, the traffic is plain text, and anyone who can reach the port can join. Use net_* on trusted LANs or inside a tunnel. Across the internet, use lingtp_*, ssh_* or HTTPS. net_test and net_local_ip learn the LAN address by opening a UDP socket towards a public address; nothing is sent.

SSH: ssh_*

The SSH builtins are a real SSH-2 client and a small SSH server. The client works with any OpenSSH server. The server lets a Ling program receive shell lines and exec requests from OpenSSH clients. None of them has a localized alias.

BuiltinPurpose
ssh_connect(host, port, user, password)Connect and log in: 1 ok, 0 wrong credentials, -1 connection error, -2 host key changed
ssh_exec(command)Run one command and return its standard output
ssh_exit_code()Exit status of the last ssh_exec (-1 if none)
ssh_client_status()0 disconnected, 2 connected
ssh_close()Disconnect the client
ssh_config(port, user, password, host_key_path)Stage the server settings
ssh_serve()Start the server in the background; true if listening
ssh_serve_recv()Oldest input from any client as "id|text", or ""
ssh_serve_send(id, text)Send one line to a client
ssh_serve_exit(id, code)Finish an exec request with an exit status and close the channel
ssh_serve_clients()Connected client ids, comma-separated
ssh_serve_client_count()Number of connected clients
ssh_serve_events()Drain connect:, disconnect: and authfail: lines
ssh_serve_status()0 idle, 1 listening, 2 client connected
ssh_stop()Stop listening and drop all clients

Client

bind start = do {
    bind r = ssh_connect("192.168.1.20", 22, "deploy", env_get("DEPLOY_PASSWORD", ""))
    if r == 1 {
        print(ssh_exec("uname -a"))
        print(ssh_exit_code())
        ssh_close()
    } else {
        print("ssh failed: " + r)
    }
}

The client checks every host key against a known_hosts file in OpenSSH format. The first connection to a host trusts its key, like OpenSSH; a changed key is refused (-2). Authentication is by password only. Don’t put passwords in source code: read them with env_get.

Server

ssh_config takes the port (default 22), the one accepted user name, a password that must not be empty, and the Ed25519 host key file ("" means .ling-ssh/host_ed25519, created on first start). The server offers password login only and compares passwords in constant time. It doesn’t run commands for you: it queues what the client typed, and your code decides what to answer. It is a protocol endpoint, not a shell.

bind start = do {
    ssh_config(2222, "admin", env_get("SSH_PASSWORD", ""), "")
    if ssh_serve() {
        while true {
            bind m = ssh_serve_recv()
            if m != "" {
                bind parts = split(m, "|")
                ssh_serve_send(to_number(parts[0]), "you said: " + parts[1])
                ssh_serve_exit(to_number(parts[0]), 0)
            }
            sleep(50)
        }
    }
}

Known limitation: in a loopback test of the Ling client against the Ling server, ssh_exec returned "" with exit code -1 instead of the server’s reply. Prefer OpenSSH as the peer and test your own pairing before you depend on it.

Post-quantum transport: lingtp://

lingtp:// is a small request/response protocol that plays the role of HTTPS with post-quantum cryptography and no certificate authority. Each connection starts with a handshake: the server proves its identity with an ML-DSA-87 signature, and both sides agree a key with the X25519 + ML-KEM-768 hybrid KEM. Every frame is then sealed with XChaCha20-Poly1305 and wrapped again with the DICE-42 cascade. Keys are fresh per connection, which gives forward secrecy.

Trust works like SSH. The first time a client sees a host, it stores the host’s public key in .lingtp/known_hosts (relative to the current folder). If that host later shows a different key, the connection is refused. If the network may be hostile, check the key out of band the first time.

A request is one string (the path, including any query string) and a response is one string (the body). A POST sends path + "\n" + body, so a handler tells them apart by looking for a newline.

BuiltinPurpose
lingtp_get(host, port, path)Fetch a path (port defaults to 7780); returns the body, "" on failure
lingtp_post(host, port, path, body)Send a body; returns the response body
lingtp_get_status()Outcome of the last request: 1 ok, 0 connect error, -1 bad server signature, -2 host key changed
lingtp_config(port, host_key_path)Stage the server settings
lingtp_route(prefix, handler)Answer paths that start with prefix (longest prefix wins)
lingtp_serve()Serve until lingtp_stop; blocks the calling thread
lingtp_stop()Stop the server
lingtp_status()0 stopped, 1 listening, 2 client connected
lingtp_client_count()Number of connected clients
lingtp_events()Drain connect:<id> / disconnect:<id> lines

None of them has a localized alias.

Serving

Register routes just before lingtp_serve(): it clears the route table when it starts. It returns false if nothing was configured or the key or socket couldn’t be created. A handler takes the path and returns the body.

fn greet(path) {
    return "pq-hello from " + path
}

bind start = do {
    lingtp_config(17780, "hostkey.hex")
    lingtp_route("/", greet)
    print("serving")
    lingtp_serve()
}

Fetching

bind start = do {
    bind body = lingtp_get("127.0.0.1", 17780, "/hi?x=1")
    if lingtp_get_status() == 1 {
        print(body)
    } else {
        print("lingtp failed: " + lingtp_get_status())
    }
}

Against the server above this prints pq-hello from /hi?x=1.

Security notes

  • The host key is stored as a hex seed in a plain file (.lingtp/host_mldsa87 by default, or the path you give lingtp_config). Protect it like an SSH private key and back it up: if you lose it, the server’s identity changes and every client refuses to connect.
  • A handler error is sent back to the client as handler error: ..., which can reveal internals. Validate input and avoid errors in handlers.
  • The server listens on all interfaces and answers one request at a time.
  • lingtp_post treats the first newline as the start of the body, so percent-encode newlines in the path.
  • The ling-net Rust crate has its own lingtp module with a different wire format. A Ling lingtp_get can’t talk to a ling-net server. Use one implementation on both ends.

Peer-to-peer: p2p_*

p2p_* runs LWP-1, the transport of the Ling Wallet project. Peers authenticate each other with ML-DSA-87 identities during a hybrid X25519 + ML-KEM-1024 handshake, and frames are padded to fixed sizes and sealed. A node keeps a peer database, can use a signed seed list and a SOCKS5 proxy (such as Tor on 127.0.0.1:9050), and relays transactions with Dandelion++. Payloads are hex strings tagged with a kind number that your program defines.

BuiltinPurpose
p2p_start(config, events)Start a node; Ok(handle) or Err(message). Pass "" for events
p2p_poll(net, max, timeout_ms)Drain up to max events (default 64), waiting up to timeout_ms
p2p_send(net, peer, kind, payload_hex)Send to one peer; true if queued
p2p_broadcast(net, kind, payload_hex, except_peer)Send to every peer except one (-1 for none)
p2p_relay(net, id_hex, payload_hex, kind, from_peer)Dandelion++ relay of a validated transaction
p2p_mark_fluffed(net, id_hex)Record that a transaction was already broadcast
p2p_peers(net)[id, addr, inbound, fingerprint, is_seed, connected_secs] per peer
p2p_misbehaving(net, peer, score, reason)Add to a peer’s ban score
p2p_local_addr(net)Listening address "ip:port", or ""
p2p_fingerprint(identity_seed_hex)Fingerprint peers will see for a seed, like 9ebc-56af-97f2-61af
p2p_netgroup(net, peer)Network group of a peer, such as v4:1.2
p2p_seeds_sign(network, issued_at, entries, authority_seed_hex)Sign a seed list as the seed authority
p2p_seeds_verify(list_hex, authority_pk_hex)Ok([network, issued_at, entries]) or Err(...)
p2p_shutdown(net)Stop the node; true the first time

None of them has a localized alias. str_to_hex(text) and hex_to_str(hex) convert payloads between text and hex.

Configuration

config is a list of [key, value] pairs. Unknown keys, duplicates and wrong types are rejected with Err(message).

KeyMeaning
magic_hexRequired. 8 hex characters; peers with different magic never connect.
networkRequired. Network id, 0–255.
data_dirRequired. Folder for the peer database and identity; created if missing.
listen"ip:port" to accept peers, or "" for outbound only. Port 0 picks a free port.
peersList of "host:port" peers to always try.
identity_seed_hex64 hex characters for a long-term identity; omit for a random one.
ephemeral_outboundUse a fresh identity per outbound connection (default true).
max_outbound, max_inboundConnection limits (defaults 8 and 32).
proxySOCKS5 proxy "ip:port" for all outbound traffic.
seeds_hex, authority_pk_hexA signed seed list and the key that must verify it.
fast_timersShort timers, for tests.

Events

p2p_poll returns a list of events, each itself a list:

First elementLayout
"connected"["connected", peer_id, addr, inbound, fingerprint, is_seed]
"disconnected"["disconnected", peer_id]
"message"["message", peer_id, kind, payload_hex]
"stem"["stem", peer_id, payload_hex]: a Dandelion++ transaction to validate

Keep polling: events wait in a bounded queue, and a full queue slows down every peer. Message kinds are 16–255 (lower values are reserved), and payloads are at most about 4 MiB.

Example

Two nodes on one machine: A listens, B connects to A and sends hello.

fn u(r) { return match r { ok(v) => v, bad(e) => "ERR:" + e } }

bind start = do {
    bind a = u(p2p_start([["magic_hex", "4c494e47"], ["network", 1], ["listen", "127.0.0.1:0"], ["data_dir", "node_a"]], ""))
    bind b = u(p2p_start([["magic_hex", "4c494e47"], ["network", 1], ["listen", ""], ["data_dir", "node_b"], ["peers", [p2p_local_addr(a)]]], ""))
    bind peers = []
    bind n = 0
    while len(peers) == 0 && n < 100 {
        bind peers = p2p_peers(b)
        sleep(100)
        bind n = n + 1
    }
    p2p_send(b, peers[0][0], 16, str_to_hex("hello"))
    bind seen = ""
    bind n = 0
    while seen == "" && n < 20 {
        bind evs = p2p_poll(a, 10, 500)
        bind i = 0
        while i < len(evs) {
            if evs[i][0] == "message" { bind seen = hex_to_str(evs[i][3]) }
            bind i = i + 1
        }
        bind n = n + 1
    }
    print("A received: " + seen)
    p2p_shutdown(a)
    p2p_shutdown(b)
}

Security notes

  • In a restricted isolate every p2p_* builtin needs the "p2p" capability. The main thread has every capability.
  • A network handle is an unguessable 128-bit hex string, valid only in the isolate that started it. An unknown handle raises an error; after p2p_shutdown, calls return false or [].
  • data_dir holds the node’s identity. Protect it like a private key.

See also

Cryptography

Ling has cryptography built in: hashes, authenticated encryption, password hashing, classical and post-quantum signatures, a hybrid post-quantum key exchange, two-factor codes, and the Ling Wallet primitives (lw_*) with BIP-39 recovery phrases. The builtins are a thin, string-based layer over vetted Rust implementations (RustCrypto, dalek, BLAKE3, ml-kem, ml-dsa, Argon2) in the ling-crypto crate.

Which install profile you need:

BuiltinsProfile
Hashes, crypto_seal/crypto_open, signatures, knot_*, password_*web or privacy (both carry the crypto building block)
totp_secret, totp_nowweb
lw_*privacy

The default install (full) includes all of them. If a profile is missing, calling one of its builtins fails with a message that names the profile to reinstall with.

Conventions

  • Hex in, hex out. Keys, nonces, ciphertexts, digests and signatures are lowercase hex strings. A 32-byte key is 64 hex characters.
  • Handles. ed25519_keygen, mldsa_keygen, mldsa87_keygen and knot_keygen return a small number that points into a key table inside the interpreter. The lw_* family returns a 32-character hex handle instead. Secret key bytes never reach your code.
  • Results. Builtins that can fail on bad input return a result. Printed, it looks like Ok(...) or Err(message). Unwrap it with match r { ok(v) => ..., bad(e) => ... }.
  • Misspelt names are silent. An unknown function evaluates to (). If a call “does nothing”, check the spelling.

Security guidance

  1. Use the highest-level builtin that does the job. To encrypt with a key you hold, use crypto_seal. To store passwords, use password_hash. Don’t build your own scheme from hashes and XOR.
  2. Keys must be 32 bytes of real entropy. crypto_seal, crypto_open and the *_from_seed builtins read hex leniently: a short key is zero-padded, a long one is cut, and invalid hex pairs are dropped. A typo gives you a weak key, not an error. Make keys with random_hex(32). Turn a passphrase into a key with lw_password_key (Argon2id), never with a single hash.
  3. password_hash is for logins, lw_password_key is for keys.
  4. Never reuse a nonce. crypto_seal picks a fresh random nonce every call. lw_aead_seal takes the nonce from you: use random_hex(24) for each message.
  5. Don’t use the game RNG for secrets. rand is for gameplay. Use random_hex or lw_random, which read the operating system’s secure generator.
  6. Strings are not wiped. A hex secret in a Ling variable lives as long as that string. Keep secrets in handles where the API offers them, and drop lw_* keys with lw_key_drop.
  7. Compare with the verify builtins. == on strings is not constant time. Use ed25519_verify, mldsa87_verify, password_verify and totp_verify.
  8. crypto_hash is not plain SHA3-256. It adds a Ling-specific label, so it won’t match other tools. Use sha256_hex or hash_hex when you need to interoperate.
  9. Treat the Ling-specific designs as unaudited. The geometric layer (knot_points, holo_points, crypto_hash), the DICE-42 cascade inside lingtp:// and the LRS-87 ring signature are original constructions over standard primitives. LRS-87 is marked experimental. For high-value systems, use the standard primitives and get your own review.
  10. Post-quantum here is hybrid. The KEM builtins combine X25519 with ML-KEM, so the secret stays safe if either half breaks. A tampered KEM ciphertext gives a different secret instead of an error, so always use the secret to authenticate something.

Hashes and random bytes

Builtin中文日本語한국어ไทยPurpose
sha256_hex(text)SHA256哈希———SHA-256 as 64 hex characters
hash_hex(text)———แฮชสตริงBLAKE3 as 64 hex characters
file_hash(path)———แฮชไฟล์BLAKE3 of a file’s raw bytes
crypto_hash(text)几何哈希幾何ハッシュ기하해시แฮชเข้ารหัสLing’s labelled SHA3-256
shake_hex(text, len)SHAKE哈希———SHAKE-256, len bytes of output
hash_str(text)———แฮชFast non-cryptographic hash, 0 to 1
hash_int(text, n)———แฮชจำนวนFast non-cryptographic hash, 0 to n - 1
random_hex(n)——무작위16진수—n secure random bytes as hex

sha256_hex, hash_hex, file_hash

sha256_hex matches every other SHA-256 tool, including the browser’s crypto.subtle.digest. hash_hex is BLAKE3: fast and collision resistant. file_hash hashes a file’s raw bytes with BLAKE3 (binary safe) and returns "" if the file can’t be read. None of them is a password hash.

bind start = do {
    print(sha256_hex("abc"))
    print(hash_hex("abc"))
    write_file("note.txt", "hello file")
    print(file_hash("note.txt") == hash_hex("hello file"))
    remove_file("note.txt")
}
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
6437b3ac38465133ffb63b75273a8db548c558465d79db03fd359c6cd5bd9d85
true

crypto_hash, shake_hex

crypto_hash(text) computes SHA3-256("ling-geo-holo-hash-v1" + text). It is the digest that knot_points draws. shake_hex(text, len) squeezes len bytes (default 32) from SHAKE-256.

bind start = do {
    print(crypto_hash("abc"))
    print(shake_hex("abc", 16))
}
0f5ae6a06fa73d3e18615b33ee9a9efafdb1a25a7bbf5f3ca9c4d7f1ac4ddfb9
483366601360a8771c6863080cc4114d

hash_str, hash_int

FNV-1a hashes for seeds, colours and bucketing. They are deterministic and not secure: never use them on anything an attacker controls. hash_int’s n defaults to 100.

random_hex(n)

Returns n bytes (default 32, clamped to 1–256) from the operating system’s secure random generator, as 2 * n hex characters. Use it for keys, nonces and session ids.

bind start = do {
    bind key = random_hex(32)
    print(len(key))
}
64

Sealing messages

Builtin中文日本語한국어ไทยPurpose
crypto_seal(key_hex, text)封印封印する봉인ผนึกEncrypt and authenticate with XChaCha20-Poly1305
crypto_open(key_hex, sealed_hex)解封封印解除봉인해제เปิดผนึกVerify and decrypt

crypto_seal returns nonce (24 bytes) + ciphertext + tag (16 bytes) as hex. Sealing the same text twice gives different output because each call draws a new nonce. crypto_open returns the text, or Err("decryption/auth failed") if the key is wrong or one bit changed. The plaintext is decoded as UTF-8, so encode binary data first (for example with base64_encode).

bind start = do {
    bind key = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
    bind sealed = crypto_seal(key, "meet at noon")
    print(crypto_open(key, sealed))
    print(crypto_open("ff" + key, sealed))
}
meet at noon
Err(decryption/auth failed)

Passwords

Builtin中文日本語한국어ไทยPurpose
password_hash(password)——비밀번호해시—Argon2id hash as a PHC string
password_verify(password, stored)——비밀번호확인—Check a password against a stored hash

password_hash uses Argon2id with 64 MiB of memory, 3 passes, 4 lanes and a fresh random salt, and returns a string like $argon2id$v=19$m=65536,t=3,p=4$.... Store the whole string. Each call takes tens of milliseconds by design. password_verify reads the parameters from the stored string and returns true or false (a malformed string gives false).

bind start = do {
    bind stored = password_hash("correct horse")
    print(substr(stored, 0, 30))
    print(password_verify("correct horse", stored))
    print(password_verify("wrong", stored))
}
$argon2id$v=19$m=65536,t=3,p=4
true
false

Signatures

Three families share one shape: make a keypair (random or from a 32-byte seed), read the public key, sign a string, verify with the public key.

FamilyPrefixPublic keySignatureNotes
Ed25519ed25519_32 bytes64 bytesClassical, fast, deterministic
ML-DSA-65 (FIPS 204)mldsa_1952 bytes3309 bytesPost-quantum, NIST category 3
ML-DSA-87 (FIPS 204)mldsa87_2592 bytes4627 bytesPost-quantum, NIST category 5; used by lingtp://
Builtin中文日本語한국어ไทยPurpose
ed25519_keygen()生成签名密钥署名鍵生成생성서명키สร้างกุญแจลายเซ็นRandom keypair handle
ed25519_keygen_from_seed(seed_hex)从种子生成签名密钥シードから署名鍵生成씨앗에서생성서명키สร้างกุญแจลายเซ็นจากเมล็ดKeypair from a 32-byte seed
ed25519_public(handle)签名公钥署名公開鍵서명공개키กุญแจสาธารณะลายเซ็นPublic key as hex
ed25519_sign(handle, message)签名署名する서명하다เซ็นชื่อSignature as hex
ed25519_verify(public_hex, message, sig_hex)验证签名署名検証서명확인ยืนยันลายเซ็นtrue if valid
mldsa_keygen()生成量子签名密钥量子署名鍵生成양자서명키생성สร้างกุญแจลายเซ็นควอนตัมRandom ML-DSA-65 keypair
mldsa_keygen_from_seed(seed_hex)从种子生成量子签名密钥シードから量子署名鍵生成씨앗에서양자서명키생성สร้างกุญแจลายเซ็นควอนตัมจากเมล็ดML-DSA-65 keypair from a seed
mldsa_public(handle)量子签名公钥量子署名公開鍵양자서명공개키กุญแจสาธารณะลายเซ็นควอนตัมPublic key as hex
mldsa_sign(handle, message)量子签名量子署名する양자서명하다เซ็นชื่อควอนตัมSignature as hex
mldsa_verify(public_hex, message, sig_hex)验证量子签名量子署名検証양자서명확인ยืนยันลายเซ็นควอนตัมtrue if valid
mldsa87_keygen()————Random ML-DSA-87 keypair
mldsa87_keygen_from_seed(seed_hex)————ML-DSA-87 keypair from a seed
mldsa87_public(handle)————Public key as hex
mldsa87_sign(handle, message)————Signature as hex
mldsa87_verify(public_hex, message, sig_hex)————true if valid

Using signatures

A seed lets you store only 64 hex characters and re-create the same keypair after a restart; protect it like a private key. An unknown handle makes *_public and *_sign return "". The verify builtins return false for a bad signature or any malformed input. Ed25519 signatures are deterministic: the same key and message always give the same signature.

For long-lived artifacts such as licence files or release manifests, sign with Ed25519 and ML-DSA-87, and accept the artifact only if both verify:

bind start = do {
    bind seed = "0101010101010101010101010101010101010101010101010101010101010101"
    bind ed = ed25519_keygen_from_seed(seed)
    bind pq = mldsa87_keygen_from_seed(seed)
    bind doc = "licence: acme, expires 2031-01-01"
    bind sig_a = ed25519_sign(ed, doc)
    bind sig_b = mldsa87_sign(pq, doc)
    print(len(ed25519_public(ed)))
    print(ed25519_verify(ed25519_public(ed), doc, sig_a) && mldsa87_verify(mldsa87_public(pq), doc, sig_b))
    print(mldsa87_verify(mldsa87_public(pq), doc + "!", sig_b))
}
64
true
false

Post-quantum key exchange

Builtin中文日本語한국어ไทยPurpose
knot_keygen()生成密钥鍵生成키생성สร้างกุญแจปมHybrid X25519 + ML-KEM-768 keypair
knot_public(handle)公钥公開鍵공개키กุญแจสาธารณะปมPublic key (1216 bytes) as hex
knot_encapsulate(public_hex)封装密钥カプセル化캡슐화ห่อกุญแจปม[ciphertext_hex, secret_hex]
knot_decapsulate(handle, ciphertext_hex)解封装密钥カプセル解除캡슐해제แกะกุญแจปมThe same 32-byte secret

hybrid_keygen, hybrid_public, hybrid_encapsulate and hybrid_decapsulate are English synonyms. The flow: the receiver makes a keypair and publishes the public key; the sender encapsulates to it, keeps the secret and sends the ciphertext; the receiver decapsulates and gets the same secret. Use the secret as a crypto_seal key.

knot_keygen keys can’t be seeded or exported: they live only as long as the process. For a persistent post-quantum KEM identity, use lw_kem_keypair.

bind start = do {
    bind bob = knot_keygen()
    bind enc = knot_encapsulate(knot_public(bob))
    bind secret_bob = knot_decapsulate(bob, enc[0])
    print(enc[1] == secret_bob)
    print(crypto_open(secret_bob, crypto_seal(enc[1], "hello bob")))
}
true
hello bob

Visual fingerprints

Builtin中文日本語한국어ไทยPurpose
knot_points(text)结点坐标結び目点매듭점จุดปม256 3-D points of a torus-knot fingerprint
knot_label(text)结点标签結び目ラベル매듭라벨ป้ายปมShort name of that knot
holo_points(text)全息点ホログラム点홀로그램점จุดโฮโลแกรม4-D points of a holographic split (decorative)
holo_fragment_count(text)全息碎片数ホログラム断片数홀로그램조각수จำนวนชิ้นโฮโลแกรมNumber of fragments for a string

These turn a digest into something a person can compare by eye: draw consecutive triples from knot_points with draw_line_3d. They add no cryptographic strength of their own.

bind start = do {
    print(len(knot_points("abc")))
    print(knot_label("abc"))
}
768
knot-17_12-v5.2

One-time codes (TOTP)

Builtin中文日本語한국어ไทยPurpose
totp_secret()———โทเทนลับNew random Base32 secret (160 bits)
totp_uri(secret, account, issuer)———โทเทนยูอาร์ไอotpauth:// link for authenticator apps
totp_verify(secret, code)———โทเทนตรวจCheck a six-digit code
totp_now(secret)———โทเทนตอนนี้The code valid right now

TOTP here is RFC 6238 with SHA-1, six digits and 30-second steps, which matches Google Authenticator and Authy. totp_verify accepts one step either side and doesn’t track replay: store the last accepted code’s time step yourself. totp_uri doesn’t URL-encode, so keep & and spaces out of the account and issuer. Show the URI as a QR code with lw_qr.

bind start = do {
    print(totp_uri("JBSWY3DPEHPK3PXP", "alice@example.com", "Acme"))
    bind secret = totp_secret()
    print(len(secret))
    print(totp_verify(secret, totp_now(secret)))
}
otpauth://totp/Acme:alice@example.com?secret=JBSWY3DPEHPK3PXP&issuer=Acme&algorithm=SHA1&digits=6&period=30
32
true

Ling Wallet primitives: lw_*

The lw_* family is the primitive set of the Ling Wallet project. It differs from the builtins above in three ways:

  • Strict input. Hex must be well formed and exactly the documented length. Bad input returns Err(reason) instead of being repaired.
  • Secret handles. Builtins that create secrets return Ok(handle), a 32-character hex handle. lw_key_drop destroys the key and wipes its memory.
  • Verifiers never fail loudly. lw_id_verify, lw_ring_verify and lw_pk_valid return false for any malformed input.

None of them has a localized alias.

BuiltinPurpose
lw_h256(domain, parts)Domain-separated SHAKE-256, 32-byte output; parts is a list of hex strings
lw_xof(domain, parts, len)The same with len bytes of output
lw_random(n)n secure random bytes (up to 1 MiB) as hex
lw_aead_seal(key, nonce, aad, plaintext)XChaCha20-Poly1305 with your 24-byte nonce and associated data (all hex)
lw_aead_open(key, nonce, aad, ciphertext)Ok(plaintext_hex) or Err("authentication failed")
lw_password_key(password, salt, m_kib, t, p)Argon2id: a 32-byte key from a passphrase and a 16-byte salt
lw_kem_keypair(seed)X25519 + ML-KEM-1024 key from a 96-byte seed
lw_kem_public(handle)KEM public key (1600 bytes)
lw_kem_encaps(public_hex, context_hex)Ok([ciphertext_hex, secret_hex]), bound to a context
lw_kem_decaps(handle, ciphertext_hex, context_hex)Ok(secret_hex); a different context gives a different secret
lw_id_keypair(seed)ML-DSA-87 identity from a 32-byte seed
lw_id_public(handle)Identity public key (2592 bytes)
lw_id_sign(handle, context, message_hex)Signature under a context label such as "tx.v1"
lw_id_verify(public_hex, context, message_hex, sig_hex)true or false
lw_id_fingerprint(public_hex)Short fingerprint like 9ebc-56af-97f2-61af
lw_key_drop(handle)Destroy a secret handle; true if it existed
lw_spend_keypair, lw_spend_public, lw_onetime_secret, lw_onetime_public, lw_onetime_public_of, lw_onetime_key_imageKeys for LRS-87 ring signatures
lw_ring_sign(message_hex, ring, index, onetime_handle)Linkable ring signature (experimental)
lw_ring_verify(message_hex, ring, key_image_hex, sig_hex)true or false
lw_pk_valid(public_hex)Is this a valid 2944-byte ring public key?
lw_mnemonic_from(entropy_hex)32 bytes of entropy as a 24-word BIP-39 English phrase (a list)
lw_mnemonic_to(phrase)Ok(entropy_hex) or Err(reason)
lw_pow_hash(header_hex)Memory-hard proof-of-work hash (16 MiB, slow by design)
lw_pow_trace(header_hex, every)The same, plus points of the walk for visualisation
lw_meets_difficulty(hash_hex, difficulty)Does a hash meet a difficulty target?
lw_qr(text)QR code as a list of rows of 1 (dark) and 0 (light)

In a restricted isolate, builtins that create or use secret handles need the "keys" capability. The main thread has every capability.

Identities

An identity signs under a context label; the verifier must use the same label.

fn u(r) { return match r { ok(v) => v, bad(e) => "ERR:" + e } }

bind start = do {
    bind id = u(lw_id_keypair("0101010101010101010101010101010101010101010101010101010101010101"))
    bind pk = lw_id_public(id)
    bind sig = lw_id_sign(id, "ctx", "68656c6c6f")
    print(lw_id_verify(pk, "ctx", "68656c6c6f", sig))
    print(lw_id_verify(pk, "other", "68656c6c6f", sig))
    print(lw_id_fingerprint(pk))
    print(lw_key_drop(id))
}
true
false
9ebc-56af-97f2-61af
true

Keys from passphrases

lw_password_key returns Ok(key_hex) or Err("invalid Argon2id parameters"). Store the salt next to the ciphertext; it doesn’t need to be secret. The Ling Wallet profile is m_kib = 262144 (256 MiB), t = 3, p = 1. The example uses tiny parameters so it runs instantly; don’t copy them.

fn u(r) { return match r { ok(v) => v, bad(e) => "ERR:" + e } }

bind start = do {
    bind salt = "00112233445566778899aabbccddeeff"
    print(u(lw_password_key("hunter2", salt, 1024, 1, 1)))
}
a97cf9fed0c0703d0b60b7351990a06b086636d9fec2c5ef4d2b7a4bae25bb34

Recovery phrases (BIP-39)

lw_mnemonic_from turns 32 bytes into 24 English words. lw_mnemonic_to takes the words separated by spaces (any case) and checks the word count, the words and the checksum.

fn u(r) { return match r { ok(v) => v, bad(e) => "ERR:" + e } }

bind start = do {
    bind entropy = "1111111111111111111111111111111111111111111111111111111111111111"
    bind words = lw_mnemonic_from(entropy)
    print(len(words))
    print(words[0] + " " + words[1] + " " + words[23])
    print(u(lw_mnemonic_to(join(words, " "))) == entropy)
    print(u(lw_mnemonic_to("abandon abandon")))
}
24
baby mass cake
true
ERR:a recovery phrase has exactly 24 words

Ring signatures and proof of work

LRS-87 ring signatures (lw_ring_sign) are marked experimental in the source. Use them for research and prototypes, not for assets you can’t afford to lose. lw_pow_hash allocates a 16 MiB scratchpad and is slow on purpose. lw_meets_difficulty accepts the difficulty as a number, or as a decimal string for values above 2^53.

See also

AI and Language Models

Ling has machine intelligence at three sizes. Each runs on your own machine; nothing is sent to a hosted service.

FamilyWhat it doesNeeds
nn_*Small feed-forward neural networks you train in a loopai profile
bt_*Behaviour trees for game charactersai profile
dialog_* (learning)A tiny language model that learns a character’s voiceai profile
stt_*Speech to text with Whisperai profile, plus a Whisper model
llm_*Chat with a local GGUF model (Qwen3, GLM-4)opt-in llm feature, plus a model file
vision_*Questions about an image (Moondream2)opt-in vision feature, plus a model file

The default install (full) includes the ai profile. llm and vision are not part of full; install them explicitly, for example cargo install ling-lang --features llm (llm-cuda for an NVIDIA GPU). In a build without them, calls to llm_* and vision_* evaluate to ().

Two things don’t exist, even though you may see the names elsewhere: there is no ai_chat or ai_embed builtin, and there is no client for hosted model APIs. To call a remote model, use http_post_async from Web Server and HTTP and parse the reply yourself.

Conventions

  • Handles are numbers. nn_new, bt_build, dialog_new, llm_load and vision_load return a small number. A failed load returns -1. A bad handle passed to any other function returns a neutral value ([], 0, "" or false) and never crashes.
  • Number lists such as [0.5, 1] are converted to 32-bit floats inside. Non-numbers are skipped.
  • Long jobs are polled. stt_start, llm_generate_start and vision_analyze_start return a job id at once and work on a background thread. Check on them in a loop with sleep(ms).

Neural networks: nn_*

A dense feed-forward network: give the number of inputs, add layers, then call nn_train once per example. Training is plain stochastic gradient descent with a squared-error loss, cheap enough to run every frame. The seed you pass to nn_new makes results reproducible.

Builtin中文日本語한국어ไทยPurpose
nn_new(n_inputs, seed)建神经网ニューラル作成신경망생성สร้างโครงข่ายEmpty network taking n_inputs numbers
nn_dense(net, units, activation)密集层密層追加밀집층ชั้นหนาแน่นAppend a fully connected layer
nn_forward(net, inputs)神经前向順伝播순전파ส่งต่อโครงข่ายRun the network; returns a list
nn_train(net, inputs, targets, rate)训练网ニューラル学習신경망학습ฝึกโครงข่ายOne training step; returns the loss
nn_save(net, path)保存网網保存신경망저장บันทึกโครงข่ายSave in the LNN1 format
nn_load(path)载入网網読込신경망불러오기โหลดโครงข่ายLoad a saved network, or -1

Building and training

  • nn_new(n_inputs, seed): both default to 1.
  • nn_dense(net, units, activation): activations are "relu" (default), "tanh", "sigmoid", or anything else for linear. The last layer’s width is the output size.
  • nn_forward(net, inputs): shorter input lists are padded with zeros, longer ones cut.
  • nn_train(net, inputs, targets, rate): rate defaults to 0.01. Returns the loss before the update. Loop over your whole data set for many rounds.

This network learns XOR:

bind start = do {
    bind net = nn_new(2, 7)
    nn_dense(net, 8, "tanh")
    nn_dense(net, 1, "sigmoid")
    for round in 0..2000 {
        nn_train(net, [0, 0], [0], 0.5)
        nn_train(net, [0, 1], [1], 0.5)
        nn_train(net, [1, 0], [1], 0.5)
        nn_train(net, [1, 1], [0], 0.5)
    }
    print(nn_forward(net, [0, 1])[0] > 0.9)
    print(nn_forward(net, [1, 1])[0] < 0.1)
}
true
true

Saving

nn_save(net, path) writes a small little-endian file (default "model.lnn") and returns true. nn_load(path) returns a new handle, or -1 if the file is missing or invalid. The format has no checksum or signature, so don’t load .lnn files from untrusted sources.

Behaviour trees: bt_*

A behaviour tree is the decision layer of a game character. You write it in a small text language and tick it against a blackboard of number facts (health, distance, ammo). A tick returns the name of the chosen action; your program decides how to carry it out.

selector {                  # try children in order until one succeeds
    sequence {              # every child must succeed
        ?enemy_visible > 0  # condition on a blackboard fact
        ?ammo >= 1
        !attack             # action
    }
    !patrol                 # fallback
}

Composites are selector, sequence, parallel (succeeds if all children do) and not <child>. Conditions are ?key OP value with >, <, >=, <=, == and !=. A key that was never set reads as 0. Comments start with #.

Builtin中文日本語한국어ไทยPurpose
bt_build(spec)建行为树行動木構築행동트리구성สร้างต้นไม้พฤติกรรมCompile a tree, or -1 on a syntax error
bt_set(tree, key, value)设事实事実設定사실설정ตั้งข้อเท็จจริงSet a blackboard fact
bt_tick(tree)行为树滴答行動木更新행동트리틱เดินต้นไม้พฤติกรรมRun once; returns the action name or ""
bt_status(tree)行为树状态行動木状態행동트리상태สถานะต้นไม้พฤติกรรมLast result: 0 failure, 1 success, 2 running
bind start = do {
    bind brain = bt_build("selector { sequence { ?enemy_visible > 0 ?ammo >= 1 !attack } sequence { ?enemy_visible > 0 !flee } !patrol }")
    print(bt_tick(brain))
    bt_set(brain, "enemy_visible", 1)
    bt_set(brain, "ammo", 5)
    print(bt_tick(brain))
    bt_set(brain, "ammo", 0)
    print(bt_tick(brain))
}
patrol
attack
flee

Dialog learning: dialog_*

These builtins give a character a miniature neural language model. It learns the cadence and vocabulary of the lines you train it on and writes fresh lines in that voice. It is tiny (kilobytes, one CPU core) and will repeat phrases from a small corpus. The dialog_show family of dialog boxes is a different, game-profile feature.

Feed it lines one at a time with dialog_learn, or a whole file in the Ling Dialog format (.lingdialog), where = label starts a conversation and speaker: text is one turn:

= welcome
bram: welcome traveler rest your boots
hero: any news from the road
bram: bandits on the north pass

Only the text of each turn is used for training. Text is lower-cased and split into words.

Builtin中文日本語한국어ไทยPurpose
dialog_new(context, embed, hidden, seed)建对话模型対話モデル作成대화모델생성สร้างโมเดลสนทนาUntrained model (defaults 3, 32, 64, 1)
dialog_learn(model, text)对话学习対話学習대화학습เรียนรู้สนทนาAdd one line of training text
dialog_load(model, path)对话载入対話読込대화불러오기โหลดชุดสนทนาAdd a .lingdialog file; returns conversations added
dialog_train(model, epochs, rate)对话训练対話訓練대화훈련ฝึกสนทนาTrain (defaults 20, 0.1); returns the final loss
dialog_say(model, prompt, max_tokens, temperature)对话生成対話生成대화생성พูดสนทนาGenerate a line (defaults 24, 0.8)
dialog_save(model, path)对话存模対話モデル保存대화모델저장บันทึกโมเดลสนทนาSave the trained model
dialog_load_model(path)对话载模対話モデル読込대화모델불러오기โหลดโมเดลสนทนาLoad a saved model, or -1

context is how many previous words the model sees. A temperature of 0 or less always picks the most likely word; higher values are more varied. For a given seed, corpus and arguments, the output is the same every run. If you add text after training, train again.

bind start = do {
    bind npc = dialog_new(3, 16, 32, 1)
    dialog_learn(npc, "welcome traveler rest your boots by the fire")
    dialog_learn(npc, "keep your blade sharp and your purse close traveler")
    print(dialog_train(npc, 40, 0.1) < 2)
    print(len(dialog_say(npc, "welcome traveler", 8, 0.7)) > 0)
}
true
true

Speech to text: stt_*

stt_* transcribes audio files with Whisper, locally. It uses the built-in Whisper engine when the llm feature is present and a model is installed; otherwise it runs faster-whisper in Python. To set up the Python route once:

python -m venv venv
venv/bin/pip install faster-whisper
huggingface-cli download Systran/faster-whisper-small

Set LING_STT_PYTHON to that Python, or create the venv in Ling’s default folder (%LOCALAPPDATA%\LingStation\stt\venv on Windows, ~/.local/share/lingstation/stt/venv elsewhere). Models are read from the local Hugging Face cache; no network is used.

BuiltinPurpose
stt_available()true if a Whisper engine can run
stt_models()Installed models as a flat list [name, size_mb, ...]
stt_start(audio, model, lang, words)Start a job; returns its id, or "" if it can’t start
stt_poll(job)Progress from 0 to 1
stt_done(job)true when the job has finished
stt_error(job)"", or why the job failed
stt_info(job)Status text, such as "loaded small on cuda"
stt_language(job)Detected language code
stt_segments(job)[start, end, text, ...] for the segments so far
stt_words(job)[start, end, word, probability, ...] for the words so far
stt_srt(job, max_chars)SubRip subtitles; cues of at most max_chars characters (default 42, 0 = whole segments)
stt_align(job, lyrics)Time each line of pasted text against what was heard: [start, end, line, ...]
stt_align_srt(job, lyrics)The same, as SubRip subtitles
stt_cancel(job)Stop the job

None of them has a localized alias. stt_start takes a model name (default "small"), a language ("auto" by default, or a code such as "en" or "ja"), and whether to record word timestamps (default true). Times are in seconds.

bind start = do {
    if !stt_available() {
        print("no Whisper engine installed")
    } else {
        bind job = stt_start("interview.wav", "small", "auto", true)
        while !stt_done(job) {
            print(stt_poll(job))
            sleep(500)
        }
        if stt_error(job) == "" {
            print(stt_language(job))
            write_file("interview.srt", stt_srt(job, 42))
        }
    }
}

Local language models: llm_*

llm_* runs a chat model inside the ling process. It loads a quantised GGUF checkpoint plus its tokenizer.json, on the CPU or a CUDA GPU. Supported architectures are qwen3 and glm4. Needs the opt-in llm feature (llm-cuda for GPU).

Generation never blocks your program: llm_generate_start returns a job id at once, and you poll llm_generate_poll for the text so far. This matters most inside web handlers, where a long generation would stall every visitor.

Conversation history is one string in this format, ending with a user turn:

<|user|>
What is a lens?
<|assistant|>
A curved piece of glass that bends light.
<|user|>
And a mirror?
BuiltinPurpose
llm_load(gguf_path, tokenizer_path, device)Load a model; device negative for CPU, else a CUDA index. Returns a handle or -1
llm_generate_start(model, system_prompt, history, max_tokens, temperature, top_p)Start a reply (defaults 512, 0.7, 0.9); returns a job id
llm_generate_poll(job)The text generated so far
llm_generate_done(job)true when finished
llm_job_status(job)"pending" or "done"
llm_job_cancel(job)Mark the job done (see the note)
llm_job_tool_name(job), llm_job_provide_tool_result(job, text)Reserved for tool calling; not implemented yet

None of them has a localized alias.

bind start = do {
    bind model = llm_load("models/Qwen3-0.6B-Q8_0.gguf", "models/tokenizer.json", 0 - 1)
    if model < 0 {
        print("could not load the model")
    } else {
        bind job = llm_generate_start(model, "Answer in one sentence.", "<|user|>\nWhy is the sky blue?\n", 128, 0.7, 0.9)
        while !llm_generate_done(job) {
            sleep(250)
        }
        print(llm_generate_poll(job))
    }
}

Notes:

  • Loading reads the whole model into memory and can take seconds. Load once at start-up.
  • Only one generation runs at a time per model.
  • llm_job_cancel only marks the job as done. The generation keeps running in the background until it reaches max_tokens, so keep max_tokens modest.
  • There is no moderation layer. Filter output before you show it to untrusted users, and never pass model output straight to files, SQL or commands.

Image understanding: vision_*

vision_* answers questions about an image with a quantised Moondream2 model. It works like llm_*: load once, then poll a background job. Needs the opt-in vision feature (which includes llm). It does not do text recognition (OCR).

BuiltinPurpose
vision_load(gguf_path, tokenizer_path, device)Load the model; returns a handle or -1
vision_analyze_start(model, image_base64, question, max_tokens, temperature, top_p)Start a job (defaults "Describe this image.", 256, 0.7, 0.9)
vision_analyze_poll(job)The text produced so far
vision_analyze_done(job)true when finished, successfully or not
vision_analyze_error(job)"", or why it failed

The image goes in as a base64 string of PNG or JPEG bytes, because Ling strings can’t hold raw bytes. From a web page, post canvas.toDataURL() and strip the data:image/png;base64, prefix.

bind start = do {
    bind model = vision_load("models/moondream2-q4.gguf", "models/moondream-tokenizer.json", 0 - 1)
    bind job = vision_analyze_start(model, read_file("shot.b64"), "What is on the screen?", 128, 0.2, 0.9)
    while !vision_analyze_done(job) {
        sleep(250)
    }
    if vision_analyze_error(job) == "" {
        print(vision_analyze_poll(job))
    }
}

See also

The ling Command

ling runs, builds, draws and converts Ling programs. This page lists every subcommand and option. For a gentler introduction, start with Running Programs.

ling run [--interp|--wasm|--O0|--O1|--O2|--O3] <file.ling>
ling <file.ling>                       (shorthand for: ling run <file.ling>)
ling build <file.ling|dir> [--out dir] [--platform list] [--icon file] [--pack] [--aot]
ling ast [path] [--technical|--artwork|--ling|--all] [--out dir]
ling visualize <file.ling>
ling convert <asset> [-o out.ling] [--no-compression]
SubcommandPurpose
runRun a program (JIT by default).
buildCompile a file or project into a distributable for one or more platforms.
astDraw the syntax tree of a file or project as SVG files.
visualizeWrite one SVG of a file’s syntax tree to standard output.
convertTurn an asset (model, sound, MIDI, SVG) into an importable .ling file.

Running ling with no arguments, or with anything it doesn’t recognise, prints the usage text and exits with status 0. The first line shows the version. There is no --version or --help flag, and there are no check, fmt, translate or test subcommands.

A source file can use any of the extensions .ling, .灵, .霊, .령 or .ลิง.

ling run

Parses the file, finds the entry point and runs it.

FlagEffect
(none)Cranelift JIT, the default. Falls back to the interpreter for the whole program if the JIT can’t compile it.
--interpTree-walking interpreter. The semantic reference, with the best error messages.
--wasm (or --web)Builds the program to WebAssembly, serves it locally and opens the browser. Needs lingc next to ling.
--O0 --O1 --O2 --O3JIT optimisation level (default --O3). Lower it if a very large program compiles slowly.

Flags can come before or after the file name; the first argument with a Ling extension is the program. Arguments after it are left for the program to read with get_args() and cli_arg(name, default).

Things worth knowing:

  • Programs that call http_serve or lingtp_serve (or a localized alias such as เว็บเสิร์ฟ) run on the interpreter automatically, because the JIT doesn’t support closure arguments yet. The ling file.ling shorthand skips this check, so use ling run for servers.
  • On the JIT, an unknown function returns () silently. The interpreter reports unknown function. See Known Limits.
  • A file without an entry point is treated as a library and fails with error[runtime]: no entry point.
  • For a source file in another language, ling prints [detected language: ...] to standard error before running.
  • A missing file prints [ling] error: file does not exist: <path>. Parse errors are error[parse]: ..., runtime errors are error[runtime]: ... with a traceback. All of these exit with status 1.

ling build

Compiles a program or a project into a distributable.

OptionMeaning
<target>A .ling file or a directory (default .). A directory is read through its manifest (灵符.toml, ลิงฟู.toml, then Ling.toml). Without one, ling looks for main.ling, start.ling, 启.灵, เริ่ม.ลิง, a src folder, or any .ling file.
--out <dir>Output folder, default dist. Each platform goes in a sub-folder such as dist/web or dist/windows.
--platform <list>Comma-separated targets, listed below. all means win,lin,mac,web.
--icon <file>App icon (.svg, .png, .jpg, .bmp, .ico), overriding the manifest’s icon.
--packEmbed the [includes] resources and the program in the executable, so it is one self-contained file.
--aotCompile ahead of time to native code instead of embedding the interpreter.
PlatformAliasesOutput
webWebGL/WebAssembly bundle, built by lingc
winwindowsWindows executable
linlinuxLinux executable
macmacos, darwinmacOS (Intel) executable
macarmmac-arm, mac-arm64, macos-arm64, apple-siliconmacOS (Apple Silicon) executable
piospi, raspios, linux-arm64, linarm, arm64Raspberry Pi OS / 64-bit ARM Linux
kernelbareLingOS bare-metal kernel image (os profile)
rpiraspberrypiLingOS image for Raspberry Pi (os profile)
lingosapp, appsLingOS userland app (os profile)
lingos-rpiapps-rpi, app-rpiLingOS userland app for Raspberry Pi (os profile)

Without --platform, the build uses the manifest’s targets, or the host platform plus web if there are none. When the list comes from the manifest, desktop targets your machine can’t build (and cross isn’t installed) are skipped with a note. An explicit --platform fails instead.

Native targets generate and compile a small Rust project, so a Rust toolchain must be installed and the first build can take minutes.

Manifest keys

ling build reads its manifest line by line, not with a full TOML parser. Write every setting on one line as key = value, and keep arrays on a single line.

KeyMeaning
nameProject name, used for the executable.
versionVersion string. Default 0.1.0.
entryEntry program relative to the manifest. Default main.ling.
kindbin (default), web, game, ui, ai, crypto, lib, polyglot, kernel.
iconIcon file.
targetsDefault platforms, e.g. targets = ["win", "lin", "web"].
packpack = true is the same as --pack.
includesResource globs, or an [includes] section with one quoted pattern per line. * matches inside a folder, ** across folders.
ling-featuresCargo features of ling to enable in the executable, e.g. ["web"] for programs that use db_*.
# Ling.toml
[project]
name = "my-game"
version = "1.0.0"
entry = "main.ling"
icon = "images/logo.svg"
targets = ["win", "lin", "web"]
pack = true

[includes]
"/music/*.wav"
"/font/*.otf"
"/levels/**/*.json"

Included files are copied next to the executable in the same layout, or embedded with --pack. File builtins such as read_file work the same either way.

ling ast

Draws the syntax tree of a file or a whole project as SVG. A directory is walked recursively (skipping hidden folders, target, dist, node_modules, AST and 灵碑) and treated as one program.

OptionMeaning
[path]File or directory, default ..
--technical, --artwork, --lingPick one or more drawing styles. With none, all three are made.
--allAll three styles.
--out <dir>Output folder, default AST.
$ ling ast hello.ling
ling ast: 'hello' — 1 file(s), 0 fn(s)
  ✓ AST\hello.technical.svg
  ✓ AST\hello.artwork.svg
  ✓ AST\hello.ling.svg

ling visualize

Writes a single SVG picture of a file’s syntax tree to standard output. Redirect it to a file:

ling visualize hello.ling > hello.svg

It only parses the file, so it is also a quick way to check that a program parses.

ling convert

Turns an asset into a .ling file you can use. See Asset Conversion.

ling convert model.glb -o model.ling

Exit status

ling returns 0 on success and 1 on any reported error.

lingfu

lingfu (灵符, “spirit token”) is Ling’s project manager. It creates projects, runs them and their tests, builds executables, talks to the package registry, and can rewrite a whole project into another human language. For running and building it calls ling, which it finds next to itself or on your PATH.

lingfu <command> [arguments]
lingfu --help | -h | help
lingfu --version | -V | version

lingfu finds the project by searching the current folder and its parents for a manifest: Ling.toml, 灵符.toml, 霊符.toml, 영부.toml or ลิงฟู.toml.

Commands at a glance

CommandAliasesPurpose
new <name>createCreate a project folder.
initinitializeCreate a project in the current folder.
runexecute, startRun the project.
testverifyRun the project’s tests.
buildcompile, makeBuild a native executable.
cleanpurge, clearDelete build output.
treestructure, lsPrint the project tree.
manifestshow, infoPrint the manifest.
normalize <lang>norm, localizeRewrite the project into another language.
add <package>install, includeInstall a package from the registry.
search <query>find, seekSearch the registry.
publishrelease, sharePublish the project.
login <api-key>sign-in, authSave registry credentials.
logoutsign-out, deauthForget credentials.
docdocs, documentBuild documentation.
bench, updateRun cargo bench / cargo update.
wizardguide, create-wizardInteractive project creator.
seedIntegrity fingerprint of the project.
ast, convertForwarded to ling ast / ling convert.
check, fmt, translateDon’t use these yet (see below).

Common options: --lang/-l <code> (scaffolding language: en, zh, ja, ko, th, ru), --type/-t <kind>, --root-lang <code>, --crates, --path <dir>, --dry-run/-n.

Each command also has names in other languages, for example 试 for test in Chinese or ทดสอบ in Thai. These only work when the executable itself has the localized name (such as 灵符.exe or ลิงฟู). Under the name lingfu, use the English commands.

lingfu new and lingfu init

lingfu new <name> [--type bin|lib|game|ui|ai|crypto|web|polyglot] [--lang en|zh|ja|ko|th|ru]

Creates <name>/ with a manifest, a source folder with an entry program, a tests folder, a lexicon folder, README.md, .gitignore and ling.ignore. lingfu init does the same in the current folder, using its name as the project name.

--lang picks the language of the generated files and of the folder names:

LanguageManifestSourcesEntryTestsBuild
EnglishLing.tomlsrcstart.lingtestsbuild
Chinese灵符.toml灵源启.灵灵镜灵碑
Japanese霊符.toml霊源啓.霊霊鏡霊碑
Korean영부.toml령원시작.령령경령비
Thaiลิงฟู.tomlต้นกำเนิดเริ่ม.ลิงทดสอบสร้าง

The manifest has the tables [spirit] (name, kind, version, optional entry), [author], [realm] (language, level, source), [root] (the core dependency) and [depends]. See Running Programs for an example.

lingfu run

Runs the project’s entry program with ling run. The entry is the first file that exists among: the manifest’s entry, <src>/<entry file>, <root>/<entry file>, <src>/main.ling and <root>/main.ling. Extra arguments are passed to ling run.

$ lingfu run
Running ...\demo\src\start.ling...
🌊 Welcome to demo Spirit Realm 🌊
Spirit Level: 铁

lingfu test

Runs every .ling file under the tests folder with ling run, stopping at the first one that fails. A test is an ordinary program with an entry point (any bind of a do block counts).

$ lingfu test
Testing Ling project...
  test: ...\demo\tests\test.ling
✨ All mirrors are clear ✨
🔮 Ling tests passed for demo
✓ All tests passed!

Tests run on the JIT, which doesn’t stop on an unknown function, so a broken test can still “pass”. Have each test print a clear PASS or FAIL line, or run it yourself with ling run --interp. Helper files inside the tests folder are treated as tests too.

lingfu build

Calls ling build <project> --aot and passes on --out, --platform, --icon and --pack. --no-aot embeds the interpreter instead; --path <dir> picks the project folder. If a Cargo.toml sits next to the manifest, it runs cargo build instead.

Before your first build, add entry = "src/start.ling" under [spirit]. Otherwise ling build looks for main.ling and stops with entry '...' not found. Building needs a Rust toolchain; see The ling Command.

lingfu clean, tree, manifest

  • clean deletes the build and lock folders (build and .lock, or their localized names) and runs cargo clean if there is a Rust crate.
  • tree prints the project’s folder tree.
  • manifest prints the manifest’s path and contents.

lingfu normalize

lingfu normalize <lang> [--dry-run|-n] [--content-only] [--files-only]

Rewrites the whole project in the current folder into one human language. It translates keywords and builtin names in every source file, renames source files and the standard folders, and fixes imports to match. <lang> is a code such as en, zh, ja, ko or th (names like chinese or 中文 work too). Without it you get a menu.

OptionEffect
--dry-run, -nList the changes without touching anything.
--content-onlyRewrite file contents, keep the names.
--files-onlyRename files and folders, keep the contents.
$ lingfu normalize zh --dry-run
Normalizing to Chinese  [dry-run]
  ~ lexicons\en.ling
  ~ src\start.ling
  ~ tests\test.ling
  mv tests\test.ling → tests\测试.ling
  mv build → 构建
  mv src → 源码
  mv tests → 测试

Dry run complete — no files changed.
  ✓ 3 file(s) rewritten
  ~ 1 file(s) renamed
  ↕ 3 folder(s) renamed

Warning: normalize rewrites every Ling file in the folder, in place. Commit your project (or make a copy) and do a dry run first.

Identifiers, comments and text inside strings are left as they are; only keywords and builtins change. normalize also uses its own folder names (源码, 测试, 构建), which differ from the ones lingfu new --lang zh creates.

lingfu check, fmt, translate

These commands exist but call ling subcommands that don’t exist (ling check, ling fmt, ling <from> <to> <file>). check and fmt report success without doing anything, and translate prints ling’s usage text. To change a project’s language, use lingfu normalize.

Registry commands

The registry is https://fu.ling-lang.org by default. Set LINGFU_REGISTRY to use another one.

CommandWhat it does
login <api-key>Saves the key to ~/.lingfu/credentials.toml.
logoutRemoves the saved credentials.
publishPacks the project as .tar.gz, skipping files listed in ling.ignore, and uploads it. Needs login.
search <query>Searches the registry. With --crates, searches crates.io instead.
add <package>Downloads a package into ./ling_modules/<name>/ and prints the use line to import it. With --crates, runs cargo add.

lingfu doc, bench, update

doc runs mdbook build if there is a docs/book.toml or book/book.toml, and cargo doc --no-deps otherwise. bench and update run cargo bench and cargo update; they are useful only in projects that contain a Rust crate.

lingfu seed

Makes an encrypted integrity fingerprint of a git project: a BLAKE3 Merkle root of every tracked file, written as a playable seed.wav. --check compares the project against a saved seed. It needs a git repository.

lingfu wizard

An interactive questionnaire (language, project type, name, …) that ends by creating a project like new. It reads from the terminal, so you can’t script it.

Exit status

lingfu returns 0 on success. On failure it prints Error: <message> (for example build failed or tests failed) and returns 1.

Asset Conversion

ling convert turns an external asset (a 3D model, a sound, a MIDI song or an SVG drawing) into a self-contained .ling file. You use that file in your program, and it rebuilds the asset with Ling’s own builtins. No loader or file at run time is needed.

ling convert model.glb                  # writes model.ling (compressed, lossless)
ling convert sfx.wav -o sfx.ling        # choose the output path
ling convert logo.svg --no-compression  # plain arrays you can read and diff
lingfu convert song.mid                 # lingfu forwards to ling convert
OptionMeaning
-o <out.ling> (or --out)Output path. Default: the input name with .ling.
--no-compressionWrite numbers as plain lists instead of compressed blobs.

What each format becomes

InputGenerated bindingsProfile
.gltf, .glbPer mesh: <name>_<mesh>_pos, _nrm, _uv, _idx, and a wireframe draw_<name>_<mesh>(ox, oy, oz, scale). draw_<name>(ox, oy, oz, scale) draws the whole model. Node names and transforms are kept as comments.game
.wav, .ogg, .flac, .mp3<name>_pcm (mono samples), <name>_rate, <name>_duraudio
.mid, .midi<name>_notes, a flat list of [time, dur, midi, vel, channel] per note, and <name>_duraudio
.svg<name>_xy (points), <name>_lens (points per polyline), and draw_<name>(ox, oy, scale)any
.blendExported to glTF by Blender, then converted like a .glb. Needs Blender on your PATH or in $BLENDER.game

<name> is the input file name, cleaned up to be a valid identifier. For SVG, <path> data (M, L, H, V, C, Q, Z) and <line>, <rect>, <polyline> and <polygon> elements are turned into polylines. Any other extension fails with unsupported extension.

Compressed or plain

By default, long lists of numbers are stored losslessly as zlib-compressed, base64 text behind two builtins:

  • blob_f32("...") decodes to a list of numbers (little-endian 32-bit floats).
  • blob_i32("...") decodes to a list of whole numbers (32-bit integers), used for indices and lengths.

--no-compression writes the same numbers as a literal [ ... ] list. The file is larger but easy to read. Lists of eight numbers or fewer are always written plainly.

Example: an SVG

Given a small logo.svg with one <rect> and one <path>:

$ ling convert logo.svg
[convert] logo.svg → logo.ling  (1 KB, deflate+base64 lossless)

The generated logo.ling starts like this:

# 2 polylines, 7 points
bind logo_xy = blob_f32("eNpdibENAAAIgzjFV/RmDzTRwaYDAwCRLF2Huvf/A/L0CM0=")
bind logo_lens = [2, 5]

followed by a draw_logo(ox, oy, scale) function. Use it from your program:

use "logo.ling"

bind start = do {
    open_window(400, 400, "Logo")
    while window_is_open() {
        fill(0, 0, 0)
        set_color(255, 255, 255)
        draw_logo(100, 100, 2.0)
        present()
    }
}

Notes

  • Audio is stored as a mono downmix at the source sample rate. The generated file holds the samples; playing or analysing them is up to your program.
  • The generated code uses Thai keywords for its functions (ฟังก์ชัน). That is normal: every language works in every file.
  • A model’s draw function draws a wireframe with draw_line_3d. For solid, textured meshes, see 3D Shapes and Meshes.

Crate Overview

Ling is written in Rust and split into a workspace of crates. The main crate, ling-lang, contains the compiler front end, the interpreter, the JIT driver and the ling command; the crates below supply the language pieces and the builtin libraries. You only need this page if you want to use these crates from your own Rust code, or to understand which crate backs which builtins.

The versions below are the ones in the repository at the time of writing. Most crates follow Ling’s 2030.x numbering; ling-http and ling-web have their own.

The main crate

CrateVersionWhat it is
ling-lang2030.1.53The language: lexer, parser, interpreter, Cranelift JIT and AOT, and the builtins. Library name ling; binaries ling, lingc, lx, ling-repl.
lingfu (crates/ling-fu)2030.1.19The project manager: lingfu new, run, build, normalize and more. See lingfu.

Compiler

CrateVersionWhat it is
ling-core2030.0.9Core types, errors and compiler infrastructure.
ling-lex2030.0.8Lexical analysis and polyglot tokenization.
ling-ast2030.0.8Abstract syntax tree types.
ling-polyglot2030.0.8The lexicon system for keywords and builtins in 16+ human languages.
ling-mir2030.0.12Mid-level intermediate representation for the code generators.
ling-codegen2030.0.13Code generation backends (bytecode, WASM, native).
ling-macro2030.0.8Procedural macros for the Ling ecosystem.
ling-runtime2030.0.8Runtime support: garbage collector, allocator, standard library.
ling-wasm2030.0.16The WebGL2 WebAssembly runtime used by ling build --platform web.

Graphics, UI and input

CrateVersionWhat it is
ling-graphics2030.0.133D/4D rendering, geometry, animation and font tools.
ling-gl2030.0.10GPU rasteriser for projected scenes (wgpu: Vulkan, Metal, DX12; WebGL2 on wasm).
ling-gpu2030.0.10GPU compute (CUDA via cudarc, with a CPU fallback).
ling-ui2030.0.9Retained-mode widgets and flex layout (ui_*).
ling-animation2030.0.8Anima, the unified animation system: one rig, any target.
ling-input2030.0.9Sensorium: gamepads, joysticks, haptics, motion, XR controllers, touch controls.
ling-paint2030.0.1LingAnime paint engine: layers, brushes, vectors, halftone, 2.5D rigs, pen tablets (art_*).
ling-icon2030.0.9Rasterizes SVG/PNG icons to multi-resolution .ico and embeds them in Windows executables (ling build --icon).

Games and physics

CrateVersionWhat it is
ling-game2030.1.9Game engine: ECS, physics and scene management.
ling-physics2030.1.18Physics, world generation, hyperbolic geometry, glTF loading.
ling-body2030.0.2Acoustic bodies: humanoid SDF scaffolds, FDTD wave solver, membranes, mesh and WAV codecs.
ling-emu2030.0.1Console-emulation host (emu_*): SNES and N64 cores.

Audio and music

CrateVersionWhat it is
ling-audio2030.0.134D positional audio synthesis and WAV background music.
ling-music2030.0.9Music decoding, BPM and key analysis, synthesis, rhythm-game and karaoke tools.
ling-mic2030.0.12Microphone input and real-time audio capture.
ling-daw2030.0.2DAW engine behind LingStationX: synth, drums, effects, mixer, sequencer.
ling-osdaw2030.0.2LingStation for LingOS: a no_std tracker sequencer and synthesizer.

Network, web and security

CrateVersionWhat it is
ling-http0.1.8HTTPS/JSON/SQLite framework on axum. Ling’s http_serve runs on it. See ling-http and ling-web.
ling-web0.1.9The Flask-style layer on ling-http: sessions, flash messages, templates, static files, blueprints, CSRF.
ling-net2030.0.9Async networking: HTTP, WebSocket, QUIC and peer-to-peer.
ling-crypto2030.1.13Post-quantum and classical cryptography: ML-KEM-768, hybrid KEM, AES-GCM, XChaCha20, BLAKE3, SHA-3, Argon2id, Shamir, Schnorr ZKP, VRF. no_std-capable.

AI

CrateVersionWhat it is
ling-ai2030.0.10Tensors, neural networks and LLM inference.
ling-llm2030.0.2A no_std GGUF inference engine for Qwen3 that runs on the CPU without an operating system (for LingOS).
ling-diffusion2030.0.1In-process Stable Diffusion (SD 1.x / SDXL) behind the sd_* builtins.

LingOS

CrateVersionWhat it is
ling-kernel2030.1.37Minimal kernel runtime: no_std CPU intrinsics, VGA, serial, boot.
ling-user2030.1.4Userland runtime for Ling programs on LingOS.

Bindings

CrateVersionWhat it is
ling-py2030.0.8Python bindings for ling-audio, ling-physics and ling-net.

Which profile pulls in which crate

The install profiles decide which of these crates are compiled into ling:

ProfileCrates
webling-http, ling-crypto, ling-icon, lingfu
privacyweb plus ling-net, ling-ui
gameling-physics, ling-gpu, ling-game, ling-animation, ling-input, ling-body, ling-ui, ling-icon
ailing-ai, ling-music
audioling-audio, ling-music, ling-mic, ling-daw
art (in full)ling-paint

ling-http and ling-web

ling-http and ling-web are the Rust crates under Ling’s web support. Ling’s own http_serve builtin runs on ling-http. You can also use both crates directly from Rust when a service outgrows what Ling’s builtins offer: sessions, templates, JSON bodies of real shape, or many requests in flight at once.

  • ling-http (灵网, 0.1.8): an axum toolkit with a pooled SQLite handle, a uniform JSON error type, CRUD routing and HTTP/HTTPS serving.
  • ling-web (灵网站, 0.1.9): a Flask-style layer on top: server-side sessions, flash messages, templates, static files, blueprints and CSRF protection.

Ling programs can’t call ling-web (it has no builtins), and a Rust service can’t run a .ling file as a handler. The two share crates and conventions, not a runtime. To write a small API in Ling itself, see A Small Web Service and Web Server and HTTP.

Ling or Rust?

ConcernLing (http_serve)Rust with ling-http / ling-web
ConcurrencyOne handler at a time on the interpreterAsync handlers on a thread pool
JSON bodiesBuild and parse by handserde structs, Json<T>
Sessions, CSRF, flash, templatesBuild them yourself from db_* and cookiesProvided by ling-web
Response headers and middlewareA fixed setAny header, any tower layer
Edit cycleEdit and ling runCompile with Cargo

A thin API in front of SQLite with a handful of routes fits Ling well. A browser-facing application with logins and templates fits Rust better.

Setting up

Add the crates and Tokio to your Cargo.toml:

[dependencies]
ling-http = "0.1"
ling-web  = "0.1"
tokio     = { version = "1", features = ["rt-multi-thread", "macros"] }
anyhow    = "1"

ling-http re-exports axum, rusqlite, serde_json and tokio, so you can write ling_http::axum::... and never get a version mismatch with the crate’s own axum.

ling-http

ItemWhat it does
Db::connect(path), Db::connect_memory()Open a pooled SQLite database (async).
db.with_conn(|conn| ...)Run a closure on a pooled rusqlite::Connection on a blocking thread. Errors become HttpError, so you can use ?.
db.run_migrations(&[(name, sql), ...])Apply migrations in order, recording them in a _migrations table.
HttpError, Result<T>Error type that turns into a JSON body {"error": "..."} with a matching status (NotFound, BadRequest, Unauthorized, Forbidden, Conflict, Database, Pool, Internal).
Resource trait, resource::<R>(path)Implement index, show, create, update, destroy once and get the five CRUD routes.
App::new(), .merge(...), .with_state(...)A router builder with tracing, a 60 s timeout, a 25 MiB body limit and permissive CORS.
serve_http(router, addr)Serve plain HTTP (use behind a TLS-terminating proxy).
serve_tls(router, addr, cert_pem, key_pem)Serve HTTPS with a certificate and key from disk.
serve_dev_tls(router, addr)HTTPS with a throwaway self-signed certificate. Local development only; needs the dev-certs feature.

A minimal JSON service with a SQLite counter:

use ling_http::axum::{extract::State, routing::get, Json, Router};
use ling_http::{serde_json, Db};
use std::net::SocketAddr;

const MIGRATIONS: &[(&str, &str)] = &[(
    "0001_init",
    "CREATE TABLE visits(id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL DEFAULT (datetime('now')));",
)];

#[derive(Clone)]
struct AppState {
    db: Db,
}

async fn health() -> Json<serde_json::Value> {
    Json(serde_json::json!({ "status": "ok" }))
}

async fn visit(State(state): State<AppState>) -> ling_http::Result<String> {
    let n: i64 = state
        .db
        .with_conn(|conn| {
            conn.execute("INSERT INTO visits DEFAULT VALUES", [])?;
            conn.query_row("SELECT COUNT(*) FROM visits", [], |row| row.get(0))
        })
        .await?;
    Ok(format!("visit number {n}\n"))
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let db = Db::connect("app.db").await?;
    db.run_migrations(MIGRATIONS).await?;

    let router: Router = Router::new()
        .route("/health", get(health))
        .route("/visit", get(visit))
        .with_state(AppState { db });

    let addr: SocketAddr = "127.0.0.1:8080".parse()?;
    ling_http::serve_http(router, addr).await
}

Warning: App::new() adds its middleware to an empty router. In axum, a layer only wraps the routes that exist when you call .layer(...), so routes merged in afterwards don’t get the timeout, body limit or CORS policy. The Ling Book’s tests confirmed this for CORS. Add your own tower-http layers to the final router, after all routes are merged.

HttpError::Database passes the database’s own message to the client (for example database error: Query returned no rows). For a public API, map errors to your own type so internal details stay on the server.

ling-web

ItemWhat it does
session_layer(&db, secure)SQLite-backed sessions: an opaque ling_session cookie, HttpOnly, SameSite=Lax, 7-day sliding expiry. Pass secure = true when serving HTTPS.
SessionExtractor for handlers: get, insert, remove, …
csrf::csrf_token(&session), csrf::verify_csrf(&session, token)A per-session CSRF token and a constant-time check.
flash::flash(&session, category, message), flash::take_flashes(&session)One-time messages for the next page.
Templates::load(dir), templates.render(name, ctx)minijinja (Jinja2-syntax) templates; build ctx with minijinja::context!.
blueprint(prefix, router)Group routes under a URL prefix.
serve_static(prefix, dir)Mount a folder of static files.

A page that counts your visits in the session:

use ling_http::axum::{routing::get, Router};
use ling_http::Db;
use ling_web::Session;
use std::net::SocketAddr;

async fn index(session: Session) -> String {
    let visits: u32 = session.get::<u32>("visits").await.unwrap_or(None).unwrap_or(0) + 1;
    let _ = session.insert("visits", visits).await;
    format!("You have been here {visits} time(s).\n")
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let db = Db::connect_memory().await?;
    let sessions = ling_web::session_layer(&db, false).await?;

    let router: Router = Router::new()
        .route("/", get(index))
        .merge(ling_web::serve_static("/static", "./static"))
        .layer(sessions);

    let addr: SocketAddr = "127.0.0.1:8080".parse()?;
    ling_http::serve_http(router, addr).await
}

Add the session layer after the routes it serves; handlers that take a Session fail at request time otherwise. Add your own middleware after that, so it sees every response.

Examples in the repository

  • crates/ling-http/examples/hello.rs: a SQLite-backed notes CRUD resource with a health check, over HTTP or HTTPS: cargo run -p ling-http --example hello --features dev-certs -- --port 6666
  • crates/ling-web/examples/guestbook.rs: sessions, flash messages, CSRF-protected forms and templates: cargo run -p ling-web --example guestbook -- --port 7777

The chapter “Web Apps with the Rust Crates” in Mastering Ling (Ling Book) builds a complete application with accounts, sessions, templates and a JSON API.

Overview

This glossary lists Ling’s keywords, types, literals and builtins with their spelling in English, 中文, 日本語, 한국어 and ไทย. In the tables, the column for your language is shown next to English. The pages are generated from the lexicon files (lexicons/*.ling) by docs/gen_glossary.py.

  • 40 keywords · 6 types · 334 builtins in 12 crates
PageContents
KeywordsReserved words and what each one really does
TypesThe type names
Literals and OperatorsHow to write values, and the operators
Builtins by CrateBuiltin names, grouped by the crate they come from

The lexer accepts a few extra spellings that are not in the lexicon files. For the full story of each keyword, see Keywords in the Language Guide. The glossary lists only builtins that have names in the lexicon files; the Builtins Reference covers many more.

Keywords

Reserved words and their spelling in each language. Some are reserved but do nothing yet; the description says so. See Keywords for examples.

English中文日本語한국어ไทยDescription
bind令束縛바인드ผูกBind a value or function to a name. Binding the same name again updates it.
do执実行실행ทำBlock expression do { … }. Its value is the last expression.
fn函関数함수ฟังก์ชันDeclare a named function.
mod核モジュール모듈โมดูลDeclare a module (a namespace of functions).
type符型타입ชนิดType alias. Parsed, no effect.
if若もし만약ถ้าConditional branch.
else否他아니면มิฉะนั้นAlternative branch of if.
while循間동안ขณะที่Loop while a condition holds.
for历繰위해สำหรับLoop over a range, list or text.
in于の中안에ในSeparates the loop variable from the sequence: for x in 0..10.
match配一致매치ตรงกับPattern matching.
return归戻る반환คืนค่าLeave the function with a value.
own独所有소유เป็นเจ้าของOwnership marker. Parsed and ignored; nothing is checked.
lend借貸す빌려ให้ยืมOwnership marker. Parsed and ignored; nothing is checked.
share共共有공유แบ่งปันOwnership marker. Parsed and ignored; nothing is checked.
move移移動이동ย้ายOwnership marker. Parsed and ignored; nothing is checked.
copy复複製복사คัดลอกOwnership marker. Parsed and ignored; nothing is checked.
async异非同期비동기อะซิงค์Asynchronous marker. Parsed and ignored; code runs synchronously.
wait待待つ기다려รอMeant as “await”. Unreliable; avoid it.
as为として로서เป็นNames an imported module: use "file" as m.
wherewherewherewherewhereConstraint clause after a function signature. Skipped, no effect.
post出投稿게시ส่งReserved word; has no effect.
give予渡す전달ให้Reserved word; has no effect.
fitfitfitfitจับคู่Reserved word; has no effect.
form形形형태รูปแบบDeclare a record type.
choose选選ぶ선택เลือกDeclare an enumeration with variants.
can能できる가능สามารถReserved word; has no effect.
change变変える변경เปลี่ยนแปลงReserved word; has no effect.
stop止停止멈춤หยุดReserved word; has no effect. Ling has no break.
again继続ける계속ทำอีกReserved word; has no effect. Ling has no continue.
try试試す시도ลองNot syntax: the builtin try(closure) turns a runtime error into bad(...).
sure确確か확실แน่นอนReserved word; has no effect.
maybe或多分아마도อาจจะReserved word; has no effect.
pure纯純粋순수บริสุทธิ์Reserved word; has no effect.
spawn启起動생성สร้างReserved word; has no effect. Use thread_spawn for threads.
ok可良い좋아ตกลงSuccess result ok(value); also a match pattern.
bad误悪い나쁨ผิดพลาดFailure result bad(reason); also a match pattern.
none无なし없음ไม่มีNot defined. Use () for “nothing”.
start始開始시작เริ่มUsual name of the entry point: bind start = do { … }. A name, not a keyword.
result果結果결과ผลลัพธ์Listed in the lexicon only; the lexer treats it as a name.

Types

Ling is dynamically typed. These type names can appear in annotations such as x: number or -> text, but annotations are parsed and ignored. See Types and Values.

English中文日本語한국어ไทยDescription
number数数値숫자จำนวนNumber. Every number is a 64-bit float.
text文文字列문자열ข้อความText (string).
bool布論理논리ตรรกะBoolean: true or false.
list列リスト목록รายการList; mixed types, indexed from 0.
map图マップ맵แผนที่No such type exists; the name is documentation only.
tuple元タプル튜플สิ่งอันดับNo such type exists; the name is documentation only.

Literals and Operators

Literals and operators are written the same way in every language, except true and false, which have their own spellings.

Literals

LiteralMeaning
42, 3.14Number. Every number is a 64-bit float. There is no hex or exponent form.
"hello"Text. Double quotes only. Escapes: \n \t \r \" \\ \0. No interpolation.
true, falseBoolean
()Unit, the “nothing” value
[1, "two", 3.0]List; mixed types, indexed from 0
0..5Range, half-open: 0, 1, 2, 3, 4. Used with for.
|x| x + 1Function value (closure)
ok(v), bad(e)Result values

There are no character, map or tuple literals.

Booleans in each language

English中文日本語한국어ไทย
true真真참จริง
false假偽거짓เท็จ

Operators

From the tightest binding to the loosest:

OperatorMeaning
. () [] :: ..Field or method, call, index, path, range
-x !xNegate, logical not
* / %Multiply, divide, remainder
+ -Add, subtract. + also joins text.
== != < > <= >=Compare
&&Logical and
||Logical or

Other symbols: = in bind name = value, => between a pattern and its result in match, and -> before a return type (parsed and ignored). In the interpreter, && and || always evaluate both sides. See Known Limits.

Builtins by Crate

Builtin names in each language, grouped by the crate that provides them. Only builtins that the runtime really provides and that have names in the lexicon files are listed. For parameters and examples, see the Builtins Reference.

ling (core runtime)

Output, math, noise, time, colour helpers and lists. Always available.

English中文日本語한국어ไทย
print印印刷출력พิมพ์
panic慌パニック패닉ตกใจ
hsl_color色相值HSL色値HSL색값สีHSL
trunc截整切り捨て버림ตัดทศนิยม
int取整整数化정수화ตัดทศนิยม
sin正弦正弦사인ไซน์
cos余弦余弦코사인โคไซน์
tan正切正接탄젠트แทนเจนต์
sqrt根平方根제곱근รากที่สอง
abs绝对絶対値절대값ค่าสัมบูรณ์
floor下整床내림ปัดลง
ceil上整天井올림ปัดขึ้น
round四舍四捨五入반올림ปัดเศษ
pow幂べき乗거듭제곱ยกกำลัง
log对数対数로그ลอการิทึม
min最小最小최솟값ต่ำสุด
max最大最大최댓값สูงสุด
clamp截取範囲制限범위제한จำกัด
pi圆周率円周率파이พาย
tau双周率タウ타우ทาว
lerp线性插值線形補間선형보간ค่าระหว่าง
smoothstep平滑步进スムーズステップ스무스스텝เปลี่ยนแบบนุ่ม
rand随机乱数난수สุ่ม
vnoise柏林噪声2Dバリューノイズ2D값노이즈2Dนอยส์2ดี
fbm分形噪声フラクタルノイズ프랙탈노이즈นอยส์ออร์แกนิก
perlin柏林噪声3Dパーリンノイズ3D펄린노이즈3Dเพอร์ลิน3ดี
hsv_to_rgbHSV转RGBHSV変換RGBHSV변환RGBเอชเอสวีเป็นRGB
lerp_color颜色插值色補間색보간ไล่สี
time_now当前时间経過時間현재시간เวลาปัจจุบัน
frame_count帧数フレーム数프레임수เฟรม
len长長さ길이ความยาว
push加追加추가ต่อท้าย
pop弹取出꺼내기ดึงออก
keys键集キー一覧키목록ชุดคีย์
contains含含む포함มีอยู่
time时時刻시간เวลา
sleep眠眠る잠นอนหลับ

ling-graphics

Window, 2D and 3D drawing, shapes, camera, lighting, cel shading, vector textures (vtex_*) and SVG export.

English中文日本語한국어ไทย
open_window开窗ウィンドウ開く창열기เปิดหน้าต่าง
open_fullscreen全屏全画面전체화면เปิดหน้าต่างเต็มจอ
fill填塗り潰し채우기เติม
clear清消去지우기clear
set_color设色色設定색설정สีดินสอ
set_color_hsl色相HSL色HSL색설정สีHSLวาด
present显表示표시แสดงผล
draw_line画线線描く선그리기วาดเส้น
draw_pixel画点点描く점그리기วาดจุด
triangle画三角三角形삼각형วาดสามเหลี่ยม
draw_circle画圆円描く원그리기วาดวงกลม
window_is_open窗开開いている창열림หน้าต่างเปิดอยู่
get_width宽幅取得너비ความกว้าง
get_height高高取得높이ความสูง
monitor_width屏宽画面幅화면너비ความกว้างจอ
monitor_height屏高画面高화면높이ความสูงจอ
monitor_refresh刷新率リフレッシュレート주사율อัตรารีเฟรช
monitor_info屏幕信息画面情報화면정보ข้อมูลจอ
set_fps设帧率フレームレート設定프레임설정ตั้งเฟรมเรต
key_down按键キー押す키누름กดค้าง
key_pressed键按キー押した키눌림กดปุ่ม
mouse_x鼠XマウスX마우스Xเมาส์X
mouse_y鼠YマウスY마우스Yเมาส์Y
mouse_dx鼠ΔXマウスΔX마우스ΔXเมาส์X
mouse_dy鼠ΔYマウスΔY마우스ΔYเมาส์Y
capture_mouse捕鼠マウス捕捉마우스잡기จับเมาส์
draw_mesh画网メッシュ描く메시그리기วาดตาข่าย
draw_triangle_3d画3D三角3D三角形描く3D삼각형그리기วาดสามเหลี่ยม3มิติ
draw_line_3d画3D线3D線描く3D선그리기วาดเส้น3มิติ
set_camera设镜カメラ設定카메라설정ตั้งกล้อง
set_camera_pos镜坐标カメラ座標카메라좌표ตั้งตำแหน่งกล้อง
set_zdist镜距Z距離設定Z거리설정ตั้งระยะห่าง
set_projection投影投影設定투영설정ตั้งโปรเจกชัน
set_ambient环境光環境光設定환경광설정ตั้งแสงรอบข้าง
add_light加灯ライト追加조명추가เพิ่มแสง
clear_lights清灯ライト消去조명초기화ล้างแสง
vtex_grid纹格格子模様격자무늬ลายตาราง
vtex_rings纹环同心円동심원ลายวงซ้อน
vtex_star纹星星模様별무늬ลายดาว
vtex_spiral纹螺螺旋나선ลายเกลียว
vtex_flower纹花花模様꽃무늬ลายดอก
vtex_lotus纹莲蓮模様연꽃무늬ลายดอกบัว
vtex_chakra纹轮輪模様바퀴무늬ลายจักร
vtex_yantra纹咒護符模様부적무늬ลายยันต์
vtex_letter_rain纹字雨文字雨글자비ลายอักษรไหล
vtex_hyperbolic_uv纹曲面双曲線쌍곡선ลายไฮเพอร์โบลิก
vtex_tessellated纹镶嵌網目模様격자망ลายตาข่าย
vtex_halftone纹半调網点模様망점ลายจุด
vtex_spiked_cog纹棘轮歯車模様톱니바퀴ฟันเฟืองหนาม
vtex_torii纹鸟居鳥居도리이ประตูโทริอิ
vtex_pagoda纹塔塔탑เจดีย์
svg_beginSVG开始SVG開始SVG시작เริ่มSVG
svg_rectSVG矩形SVG矩形SVG사각형SVGสี่เหลี่ยม
svg_circleSVG圆SVG円SVG원SVGวงกลม
svg_lineSVG线SVG線SVG선SVGเส้น
svg_polylineSVG折线SVG折れ線SVG꺾은선SVGเส้นหัก
svg_textSVG文字SVG文字SVG글자SVGข้อความ
svg_endSVG结束SVG終了SVG끝จบSVG
set_blend混合模式ブレンドモード블렌드모드โหมดผสม
draw_disc画实心圆塗りつぶし円원채우기วาดวงกลมทึบ
set_alpha设透明アルファ設定투명도설정ตั้งความโปร่งใส
grad_triangle渐变三角グラデ三角그라데삼각สามเหลี่ยมไล่สี
grad_rect渐变矩形グラデ矩形그라데사각สี่เหลี่ยมไล่สี
shadow_blob阴影斑影ブロブ그림자블롭เงาวงรี
cast_shadow投射阴影影を落とす그림자드리우기ทอดเงา
shadow_params阴影参数影設定그림자설정ตั้งค่าเงา
depth_triangle深度三角深度三角形깊이삼각สามเหลี่ยมเรียงลึก
depth_line深度线深度線깊이선เส้นเรียงลึก
set_color_space色彩空间色空間색공간ปริภูมิสี
set_gradient_space渐变空间グラデ空間그라데이션공간ปริภูมิไล่สี
mix_color混合颜色色混合색혼합ผสมสี
set_depth_test深度测试深度テスト깊이테스트ทดสอบความลึก
layer_save图层保存レイヤー保存레이어저장บันทึกเลเยอร์
layer_restore图层恢复レイヤー復元레이어복원คืนเลเยอร์
layer_free图层释放レイヤー解放레이어해제ลบเลเยอร์
set_cull背面剔除背面カリング뒷면컬링ตัดด้านหลัง
cube立方体立方体정육면체ลูกบาศก์
box方块箱상자กล่อง
sphere球体球구ทรงกลม
icosphere二十面球アイコ球아이코구체ทรงกลมเหลี่ยม
dome穹顶ドーム돔โดม
cylinder圆柱円柱원기둥ทรงกระบอก
cone圆锥円錐원뿔กรวย
capsule胶囊カプセル캡슐แคปซูล
torus圆环トーラス토러스ทอรัส
pyramid金字塔ピラミッド피라미드พีระมิด
prism棱柱角柱각기둥ปริซึม
frustum棱台錐台원뿔대กรวยตัด
tetrahedron四面体四面体정사면체ทรงสี่หน้า
octahedron八面体八面体정팔면체ทรงแปดหน้า
dodecahedron十二面体十二面体정십이면체ทรงสิบสองหน้า
icosahedron二十面体二十面体정이십면체ทรงยี่สิบหน้า
gear齿轮歯車톱니바퀴เฟือง
gyro陀螺ジャイロ자이로ไจโร
helix螺旋线らせん나선เกลียว
spring弹簧ばね스프링สปริง
arch拱门アーチ아치ซุ้มโค้ง
stairs楼梯階段계단บันได
star_prism星柱星柱별기둥แท่งดาว
capsule_chain胶囊链カプセル鎖캡슐체인โซ่แคปซูล
mobius莫比乌斯メビウス뫼비우스เมอบีอุส
set_shade_mode设置着色シェード設定셰이드모드ตั้งการแรเงา
set_cel_bands设置色阶セル段数셀밴드ตั้งระดับสี
set_shadow_color设置阴影色影の色그림자색ตั้งสีเงา
set_rim设置边缘光リム設定림라이트ตั้งขอบเรือง
tone_soft色调柔边トーンソフト톤소프트โทนขอบนุ่ม
set_ssao环境光遮蔽アンビエントオクルージョン앰비언트오클루전ตั้งเงาสัมผัส
set_fxaa屏幕抗锯齿画面アンチエイリアス화면안티앨리어싱ลบรอยหยัก
set_bloom泛光ブルーム블룸ตั้งบลูม
light_pool光池ライトプール빛웅덩이แอ่งแสง
light_beam光柱ライトビーム빛기둥ลำแสงไฟ
project_3d投影3D3D投影3D투영ฉาย3มิติ
draw_poly填充多边形ポリゴン塗り다각형채우기เติมรูปหลายเหลี่ยม
sparkle闪光きらめき반짝임ประกาย
orb_shell球壳オーブ殻오브껍질เปลือกทรงกลม
orb_particles球内粒子オーブ粒子오브입자อนุภาคทรงกลม

ling-ui

HUD, meters, controls, game UI widgets and vector fonts.

English中文日本語한국어ไทย
ui_theme界面主题UIテーマ인터페이스테마ธีมส่วนติดต่อ
ui_text界面文字UI文字UI텍스트ข้อความหน้าจอ
ui_frame边框フレーム枠프레임틀กรอบ
ui_bevel斜角框ベベル枠베벨틀กรอบเฉียง
ui_hot热区ホットエリア핫존พื้นที่สัมผัส
ui_radar雷达レーダー레이더เรดาร์
ui_compass罗盘コンパス나침반เข็มทิศ
ui_reticle准星照準조준선เป้าเล็ง
ui_target锁定框ターゲット표적กรอบเป้า
ui_panel面板パネル패널แผง
ui_scanlines扫描线走査線스캔라인เส้นสแกน
ui_bar进度条バー막대แถบ
ui_segbar分段条分割バー분할막대แถบแบ่ง
ui_gauge仪表ゲージ게이지มาตรวัด
ui_ring环表リングメーター링미터วงแหวนวัด
ui_vu音量条VUメーター음량막대มาตรเสียง
ui_spark迷你图スパークライン스파크라인กราฟจิ๋ว
ui_battery电池バッテリー배터리แบตเตอรี่
ui_button按钮ボタン버튼ปุ่ม
ui_toggle开关トグル토글สวิตช์
ui_slider滑块スライダー슬라이더แถบเลื่อน
ui_checkbox复选框チェックボックス체크박스ช่องเลือก
ui_tabs标签页タブ탭แท็บ
ui_progress进度プログレス진행바ความคืบหน้า
ui_tooltip提示框ツールチップ툴팁คำแนะนำ
ui_stepper步进器ステッパー스테퍼ตัวปรับค่า
ui_healthbar血条体力バー체력바แถบพลังชีวิต
ui_cooldown冷却クールダウン쿨다운คูลดาวน์
ui_counter计数器カウンター카운터ตัวนับ
ui_minimap小地图ミニマップ미니맵แผนที่ย่อ
ui_dpad方向键方向パッド방향패드ปุ่มทิศทาง
ui_slotgrid物品格スロットグリッド슬롯격자ช่องไอเทม
ui_vignette暗角ビネット비네트ขอบมืด
ui_gauge3d立体仪表立体ゲージ입체게이지มาตรวัด3มิติ
ui_panel3d立体面板立体パネル입체패널แผง3มิติ
ui_radar3d立体雷达立体レーダー입체레이더เรดาร์3มิติ
ui_sound界面音UI音인터페이스음เสียงปุ่ม
font_load加载字体フォント読込글꼴로드โหลดฟอนต์
font_text字体文本フォント文字글꼴텍스트ข้อความฟอนต์
font_text_fill填充字体フォント塗り글꼴채움เติมฟอนต์
font_text_3d字体3Dフォント3D글꼴3Dข้อความฟอนต์3มิติ
font_width字体宽度フォント幅글꼴너비ความกว้างฟอนต์

ling-audio

Tone synthesis, spatial sound, background music and microphone input.

English中文日本語한국어ไทย
mic_open开麦マイク開く마이크열기เปิดไมค์
mic_peak麦克风峰值マイクピーク마이크피크เสียงพีค
mic_rms麦克风音量マイクRMS마이크RMSเสียงRMS
mic_fft实时频谱リアルタイムFFT실시간FFTวิเคราะห์เสียงสด
audio_tone空间音空間音공간음เสียงโทน
audio_volume总音量マスター音量마스터음량ระดับเสียง
audio_listener听者リスナー청취자ผู้ฟัง
audio_bgm背景乐BGM배경음악เพลงพื้นหลัง
audio_bgm_volume背景音量BGM音量배경음량ระดับเสียงพื้นหลัง
audio_blip提示音ビープ音효과음เสียงบี๊บ
audio_sfx音效空間効果音공간효과음เสียงเอฟเฟกต์
audio_sample_load载入采样サンプル読込샘플로드โหลดตัวอย่างเสียง
audio_sample_play播放采样サンプル再生샘플재생เล่นตัวอย่างเสียง
audio_sample_stop停止采样サンプル停止샘플정지หยุดตัวอย่างเสียง
audio_fx_delay回声ディレイ効果딜레이เสียงสะท้อน
audio_fx_reverb混响リバーブ리버브เสียงก้อง
audio_fx_lowpass低通滤波ローパス저역통과กรองความถี่ต่ำ

ling-music

Music decoding and analysis, GM-style synth, rhythm grading, karaoke and MIDI.

English中文日本語한국어ไทย
music_load载入音乐音楽読込음악로드โหลดเพลง
music_duration音乐时长音楽長さ음악길이ความยาวเพลง
music_bpm节拍速度テンポ템포จังหวะต่อนาที
music_key调性調性조성คีย์เพลง
music_onsets音符起点オンセット온셋จุดเริ่มเสียง
music_beat_grid节拍网格ビートグリッド비트그리드กริดจังหวะ
music_play播放音乐音楽再生음악재생เล่นเพลง
music_pause暂停音乐音楽一時停止음악일시정지หยุดเพลงชั่วคราว
music_stop停止音乐音楽停止음악정지หยุดเพลง
music_seek定位音乐音楽シーク음악탐색ค้นหาเพลง
music_pos音乐位置音楽位置음악위치ตำแหน่งเพลง
music_volume音乐音量音楽音量음악음량ระดับเพลง
music_patch乐器音色音色読込악기패치แพตช์เครื่องดนตรี
music_note弹音符音符演奏음표연주เล่นโน้ต
music_note_on音符开始音符オン음표켜기โน้ตเริ่ม
music_note_off音符结束音符オフ음표끄기โน้ตจบ
music_judge判定判定する판정ตัดสินจังหวะ
music_grade_name判定名判定名称판정이름ชื่อการตัดสิน
music_lrc载入歌词歌詞読込가사로드โหลดเนื้อเพลง
music_lyric当前歌词現在歌詞현재가사เนื้อเพลงปัจจุบัน
music_mic_pitch麦克风音高マイク音程마이크음정ระดับเสียงไมค์
music_note_name音名音名称음이름ชื่อโน้ต
music_hz音符频率音符周波数음표주파수ความถี่โน้ต
music_pitch_score音准评分音程スコア음정점수คะแนนเสียง
music_midi_load载入MIDIMIDI読込미디로드โหลดมิดี
music_midi_countMIDI数量MIDI数미디수จำนวนมิดี
music_midi_notesMIDI音符MIDIノート미디음표โน้ตมิดี
music_fft音乐频谱音楽スペクトル음악스펙트럼สเปกตรัมเพลง
music_midi_barsMIDI音条MIDIバー미디바แท่งมิดี

ling-physics

Vector math, forces, soft bodies, rigid bodies and a liquid simulation.

English中文日本語한국어ไทย
soft_ball软球ソフトボール소프트볼ลูกบอลนุ่ม
soft_step软体步进ソフト更新소프트스텝ก้าวนุ่ม
soft_bounce软体落地ソフト着地소프트바운스เด้งนุ่ม
soft_contain软体边界ソフト箱소프트경계กล่องนุ่ม
soft_kick软体踢ソフト衝撃소프트킥เตะนุ่ม
soft_deform形变量変形量변형량ความบิดเบี้ยว
soft_centroid软体质心ソフト重心소프트중심จุดศูนย์กลางนุ่ม
soft_nodes软体节点ソフト節点소프트노드จุดนุ่ม
rb_add刚体添加剛体追加강체추가เพิ่มวัตถุแข็ง
rb_torque扭矩トルク토크แรงบิด
rb_spin自旋スピン스핀หมุน
rb_impulse刚体冲量剛体インパルス강체충격แรงดลแข็ง
rb_floor刚体落地剛体着地강체바닥พื้นแข็ง
rb_gravity刚体重力剛体重力강체중력แรงโน้มถ่วงแข็ง
rb_step刚体步进剛体更新강체스텝ก้าวแข็ง
rb_pos刚体位置剛体位置강체위치ตำแหน่งแข็ง
rb_rot刚体旋转剛体回転강체회전การหมุนแข็ง
liquid_new新建液体液体新規액체생성สร้างของเหลว
liquid_splat液体注入液体追加액체분사หยดของเหลว
liquid_gravity液体重力液体重力ベクトル액체중력แรงโน้มถ่วงเหลว
liquid_step液体步进液体更新액체스텝ก้าวของเหลว
liquid_draw绘制液体液体描画액체그리기วาดของเหลว
liquid_draw_surface液体贴面液体曲面액체곡면ของเหลวบนพื้นผิว
liquid_rainbow液体彩虹液体虹액체무지개ของเหลวสายรุ้ง
soft_spin软体自旋ソフト回転소프트회전หมุนนุ่ม
soft_angular_speed软体角速ソフト角速度소프트각속도ความเร็วเชิงมุมนุ่ม
liquid_mix液体混合液体混合度액체혼합การผสมของเหลว

ling-animation

Procedural animation: tweens, gaits, springs, gears and IK.

English中文日本語한국어ไทย
tween补间補間트윈แทรกค่า
tween_ease缓动补间緩和補間이징트윈แทรกนุ่ม
breathe呼吸呼吸호흡หายใจ
wobble摆动揺れ흔들림โยก
gait_phase步相歩相걸음위상เฟสก้าว
gait_swing步摆歩振り걸음흔들ก้าวแกว่ง
gait_lift抬脚足上げ발들기ยกเท้า
spring_to弹向バネ寄せ스프링이동สปริงไป
ik2反解逆運動역운동ไอเค2
gear_couple齿轮联动歯車連動기어연동เฟืองทด
gear_train齿轮组歯車列기어열ชุดเฟือง
cam_lift凸轮升程カム揚程캠리프트ยกลูกเบี้ยว
piston活塞ピストン피스톤ลูกสูบ
rack齿条ラック랙แร็ค

ling-ai

Neural networks, behaviour trees and a small learned dialog model.

English中文日本語한국어ไทย
nn_new建神经网ニューラル作成신경망생성สร้างโครงข่าย
nn_dense密集层密層追加밀집층ชั้นหนาแน่น
nn_forward神经前向順伝播순전파ส่งต่อโครงข่าย
nn_train训练网ニューラル学習신경망학습ฝึกโครงข่าย
nn_save保存网網保存신경망저장บันทึกโครงข่าย
nn_load载入网網読込신경망불러오기โหลดโครงข่าย
bt_build建行为树行動木構築행동트리구성สร้างต้นไม้พฤติกรรม
bt_set设事实事実設定사실설정ตั้งข้อเท็จจริง
bt_tick行为树滴答行動木更新행동트리틱เดินต้นไม้พฤติกรรม
bt_status行为树状态行動木状態행동트리상태สถานะต้นไม้พฤติกรรม
dialog_new建对话模型対話モデル作成대화모델생성สร้างโมเดลสนทนา
dialog_learn对话学习対話学習대화학습เรียนรู้สนทนา
dialog_load对话载入対話読込대화불러오기โหลดชุดสนทนา
dialog_train对话训练対話訓練대화훈련ฝึกสนทนา
dialog_say对话生成対話生成대화생성พูดสนทนา
dialog_save对话存模対話モデル保存대화모델저장บันทึกโมเดลสนทนา
dialog_load_model对话载模対話モデル読込대화모델불러오기โหลดโมเดลสนทนา

ling-crypto

Hashing, encryption, signatures and the geometric and post-quantum suite.

English中文日本語한국어ไทย
sign签名署名서명ลายเซ็น
hash哈希ハッシュ해시แฮช
encrypt加密暗号化암호화เข้ารหัส
crypto_hash几何哈希幾何ハッシュ기하해시แฮชเข้ารหัส
knot_points结点坐标結び目点매듭점จุดปม
knot_label结点标签結び目ラベル매듭라벨ป้ายปม
knot_keygen生成密钥鍵生成키생성สร้างกุญแจปม
knot_public公钥公開鍵공개키กุญแจสาธารณะปม
knot_encapsulate封装密钥カプセル化캡슐화ห่อกุญแจปม
knot_decapsulate解封装密钥カプセル解除캡슐해제แกะกุญแจปม
crypto_seal封印封印する봉인ผนึก
crypto_open解封封印解除봉인해제เปิดผนึก
holo_points全息点ホログラム点홀로그램점จุดโฮโลแกรม
holo_fragment_count全息碎片数ホログラム断片数홀로그램조각수จำนวนชิ้นโฮโลแกรม

ling-input

Gamepad polling, sticks, triggers and rumble.

English中文日本語한국어ไทย
pad_poll手柄轮询パッド更新패드폴링อัปเดตแพด
pad_count手柄数パッド数패드수จำนวนแพด
pad_connected手柄连接パッド接続패드연결แพดเชื่อม
pad_button手柄按键パッドボタン패드버튼ปุ่มแพด
pad_pressed手柄按下パッド押下패드눌림แพดกด
pad_lx手柄左Xパッド左X패드왼Xแพดซ้ายX
pad_ly手柄左Yパッド左Y패드왼Yแพดซ้ายY
pad_rx手柄右Xパッド右X패드오XแพดขวาX
pad_ry手柄右Yパッド右Y패드오YแพดขวาY
pad_lt手柄左扳机パッド左トリガー패드왼트리거ไกแพดซ้าย
pad_rt手柄右扳机パッド右トリガー패드오트리거ไกแพดขวา
pad_rumble手柄震动パッド振動패드진동แพดสั่น

ling-net

HTTP client.

English中文日本語한국어ไทย
http_get网取HTTP取得HTTP가져오기ดึงHTTP

ling-dialog

On-screen dialog boxes with typewriter text.

English中文日本語한국어ไทย
dialog_show对话显示会話表示대화표시แสดงบทสนทนา
dialog_step对话步进会話更新대화스텝ก้าวบทสนทนา
dialog_advance对话推进会話送り대화진행เลื่อนบทสนทนา
dialog_active对话激活会話中대화중บทสนทนาทำงาน
dialog_typing对话打字会話タイプ中대화타이핑กำลังพิมพ์บทสนทนา
dialog_close对话关闭会話閉じる대화닫기ปิดบทสนทนา
dialog_color对话颜色会話色대화색สีบทสนทนา
dialog_draw对话绘制会話描画대화그리기วาดบทสนทนา

道场 — Shrine Room

Source: examples/3d-rooms/ling-dao-chamber.ling

A quiet Chinese-Japanese shrine drawn only with vector geometry (vtex_*), with no pixel fills. Everything moves slowly in a gold, jade and crimson palette, and a soft pentatonic bell chord plays in the background. The program is written mostly with Thai keywords and builtins, with a few Chinese names mixed in.

Run it from the repository root:

ling run examples/3d-rooms/ling-dao-chamber.ling

What’s in the room

PartBuilt with
Torii gate at the far endvtex_torii
Five-tier pagoda behind the gatevtex_pagoda
Altar mandala: gear ring, dharma wheel, lotus, ringsvtex_spiked_cog, vtex_chakra, vtex_lotus, vtex_rings
Stone-tile floor with a yantra bordervtex_grid, vtex_yantra
Star lantern on the ceilingvtex_star, vtex_rings
Ink-brush panels on the side wallsvtex_letter_rain, vtex_lotus
Four corner pillarsvtex_rings, vtex_spiked_cog, vtex_lotus

Sound

Five tones form a Chinese pentatonic scale, 宫 商 角 徵 羽 (C4, D4, E4, G4, A4), plus a faint sub-bass. Each tone is placed in 3D space with audio_tone, and audio_listener follows the camera, so the bells shift as the view swings.

Camera and light

The camera swings like a slow pendulum, about 30 degrees to each side, always facing the altar. Five lights (add_light) give a gold overhead lamp, a warm altar glow, jade and crimson accents on the pillars, and a lamp at the gate.

Ideas to try

  • Change the hue anchors GOLD, JADE and CRIMSON at the top of the file.
  • Speed up the camera by raising orbit_spd.
  • Change the frequencies in init_audio to try a different scale.

See 3D Shapes and Meshes and Audio for the builtins used here.

Garden

Source: examples/audiovisual/Garden.ling

An open outdoor garden: ground, sky, a pond in the centre, two trees in front, flower beds, a tree line behind and a wooden shed. There are no walls or ceiling. All of it is drawn with vector geometry (vtex_*), and each kind of shape has its own tone, so the scene is something you hear as well as see.

Run it from the repository root:

ling run examples/audiovisual/Garden.ling

The scene

PartFunction in the file
Grass, stone path and flower-bed patchesdraw_ground
Sun disc, drifting clouds and horizon glowdraw_sky
Trees with spiral trunks and flower crownsdraw_tree, draw_trees
Scattered flower bedsdraw_flowers
Pond with floating lotus, a fountain and ripplesdraw_pond
Wooden shed with a door, window and roofdraw_shed
Two faint “echo” copies of the scene from earlier framesdraw_echo

The shapes come from vtex_flower, vtex_lotus, vtex_chakra, vtex_rings, vtex_grid, vtex_spiral, vtex_star, vtex_yantra, vtex_hyperbolic_uv and vtex_tessellated. A small hash function, sm2_hash, gives each ground patch and shed plank its own amount of detail.

Sound

Six tone voices use a G major pentatonic scale (G A B D E). Each voice is placed at its own point in the scene with audio_tone, around the pond, the shed and the sky, and audio_listener follows the camera.

Camera

The camera floats on a slow, wandering path around the pond and always looks at the centre of the garden. Colours cycle through the whole spectrum about every two seconds.

Ideas to try

  • Change orbit_h and orbit_v to move the camera closer or further away.
  • Move the pond with PX and PZ, or the shed with SX and SZ.
  • Change the pentatonic frequencies PG3 to PE4 to give the garden a new key.

Hyperbolic World (H²×ℝ)

Source: examples/physics/hyperbolic_world.ling

A small block world where the ground is the hyperbolic plane. It is inspired by Hypermine, which is set in full 3D hyperbolic space (H³). This demo uses its simplest playable cousin, H²×ℝ: you walk on the hyperbolic plane (drawn as a Poincaré disk) and gravity works normally in the vertical direction.

Run it from the repository root:

ling run examples/physics/hyperbolic_world.ling

Controls

KeyAction
W / SWalk forward / back
A / DStep left / right
Q / ETurn left / right
SpaceJump

What makes it hyperbolic

  • Crowding toward the edge. Blocks sit on rings, and each ring has more blocks than the one inside it (cells = 6 * ring). Toward the edge of the disk, which stands for infinity, they pile up and shrink by the factor 1 − |z|².
  • Möbius movement. You stay at the centre of the disk and the world slides under you by a Möbius translation, z ↦ (z + a) / (1 + ā z). Turning rotates the world around the centre.
  • Holonomy. Walk in a closed loop, such as a square, and you come back turned. This is what moving through negatively curved space feels like.
  • Normal gravity. Jumping and falling use the ordinary vertical axis, so they feel the same as in any game.

Blocks without textures

Each block hashes its ring and position (hash01, a fract(sin(...)) hash) into a type (grass, stone, dirt or crystal) and a height. The colour comes from the type, and the cel-shading settings (set_shade_mode, set_cel_bands, set_rim) do the rest. No texture files are needed. See Post-FX and Lighting.

Ideas to try

  • The blocks are drawn with cube. Try cylinder or another shape from 3D Shapes and Meshes.
  • Raise the ring limit (ring <= 4) for a bigger world.
  • Change STEP and TURN to move or turn faster.

For a different kind of 3D demo, see Hyperbolic 3D.

Hyperbolic 3D

Source: examples/physics/hyperbolic3d.ling

Despite its file name, the current version of this demo is a physics maze in ordinary (Euclidean) 3D space. You roll a ball through a wireframe maze, bounce off walls and charge up jumps, while a tone follows the ball’s motion. For real hyperbolic geometry, see Hyperbolic World.

Run it from the repository root:

ling run examples/physics/hyperbolic3d.ling

Controls

KeyAction
W / SPush the ball forward / back
A / DPush the ball left / right
SpaceHold to charge a jump, release to jump
← / →Orbit the camera
↑ / ↓Tilt the camera
Z / XZoom in / out

How it works

  • Physics. Each frame adds gravity, multiplies the velocity by a damping factor (DAMPING = 0.99) and moves the ball. When the ball crosses a wall, the program pushes it back and reverses its speed, scaled by ELASTICITY = 0.80.
  • The maze. An outer box of 300 × 200 × 300 units and five inner walls. The walls are checked as rectangles and drawn as lines with draw_line_3d.
  • Jumping. Holding Space on the ground builds up a charge, up to MAX_CHARGE. Releasing it launches the ball. A small meter at the ball shows the charge.
  • The ball. Drawn as a spinning vtex_chakra wheel whose colour changes with height. A shadow cross on the floor, a line down to the floor and a red velocity arrow help you see where it is.
  • Sound that follows physics. One audio_tone voice changes every frame: the pitch rises with height and speed and jumps briefly on each bounce, the volume grows with speed, and the stereo pan follows the ball’s x position.
  • Lights. Three lights: a slowly drifting warm light, a cool fill light, and a purple light that follows the ball.

Ideas to try

  • Change GRAVITY, DAMPING and ELASTICITY at the top of the file and feel the difference.
  • Add a wall: copy one of the wall collision checks and draw it with matching draw_line_3d calls.
  • Map another value to sound, for example the charge level to the pitch.