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_*anddb_*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.
| Volume | Level | Pages | Download |
|---|---|---|---|
| Learn Ling | Beginner | 321 | ling-beginner.pdf (13 MB) |
| Build with Ling | Intermediate | 716 | ling-intermediate.pdf (27 MB) |
| Mastering Ling | Advanced | 452 | ling-advanced.pdf (16 MB) |
| The Ling Reference | Complete reference | 650 | ling-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
| App | What it is |
|---|---|
| LingStationX | A 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. |
| LingDev | A 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. |
| LingModeler | Modelling, 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. |
| LingForFun | An 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 Arcade | A 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 Wallet | A 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
| Project | What it is |
|---|---|
| Soul Symphony | An 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. |
| LingSoul | An 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:
| Demo | What it shows |
|---|---|
examples/music/hallway_runner.ling | An infinite runner that reacts to the music; coins ring the melody as spatial sound |
examples/music/karaoke_hero.ling | Karaoke pitch bars from a vocal MIDI, with a live microphone tuner |
examples/music/synth_jam.ling | GM instruments synthesized from .ling patches |
examples/physics/bouncy_ball.ling | A spring-mass soft body that squashes as it bounces |
examples/physics/tumbling.ling | Rigid bodies tumbling and rolling |
examples/physics/liquid_marble.ling | A water and oil simulation on a spinning sphere, cone and dome |
examples/ui/hud_showcase.ling | The UI toolkit: HUD, meters, controls and game widgets |
examples/crypto/crypto_donut_physics.ling | A 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
| Profile | What it adds |
|---|---|
core | Lexer, parser, Cranelift JIT and AOT, the interpreter, the software window and drawing (draw_*, fonts, images, meshes). Every profile includes it. |
web | http_* server and client (Web Server and HTTP), db_* SQLite (Database), static files, TOTP, zip/tar, video playback, processes, hashes and password_hash. |
privacy | Post-quantum identities, lingtp://, peer-to-peer p2p_*, Ling Wallet lw_*, ssh_*, plus web and the ui_* widgets. |
game | Physics (soft, rigid, liquid, glTF), GPU raster, animation, dialogs, gamepads, acoustic bodies, ui_* widgets. |
ai | Neural networks (nn_*), behaviour trees (bt_*), learned dialog and speech-to-text (stt_*). |
audio | Sound engine, music decoding, synthesis and MIDI, microphone, the LingStationX DAW. |
os | ling build --platform kernel, rpi, lingos, lingos-rpi (LingOS images). |
full | All 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-devfor audio. - On macOS and Windows: nothing extra.
ling buildfor 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 namestartto 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.printlndoes 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: the JIT, the interpreter, and projects.
- Values and Bindings: the first tutorial.
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:
| Command | Backend | Use it for |
|---|---|---|
ling run file.ling | Cranelift JIT (the default) | Speed. Compiles your program to native code first. |
ling run --interp file.ling | Tree-walking interpreter | Diagnostics. 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
| Command | What it does |
|---|---|
lingfu run | Runs the entry program with ling run. Extra arguments are passed on. |
lingfu test | Runs every .ling file under tests/, one by one. |
lingfu build | Builds a native executable with ling build --aot. |
lingfu clean | Deletes 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 addentry = "src/start.ling"here.[realm]sets the project’s language and its source folder.[root]and[depends]list thecoredependency 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
| Option | Meaning |
|---|---|
--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, …). |
--pack | Embed the manifest’s [includes] files in the executable. |
--aot | Compile 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:
- Open the window, once.
- Clear it with
fill, so the last frame doesn’t linger. - Draw your shapes.
- 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: centrex, y, z, size, rotation in radians, and a final mode (0solid,1wireframe,2both).present()shows the frame. Nothing appears without it.- Rebinding
angleeach 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:
| Call | What 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:
pillarandwallsare functions that draw parts of the room. They are called inside the loop, so they draw again every frame.wallsgetstas a parameter because functions only see their parameters and top-level names.- The four lines after
open_windowswitch to calm, faithful colours. Without them, Ling’s default look tints shadows indigo and adds a glowing rim. px,pzandyawhold the camera’s position and heading.key_down("left")is true while the key is held. Walking moves bysin(yaw)along x andcos(yaw)along z, the direction you are facing.clear_lights()andadd_light(x, y, z, r, g, b, intensity, radius)run every frame, because lights add up otherwise. The lamp is aty = -2.5, near the ceiling.vtex_gridandvtex_flowerdraw 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” is0, -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_gridcall (the hue) to get other colours. - Add a fifth pillar, or a second
add_lightin a different colour. - Add
if key_pressed("p") { screenshot("room") }afterpresent(). Pressing P saves a PNG in ascreenshotsfolder.
Next steps
- Window and Camera and 3D Shapes and Meshes list every drawing builtin.
- Drawing and Games goes further with drawing and simple games.
- Chapter 6 of Learn Ling in the Ling Book covers this room in more depth.
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:
| Kind | What it holds | Examples |
|---|---|---|
| number | any number, whole or with a fraction | 42, 3.14, -7 |
| text | letters, words, sentences (also called a string) | "hello", "Room 101" |
| boolean | one of two answers: yes or no | true, false |
| list | several 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 no1e3or0xff. - Text uses double quotes only. Inside text,
\nstarts 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
- Bind your age and print
In 10 years I will be ...with the right number. - A rectangle is 12.5 wide and 8 tall. Print its area and its perimeter, each with a label.
- Bind
nto 10. Using onlybind, make it 11, then 22, then 4. Printnafter each step. - Convert 98.6 degrees Fahrenheit to Celsius with
(f - 32) * 5 / 9and print it rounded to one decimal place. - Print
"7" + "3"and thento_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:
- Set a counter before the loop (
bind i = 1). - A condition that keeps the loop going (
i <= 5). - 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
- Bind a number
nand printpositive,negativeorzero. - Print the 6 times table from
6 x 1to6 x 10with aforloop. - Use a
whileloop to add up the even numbers from 2 to 50. (The answer is 650.) - Start with 1 and double it until it is larger than 1000. Print how many doublings it took.
- Rewrite the grade example with the tests in the opposite order (
score >= 70first). 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!
fnsays “I am defining a function”.greetis the function’s name.namein 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:
- A base case, so simple that the answer is known directly.
- 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 withling run --interp yourfile.ling, which reportsunknown function.
Try it
- Write
is_even(n)that returnstrueorfalse. Printis_even(10)andis_even(7). - Write
max3(a, b, c)that returns the largest of three numbers. (The builtinmaxtakes two; you can nest it.) - Write
sum_to(n)with awhileloop, thensum_to_r(n)with recursion. Both should give 5050 for 100. - Write
power(base, exp)recursively, using only multiplication.power(2, 10)is 1024. - 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 writelist_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
| Builtin | Purpose |
|---|---|
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 alwaysfalse, even when they hold the same items. Compare them item by item.
Try it
- Make a list of five numbers and print their total with a
whileloop. - Split
"3,8,15,4"on commas, convert each piece withto_number, and print the biggest. - Write
count_vowels(s)that counts the letters a, e, i, o, u. (Hint: lower-case the text, then test each character withstr_find("aeiou", ch) != -1.) - Use
str_replaceandstr_lowerto make a palindrome test that ignores spaces, and try it on"never odd or even". - 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 withoutpresent()is invisible.tcounts 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 = 300is lower on the screen thany = 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.
| Builtin | Draws |
|---|---|
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_rectis 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:
- State:
xandylive outside the loop, so they survive from frame to frame. - Input and update: the
key_downchecks change the state, andclampkeeps the ball inside the window. - 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.
starbuilds a flat list of ten corner coordinates withcosandsin, alternating a long and a short radius, and hands it todraw_poly. Thespinangle 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) < 55decides whether it was caught.rand()returns a number from 0 up to 1, so50 + rand() * 540is a random x between 50 and 590. - Difficulty.
bind fall = fall + 0.25makes 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
- 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)). - Make the ball bounce: keep speeds
vxandvy, add them toxandyeach frame, and flip the sign (bind vx = 0 - vx) when the ball reaches a wall. - In the paint program, make the colour follow the pointer’s x position:
bind hue = mouse_x() / 640 * 360. - Add a best score to Star Catcher and show it under the score with
ui_text. - 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:
| Wave | Sounds 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)
slotnumbers 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, zplace the sound relative to the camera;z = 3is straight ahead.wis an extra timbre parameter; 0 turns it off.freqis the pitch in hertz andampthe loudness.lfo_rateandlfo_depthadd 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:
| Builtin | Use 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
daw_new()starts an empty project anddaw_set_bpm(120)sets the tempo.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.daw_clip_add_midi(track, start, length)adds an empty clip, measured in beats.daw_note_add(track, clip, start, length, pitch, velocity)adds one note. Velocity is how hard the key is hit, from 0 to 1.daw_bounce(path, from, to, tail, bits, format, quality)renders the beatsfromtotoplus atailin seconds, and returns1on success.
The file twinkle.wav appears in the folder where you ran the program. Play it with
music_load and music_play.
Try it
- Print the frequency of every MIDI note from 60 to 72. What is the ratio between the first and the last?
- In the keyboard piano, make the key
"z"play a drum-like hit:audio_blip(120, 0.15, "noise", 0.4). - Change the piano’s notes to an A minor pentatonic scale:
[57, 60, 62, 64, 67, 69, 72, 74]. - Put your own tune in the melody player. “Happy Birthday” starts with 60, 60, 62, 60, 65, 64.
- Render a drum loop: a
"drums"track with a kick (36) on every beat and a snare (38) on beats 2 and 4, bounced todrums.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
200with 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:
| Field | Content |
|---|---|
method | "GET", "POST", … in upper case |
path | the path without the query string |
query | the raw query string after ?, such as name=Ada&page=2 |
body | the request body as text |
cookie | the raw Cookie header |
authorization | the raw Authorization header |
client_ip | the 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>"))
}
<b>Tom & Jerry</b>
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:
| Builtin | Purpose |
|---|---|
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, <b>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-levelbinds. - 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
- Add
GET /note?id=2that returns one note, or status404with{"error":"not found"}whendb_queryreturns an empty list. - Add
POST /delete?id=2withdb_exec("DELETE FROM notes WHERE id = ?1", id). Use the numberdb_execreturns to answer404when nothing was deleted. - Serve a folder
public/with anindex.htmlat/appusinghttp_static. - Make the greeting page count visits in a
visitstable 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:
| Item | Form | See |
|---|---|---|
| binding | bind name = expression | Bindings |
| function | fn name(a, b) { ... } | Functions |
| record type | form Name { field, field } | Records and enums |
| enum type | choose Name { Variant, Variant(a) } | Records and enums |
| module | mod name { fn ... } | Modules and Projects |
| import | use "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. Writebind 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
| Literal | Form | Notes |
|---|---|---|
| number | 42, 3.14 | Decimal 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. |
| boolean | true, false | |
| unit | () | The “nothing” value. |
| list | [1, "two", 3.5] | Items of any type, indexed from 0. |
| range | 0..5 | Half-open: 0, 1, 2, 3, 4. Used with for. |
| closure | |x| x + 1 | See 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:
| Level | Operators | Notes |
|---|---|---|
| 1 | . () [] :: .. | field or method, call, index, module path, range |
| 2 | -x !x | prefix 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 > 1does not protect the division. Use a nestedifinstead.- Comparisons chain to the left:
1 == 1 == 1means(1 == 1) == 1, which isfalse. - Prefix minus can’t be doubled:
- - xis a parse error.0 - xalways works. ==on lists, records and enum values is alwaysfalse. 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:
| Inside | Rebinding after the block ends |
|---|---|
if / else body | kept |
while body | kept, so while loops can accumulate |
for body | lost: each pass starts from a fresh copy |
match arm | lost |
| function body | local to the call |
do { } block | lost 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) -> textare 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 withling 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:
| Pattern | Matches |
|---|---|
_ | anything |
0, "yes", true | that literal value |
name | anything, 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 = 5followed by a line-1makesxequal to4, and a line starting with[1, 2]is read as indexing. - Range bounds.
0..n + 1is a parse error and0..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 + 1is a parse error. Writebind 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
| Keyword | Status | What it does |
|---|---|---|
bind | active | Creates or replaces a binding. Also defines globals and the entry point. |
do | active | A block whose value is its last statement. |
fn | active | Declares a function. |
if / else | active | Conditional expression. |
while | active | Loop while a condition holds. The body shares the outer scope. |
for / in | active | Loop over a range or list. Each pass gets a fresh scope. |
match | active | Pattern matching. |
return | active | Leaves the current function with a value. |
form | active | Declares a record type. |
choose | active | Declares an enum type with optional payloads. |
mod | active | Groups functions into a namespace (name::f()). |
use / as | active | Loads another file, optionally under an alias. |
ok / bad | active | Build a result, and match one as a pattern. |
true / false | active | The boolean values. |
try | builtin | Not syntax: the builtin try(f, args...). Works on the interpreter only. |
type | ignored | type Name as T is parsed and thrown away. It swallows what follows it, so avoid it. |
where | ignored | fn f(x) where ... { }: everything up to { is skipped. |
async | ignored | async fn runs synchronously, like a normal function. |
wait | unreliable | Gives the value on the interpreter but () on the JIT. Don’t use it. |
own lend share move copy | ignored | Prefix words that return their operand unchanged. No ownership checks happen. |
asm | ignored | asm("...") is meant for bare-metal builds. In a normal run it does nothing useful. |
stop | reserved | Does not break out of a loop. |
again | reserved | Does not continue a loop. |
change | reserved | Does nothing. Rebind with bind instead. |
post give fit can sure maybe pure | reserved | Do nothing. They are ordinary names to the parser. |
spawn | reserved | Does nothing, and there is no spawn builtin. |
none | reserved | Not 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,constand similar words appear in some lexicon files but are not keywords. Ling has noloopand nolet: usewhileandbind.number,text,bool,list,mapandtupleare 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
| Type | Examples | Created by | Prints as |
|---|---|---|---|
| number | 3, 2.5, -7 | number literals, arithmetic | 3, 2.5 |
| text | "abc" | text literals, +, text builtins | abc |
| bool | true, false | literals, comparisons | true |
| unit | () | (), functions with no result, failed lookups | () |
| list | [1, "a", true] | list literals, list_new, list builtins | [1, a, true] |
| record | Point(3, 4) | calling a form name | Point { x: 3, y: 4 } |
| enum value | Circle(2), Dot() | calling a choose variant | Circle(2) |
| result | ok(5), bad("e") | ok and bad | Ok(5), Err(e) |
| function | |x| x + 1 | closures |
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 condition | JIT (default) | Interpreter |
|---|---|---|
true / false | true / false | true / false |
0 | false | false |
() | false | false |
| other numbers, non-empty text, non-empty lists | true | true |
"" (empty text) | true | false |
[] (empty list) | true | false |
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
| Builtin | Converts | Notes |
|---|---|---|
str(v) | any value to text | Same text that println shows. Also called to_str. |
to_number(s) | text to number | Ignores surrounding spaces. Returns 0 if the text isn’t a number. |
hex_to_number(s) | hex text to number | No 0x prefix: hex_to_number("ff") is 255. |
int(x) | number to whole number | Cuts off the fraction, toward zero. Also called trunc. |
floor(x) / ceil(x) | number to whole number | Round down / up. |
round(x) | number to whole number | Halves 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.
| Tool | Use 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 --interp | Seeing 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).anythingis5). That is rarely what you want. Usematch.
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()underling run. When a program misbehaves, run it once withling run --interpto 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:
| Builtin | On 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.
| Form | What 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 m | Loads 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
startbinding 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), aslen2does. A baredot(a, a)fails on the interpreter and gives()on the JIT. - Functions in a
modcan call the file’s top-level functions without a prefix. - Don’t bind values inside a
mod.vec::ORIGINgives()on the JIT and the textvec::ORIGINon 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 asvec::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".
| Command | What it does |
|---|---|
lingfu run | Runs src/start.ling |
lingfu test | Runs every .ling file in tests/ |
lingfu build | Builds a distributable (needs the entry line below) |
Entry points in a project
- The program is
src/start.ling, with abind start = do { ... }. - A test in
tests/is a program too. It binds any name to adoblock (the starter test usesbind test = do { ... }) and loads the code it tests with a path relative to itself, such asuse "../src/lib/textkit.ling". Every file intests/must have an entry point: a helper file without one fails withno 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
doblock, so you can call itstart,始,開始,시작orเริ่ม. to_strstays in English in every version, because it has no alias in these languages. English names always work.- When a file uses another language,
ling runprints 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 aswrite_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_routeis alsoเว็บเส้นทาง,db_openis 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 forlenis长度). If a call seems to do nothing, runling run --interp yourfile.ling, which stops withunknown 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
.lingfile under the current folder, including subfolders. - It also renames files and folders whose names it knows how to translate. Add
--content-onlyto change only file contents, or--files-onlyto 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:
normalizechanges 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
| Situation | JIT (default) | Interpreter |
|---|---|---|
| Unknown function name | returns () silently | unknown function error |
| Runtime error (missing file, bad index, …) | returns () or an empty value, keeps going | stops with an error and a traceback |
1 / 0 | () | inf |
pi as a bare name | () (write pi()) | the value |
"" or [] in a condition | true | false |
| Index past the end of a list | empty value | index N out of bounds error |
One character of text, s[i] | empty value | the character (use substr(s, i, 1) on both) |
for c in "text" | empty values | each character |
Ordering text, "a" < "b" | false | error |
bind inside do { } | visible afterwards | discarded |
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 start | ends the program quietly | unexpected 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
| Construct | Does a bind inside update the outer variable? |
|---|---|
while body | yes |
if body | yes |
for body | no: each pass gets a fresh copy of the scope |
do { } block | yes 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,.5or3.. Worse,1e3and0xffaren’t parse errors: they read as1or0followed by an unknown name. - Text uses double quotes only and has no interpolation. Build text with
+andstr(). printandprintlnboth end the line, and both join their arguments with no separator:println("sum", 1 + 2)printssum3.!xmeansx == false, so!0and!""arefalse. 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_filterand similar builtins return(), andtry()always returnsbad("try: first argument must be a function"). They work on the interpreter. - Programs that call
http_serverun on the interpreter automatically, so closures andtrywork 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 tostart, so a library must never bindstart.- Inside a
mod, call sibling functions with the qualified name (geo::area). A bare call fails. - Values bound inside a
modare not usable. Expose constants as functions.
Prefix your library functions with the library name, for example geom_area. See
Modules and Projects.
Tooling
lingfu newcreatessrc/start.ling, butlingfu buildlooks formain.lingunless the manifest says otherwise. Addentry = "src/start.ling"to the[spirit]section ofLing.toml.lingfu check,lingfu fmtandlingfu translatecalllingsubcommands that don’t exist. They printling’s usage text and do nothing;checkandfmtstill report success. Useling run --interpto check a program andlingfu normalize <lang>to translate one (it rewrites every.lingfile in the current folder, so use it on a copy).lingfu normalizegets a few keywords wrong. It writesformas a word the lexer doesn’t accept in Chinese, Korean and Thai (use the spelling from Keywords), leaveschoosein English, and in Japanese and Thai writesok/badwith builtin names that don’t work asmatchpatterns. Some ownership words (copy,lend,share) also come out wrong in Japanese and Thai. Run the result and fix those words by hand.lingfu buildcompiles 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. Usebind main = do { ... }.assert,panic,exit,append_fileanddelta_timeare not builtins. For frame timing, subtract successivetime_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)
| Profile | Builtin families (examples) |
|---|---|
core | The Output, Text and Files pages (except processes), windows, 2D drawing, fonts, images, meshes |
web | http_*, db_*, zip_*, tar_gz_*, video_*, run_process, proc_*, hashing and crypto |
privacy | p2p_*, lingtp_*, ssh_*, lw_* |
game | rb_*, soft_*, liquid_*, gltf_*, gpu_*, body_*, pad_*, dialog_*, ui_* |
ai | nn_*, bt_*, stt_*, learned dialog models |
audio | audio_*, 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:
- An introduction with the rules that apply to the whole page.
- 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. - 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
| Page | What it covers |
|---|---|
| Output, Math and Logic | print, format, ok/bad, rounding, trigonometry, noise, rand, sleep |
| Text and Lists | Measuring, searching, cutting and converting text; building and reading lists |
| Files, Time and System | Files and directories, time, command line, environment, processes, threads |
| Window and Camera | Opening a window, the frame loop, the 3D camera |
| 2D Drawing and Images | Pixels, lines, shapes, text on screen, loading and drawing images |
| 3D Shapes and Meshes | Built-in 3D shapes, meshes, textures |
| Fonts and UI | Fonts, text layout and interface widgets |
| Animation | Tweens, easing and animated motion |
| Post-FX and Lighting | Lights and screen effects |
| Audio | Playing sounds and synthesizing audio |
| Music | Notes, scales, music playback and MIDI |
| Physics | Rigid bodies, soft bodies and liquids |
| Acoustic Bodies | Physical objects that make sound |
| Input and Microphone | Keyboard, mouse, gamepads and the microphone |
| Dialog | Cinematic dialog boxes that type out text, for games |
| Web Server and HTTP | Routes, handlers, HTTP client requests |
| Database (SQLite) | Opening a database, running queries |
| Networking | Peer-to-peer, lingtp:// and SSH |
| Cryptography | Hashes, passwords, signatures and encryption |
| AI and Language Models | Neural 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.
print_file(text)
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!
print_color(color, value, ...)
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
(), sotryreturnsErr(try: first argument must be a function). Run programs that usetrywithling 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.
| Builtin | Purpose |
|---|---|
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:
window_is_open()turns false when the user closes the window or presses Escape. You don’t need to handle Escape yourself.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 withoutpresent()is invisible.- There is no delta-time builtin. Subtract the previous
time_now()from the current one, or count frames withframe_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
| Space | Origin | +x | +y | +z |
|---|---|---|---|---|
| Screen (2D) | top-left pixel | right | down | not used |
| World (3D) | camera pivot | right | down | away 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,hsize in pixels (default 800 by 600);title(default"Ling");resizableoptional,1makes 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()andget_height()every frame. If the window can’t be created, the program stops withcannot 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 withset_camera_pos, which is subtracted from every point; - the orientation, set with
set_cameraas the cosine and sine of a yaw and a pitch angle; - the depth offset
zdist, set withset_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) | 投影3D | 3D投影 | 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, callflush_3d()first. - Packed colours. Some builtins take one number
0xRRGGBB. Ling has no hex literals, so write it asr * 65536 + g * 256 + b(for example51 * 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.
| Builtin | Purpose |
|---|---|
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, _a | Read 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)
| Arguments | Meaning |
|---|---|
cx, cy, cz | Centre in world coordinates |
sx, sy, sz | Scale 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, rz | Rotation in radians (default 0), applied X, then Y, then Z |
mode | 0 filled (default), 1 wireframe, 2 both |
e0, e1, e2 | Shape-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
cylinderruns along local y from -1 to 1, so it is2 * sytall. A smallsysuch as 0.05 makes a disc or plate.torus:tubeis 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 tallsymakes an obelisk.gear: the thickness comes fromsy; 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 π onrzto flip them.gyronests gimbal rings on alternating axes;capsule_chainlines beads up along x.- The dice (
tetrahedrontoicosahedron) look like gems withmode2 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.
| Plane | u | v |
|---|---|---|
| Floor or ceiling | 1, 0, 0 | 0, 0, 1 |
| Wall facing the camera, upright | 1, 0, 0 | 0, -1, 0 |
| Side wall, upright | 0, 0, 1 | 0, -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.
| Builtin | Purpose |
|---|---|
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.
| Builtin | Purpose |
|---|---|
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.
| Builtin | Purpose |
|---|---|
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_drawcontinues withuoff, voff, uscale, vscale(texture scroll and scale),shade(0 to 1, darkens faces turned from the light),blendandcull(0none,1or2one winding).rotis a yaw angle or a row-major 3 by 3 list. It returns the number of triangles queued.tm_spritedraws onto the 2D framebuffer, so call it afterflush_3d()for a HUD or title card.tm_wirekinds:0cube,1tetrahedron,2octahedron,3icosahedron,4torus,5sphere,6ring,7star prism,8grid.sizeis the radius;thick1 doubles the strokes.tm_solidkinds:0cube,1tetrahedron,2octahedron,3icosahedron,9a 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_loadreads a.ttfor.otffile;font_text_fill,font_textandfont_text_3ddraw 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_textdraws 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 centrecx, cyand radiusr. - Colours come from the theme (
ui_theme). Most widgets accept an optional trailingr, g, bthat 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_textorfont_text_fill. - Interaction reads the left mouse button. A button returns
1on the single frame the mouse goes down over it, so compare with== 1. This needspresent()once per frame. - Blend. Widgets honour
set_blend, soset_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_buttonhighlights on hover and returns1on the frame it is clicked, otherwise0.ui_toggleandui_checkboxtake the current state and return the new one,1or0.ui_sliderhas 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_tabsdrawscountequal tabs and returns the active index (from 0). Divide the width bycountto place captions.ui_stepperreturnsvalueplus or minusstepwhen a side is clicked. It draws no number.ui_tooltipis 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) | 反解 | 逆運動 | 역운동 | ไอเค2 | Two-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, usuallytime_now()or a variable you advance by1/60each 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.
| Family | Names |
|---|---|
| Basic | linear, step |
| Quadratic | quad_in, quad_out, quad_in_out |
| Cubic | cubic_in, cubic_out, cubic_in_out (also smooth) |
| Sine | sine_in, sine_out, sine_in_out |
| Exponential | expo_in, expo_out, expo_in_out |
| Elastic | elastic_in, elastic_out (also elastic) |
| Back | back_in, back_out, back_in_out (also overshoot) |
| Bounce | bounce_in, bounce_out (also bounce) |
ease (UI curves). Dashes and underscores are interchangeable. Unknown names give quad_inout.
| Name | Shape |
|---|---|
linear | Straight line |
quad_in, ease_in | Slow start |
quad_out, ease_out | Slow finish |
quad_inout, ease, smooth | Slow start and finish (the default) |
cubic_in, cubic_out, cubic_inout | Stronger versions |
quart_out | Fast start, long slow finish |
sine, sine_inout | Gentle sine in-out |
expo, expo_out | Exponential decay |
back, back_out | Overshoots, then settles |
elastic, elastic_out | Springy overshoot |
bounce, bounce_out | Bounces 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_phasereturns where the cycle is, from 0 up to (not including) 1.gait_swingreturns the forward and backward swing of a leg, between-strideandstride. For the other leg, uset + 0.5 / speed.gait_liftreturns 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
| Builtin | Returns |
|---|---|
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 骨骼姿势纹理绘制, スキンポーズ描画, 글꼴포즈텍스처, วาดสกินมีพื้นผิว.
| Builtin | Purpose |
|---|---|
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.
poseis 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_textakes more optional arguments aftertime: ambient light, back-face culling (1to cull), a source model whose clips drive this one (for equipment matched by joint name), a list of extra per-bone rotations, and a0xRRGGBBtint.gltf_draw(h, x, y, z, scale, yaw)draws the model unskinned.gltf_mesh_count,gltf_mesh_name,gltf_mesh_show(h, i, on)andgltf_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.
| Builtin | Parameters |
|---|---|
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:
- Ambient occlusion (
set_ssao): soft contact shadows from the depth buffer. - Outlines (
toon_outlines): ink lines where depth jumps. - Tone ramp (
tone_*): maps brightness to cel bands. - Bloom (
set_bloom): glow bleeding from bright pixels. - 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 byt.tone_ramp_clear()removes all stops so you can build your own.tone_ramp_reset()restores the default.tone_smooth(on):0snaps hard between stops (default),1blends smoothly.tone_bezier(y1, y2)remaps the input brightness through a cubic Bézier before the lookup. About0.333, 0.667is neutral (the defaults),0, 0is shadow-heavy,1, 1highlight-heavy and0.1, 0.9an 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:
| Look | Calls |
|---|---|
| Crisp anime cel | tone_smooth(0), tone_soft(0.32, 0.65) |
| Painterly, smooth | tone_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-guiprograms. 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레벨 | ระดับRMS | Overall 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.
| Parameter | Default | Meaning |
|---|---|---|
slot | 0 | Tone slot number. |
x, y, z | 0 | World position of the source. |
w | 1 | Fourth-dimension value. It drives a slow sub-oscillator that cross-modulates the tone; 0 disables it. |
freq | 220 | Frequency in Hz. |
amp | 0.15 | Amplitude. Pass 0 to silence the slot (there is no delete). |
lfo_rate | 0.5 | Vibrato speed in Hz. |
lfo_depth | 0.02 | Vibrato depth as a fraction of freq. |
wave | "sine" | "sine", "square", "saw", "triangle" or "noise" (stepped noise pitched at freq). |
duty | 0.5 | Square 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.
| Builtin | Parameters |
|---|---|
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:
| Builtin | Returns |
|---|---|
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 gives0, 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) | 载入MIDI | MIDI読込 | 미디로드 | โหลดมิดี | 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
| Builtin | Returns |
|---|---|
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)makestrackcurrent 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, callmusic_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 fordurationseconds (default 0.5) atvelocity0 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
1and0. 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
-1for the master bus.
The main groups:
| Group | Builtins |
|---|---|
| Project | daw_new, daw_project_save(path), daw_project_load(path), daw_set_project_name(name), daw_status |
| Transport and tempo | daw_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) |
| Tracks | daw_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 notes | daw_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) |
| Instruments | daw_inst_presets(track), daw_inst_preset(track, name), daw_inst_params(track), daw_inst_set(track, name, value) |
| Effects | daw_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 undo | daw_bounce(path, start, end, tail, bits, format, quality), daw_render_start(...), daw_undo_push, daw_undo, daw_redo |
| MIDI | daw_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_*andliquid_*have names in all five languages.coll_*andgltf_*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), andrb_floorcatches 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):0for a perfect sphere, rising toward1when 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 blue40, 110, 235and amber240, 175, 45).liquid_rainbow(id, on): colour the fluid as a flowing seven-colour marble (onabove 0.5 turns it on).liquid_draw(id, x, y, scale): copy the grid to the window at pixel(x, y),scalepixels 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).kindis0plane,1sphere (default),2cylinder,3cone or4dome.
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_*toolkit that simulates how a shape sounds. - 3D Shapes and Meshes:
tm_loadand drawing meshes. - Window and Camera:
set_cameraand the frame loop.
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
1for success and0for failure, and leave a message you read withbody_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_drawandbody_draw_creasesruns 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
| Builtin | Purpose |
|---|---|
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.
| Group | Names (defaults) | Meaning |
|---|---|---|
| body | height (1.7), build (1), arm_span (1), head_scale (1) | Scaffold proportions; height also scales imported models |
| body | seal (3) | Voxel radius used to close openings in imported models |
| sim | sr (22050), steps (800), margin (16), up (2) | Sample rate, time steps, air margin in cells, membrane grid refinement |
| medium | c_air (343), c_body (1), rho_body (4), damping (0.002), sponge (8) | Sound speed, body speed and density ratios, loss, absorbing layer |
| mic | mic_sep (0.18), mic_dist (0.15) | Ear spacing and distance in front of the face |
| membrane | relief, coupling, threshold, tension, stiffness, mem_time, mem_every, reinit_every, band, drive_mode, drive_tau | How the skin follows the wave |
| mesh | smooth (3), decimate (0), iso (0) | Smoothing passes, vertex-merge cell size in metres, surface level offset |
| audio | wav_bits (16), wav_gain (0.9), wav_repeat (4), wav_gap (0.25) | WAV export |
| detail | crease_mode, crease_levels, crease_tol, crease_min, detail_level, crease_depth, crease_width, noise_amp, noise_freq | Crease detection and carving |
| listen | sig_dur, sig_sr, sig_rho, sig_excite | The 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-1for 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 aboutmsmilliseconds (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 lastnsamples 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. Withanalyze_onlyset to 1, or when the chunks are missing, it estimates sources from the audio instead, andbody_notes()explains each estimate. WAV, FLAC, Ogg and MP3 are accepted.body_project_save(path)andbody_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:
| Mode | Look |
|---|---|
| 0 | Solid, smoothed normals |
| 1 | Wireframe of every extra-th triangle |
| 2 | Tinted by skin displacement; extra is the full-scale push in millimetres (default 10) |
| 3 | Coloured by surface normal |
| 4 | Single-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
}
}
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 | เมาส์X | Horizontal movement while captured. |
mouse_dy() | 鼠ΔY | マウスΔY | 마우스ΔY | เมาส์Y | Vertical 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, แพดซ้ายY | Left stick, -1 to 1. |
pad_rx(player), pad_ry(player) | 手柄右X, 手柄右Y | パッド右X, パッド右Y | 패드오X, 패드오Y | แพดขวาX, แพดขวาY | Right 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 | เสียงRMS | Loudness 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.
| Group | Names |
|---|---|
| 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 are0until 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,0when idle.mouse_dx(),mouse_dy(): how far the mouse moved since the last frame. Positivedxis right, positivedyis down. They are only non-zero while the mouse is captured.capture_mouse()hides the cursor and switches to relative motion, somouse_dxandmouse_dykeep 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 likepad_buttonthere.pad_lx,pad_ly,pad_rx,pad_ry: stick axes,-1to1. Pushing a stick up gives a negativey, matching the screen. No dead zone is applied, so ignore small values yourself.pad_lt,pad_rt: analog triggers,0(released) to1(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. Usegamepad_rumbleto 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.
| Button | Names |
|---|---|
| bottom face | a, south, cross |
| right face | b, east, circle |
| left face | x, west, square |
| top face | y, north, triangle |
| shoulders | lb, l1, left_shoulder; rb, r1, right_shoulder |
| triggers (digital) | lt, l2, left_trigger; rt, r2, right_trigger |
| start / select | start, menu, options; select, back, share, view |
| guide | guide, home |
| stick clicks | l3, left_stick; r3, right_stick |
| d-pad | up/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):1while held, else0. 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,-1to1) andl2,r2(triggers). Here pushing a stick up gives a positivey, the opposite ofpad_ly.gamepad_rumble(low, high, ms): vibrate the heavy (low) and light (high) motors, each0to1, formsmilliseconds (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():1if 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),0to1.mic_peak(): the highest absolute sample in the latest buffer,0to1.mic_fft(bands): a list ofbands(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
- Window and Camera: the frame loop and
mouse_rayfor picking in 3D. - Fonts and UI:
ui_*controls read the mouse for you. - AI and Language Models: speech-to-text from recorded audio.
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
| Markup | Meaning |
|---|---|
{n}...{/} | A character name (colour role 1). |
{p}...{/} | A place (role 2). |
{i}...{/} | An item (role 3). |
| a newline character | A 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
| Line | Meaning |
|---|---|
# ... | Comment to the end of the line. |
@meta key: value | Metadata about the dataset. Repeatable. |
= label | Start a new conversation. The label is optional. |
speaker: text | One turn. The speaker is the text before the first colon. |
a line without : | Continues the previous turn (joined with a space). |
| a blank line | Ignored. |
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
- Fonts and UI:
font_loadfor the box font. - Input and Microphone:
key_pressedfor advancing. - AI and Language Models: behaviour trees, larger language models and speech.
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
webprofile (andfull, the default). Alingbuilt with--no-default-features --features corestops withunknown function 'http_static'. Reinstall withcargo install ling-langor add--features web.
How a request is answered
- Virtual hosts (
http_vhost) come first. If theHostheader names a registered host, the request is answered from that host’s folder, or redirected if the target is a URL. - Static prefixes (
http_static) come next./css/style.cssunder a/cssprefix is read from disk byte for byte. - Routes (
http_route) come last: method plus exact path. The handler is a Ling function that receives aRequestand returns text or a response record. - Anything else gets
404with the bodynot 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 answers404with the folder’s own404.htmlwhen it has one (mdBook and most static-site generators write one). Use it to put a static site on its own subdomain. - An
http://orhttps://URL: every request to that hostname answers301 Moved Permanentlyto the target plus the request’s path and query. Use it to retire a subdomain without breaking old links.
Details:
hostis matched against theHostheader case-insensitively, with any port ignored.- Vhosts are checked before every
http_staticprefix and route, so a vhost request never reaches your handlers. - Registering several vhosts is fine; each
Hostmatches 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: default8080.workers: default1. 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:
| Field | Content |
|---|---|
method | Upper-case method, such as GET. |
path | Path without the query string. |
query | Raw query string, without the ?. Read it with query_param. |
body | Body as UTF-8. Up to 32 MiB, except multipart uploads (below). |
cookie | Raw Cookie header, or "". Read it with cookie_get. |
authorization | Raw Authorization header, or "". |
client_ip | First 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
startblock runs once, on the main interpreter. Workers only see the program’s declarations, so keep configuration in functions, not in top-levelbinds thatstartchanges. - Each worker opens its own connection to the
db_opendatabase. 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
<b>Ada & 'Bob'</b>
{"name":"say \"hi\"\n"}
a b cA
8080
query_param(qs, name, default): the first value forname, with%XXand+decoded. Works onreq.queryand on form bodies (req.body).cookie_get(header, name, default): one cookie fromreq.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%XXand+.cli_arg(name, default):--name valuefrom the command line, as text. Convert withto_number:cli_arg("port", "8080") + 0gives"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):
db_open,db_exec,db_query. - A Small Web Service: a complete service step by step.
- Networking: lobby networking, SSH and peer-to-peer.
- ling-http and ling-web: the same stack used directly from Rust.
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_openagain replaces it. - With WAL, SQLite keeps two helper files next to the database while it’s open
(
app.db-walandapp.db-shm). Back up all three, or copy the database while no program has it open. - If the file can’t be opened,
db_openraises 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_openis 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 value | Ling value |
|---|---|
INTEGER | number |
REAL | number |
TEXT | text |
NULL | "" (empty text) |
BLOB | base64 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 value | Binds as |
|---|---|
whole number (3) | INTEGER |
fractional number (4.5) | REAL |
true / false | 1 / 0 |
| anything else | TEXT (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_openinstart, beforehttp_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
- Web Server and HTTP: routes, requests, responses and workers.
- A Small Web Service: a complete service step by step.
- ling-http and ling-web: the same SQLite layer used from Rust.
Networking
Ling has four networking families besides HTTP. Pick by what you are building:
| You want | Use | Security |
|---|---|---|
| A game lobby or LAN tool | net_* | Plain text, no authentication. Trusted LANs only. |
| To run commands on a server, or accept SSH clients | ssh_* | SSH-2, host keys pinned, password login. |
| A private request/response service | lingtp_* | Post-quantum handshake, pinned host keys. |
| A peer-to-peer network of nodes with identities | p2p_* | 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()andnet_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.
| Builtin | Purpose |
|---|---|
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_execreturned""with exit code-1instead 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.
| Builtin | Purpose |
|---|---|
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_mldsa87by default, or the path you givelingtp_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_posttreats the first newline as the start of the body, so percent-encode newlines in the path.- The
ling-netRust crate has its ownlingtpmodule with a different wire format. A Linglingtp_getcan’t talk to aling-netserver. 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.
| Builtin | Purpose |
|---|---|
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).
| Key | Meaning |
|---|---|
magic_hex | Required. 8 hex characters; peers with different magic never connect. |
network | Required. Network id, 0–255. |
data_dir | Required. 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. |
peers | List of "host:port" peers to always try. |
identity_seed_hex | 64 hex characters for a long-term identity; omit for a random one. |
ephemeral_outbound | Use a fresh identity per outbound connection (default true). |
max_outbound, max_inbound | Connection limits (defaults 8 and 32). |
proxy | SOCKS5 proxy "ip:port" for all outbound traffic. |
seeds_hex, authority_pk_hex | A signed seed list and the key that must verify it. |
fast_timers | Short timers, for tests. |
Events
p2p_poll returns a list of events, each itself a list:
| First element | Layout |
|---|---|
"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 returnfalseor[]. data_dirholds the node’s identity. Protect it like a private key.
See also
- Web Server and HTTP for
http_*. - Cryptography for the primitives behind
lingtp://andp2p_*.
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:
| Builtins | Profile |
|---|---|
Hashes, crypto_seal/crypto_open, signatures, knot_*, password_* | web or privacy (both carry the crypto building block) |
totp_secret, totp_now | web |
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_keygenandknot_keygenreturn a small number that points into a key table inside the interpreter. Thelw_*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(...)orErr(message). Unwrap it withmatch r { ok(v) => ..., bad(e) => ... }. - Misspelt names are silent. An unknown function evaluates to
(). If a call “does nothing”, check the spelling.
Security guidance
- Use the highest-level builtin that does the job. To encrypt with a key you hold, use
crypto_seal. To store passwords, usepassword_hash. Don’t build your own scheme from hashes and XOR. - Keys must be 32 bytes of real entropy.
crypto_seal,crypto_openand the*_from_seedbuiltins 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 withrandom_hex(32). Turn a passphrase into a key withlw_password_key(Argon2id), never with a single hash. password_hashis for logins,lw_password_keyis for keys.- Never reuse a nonce.
crypto_sealpicks a fresh random nonce every call.lw_aead_sealtakes the nonce from you: userandom_hex(24)for each message. - Don’t use the game RNG for secrets.
randis for gameplay. Userandom_hexorlw_random, which read the operating system’s secure generator. - 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 withlw_key_drop. - Compare with the verify builtins.
==on strings is not constant time. Useed25519_verify,mldsa87_verify,password_verifyandtotp_verify. crypto_hashis not plain SHA3-256. It adds a Ling-specific label, so it won’t match other tools. Usesha256_hexorhash_hexwhen you need to interoperate.- Treat the Ling-specific designs as unaudited. The geometric layer (
knot_points,holo_points,crypto_hash), the DICE-42 cascade insidelingtp://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. - 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.
| Family | Prefix | Public key | Signature | Notes |
|---|---|---|---|---|
| Ed25519 | ed25519_ | 32 bytes | 64 bytes | Classical, fast, deterministic |
| ML-DSA-65 (FIPS 204) | mldsa_ | 1952 bytes | 3309 bytes | Post-quantum, NIST category 3 |
| ML-DSA-87 (FIPS 204) | mldsa87_ | 2592 bytes | 4627 bytes | Post-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_dropdestroys the key and wipes its memory. - Verifiers never fail loudly.
lw_id_verify,lw_ring_verifyandlw_pk_validreturnfalsefor any malformed input.
None of them has a localized alias.
| Builtin | Purpose |
|---|---|
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_image | Keys 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
- Networking:
lingtp://andp2p_*use these primitives. - Web Server and HTTP: sessions, logins and HTTPS.
AI and Language Models
Ling has machine intelligence at three sizes. Each runs on your own machine; nothing is sent to a hosted service.
| Family | What it does | Needs |
|---|---|---|
nn_* | Small feed-forward neural networks you train in a loop | ai profile |
bt_* | Behaviour trees for game characters | ai profile |
dialog_* (learning) | A tiny language model that learns a character’s voice | ai profile |
stt_* | Speech to text with Whisper | ai 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_loadandvision_loadreturn a small number. A failed load returns-1. A bad handle passed to any other function returns a neutral value ([],0,""orfalse) 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_startandvision_analyze_startreturn a job id at once and work on a background thread. Check on them in a loop withsleep(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):ratedefaults 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.
| Builtin | Purpose |
|---|---|
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?
| Builtin | Purpose |
|---|---|
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_cancelonly marks the job as done. The generation keeps running in the background until it reachesmax_tokens, so keepmax_tokensmodest.- 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).
| Builtin | Purpose |
|---|---|
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
- Web Server and HTTP for serving a model to a browser without blocking.
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]
| Subcommand | Purpose |
|---|---|
run | Run a program (JIT by default). |
build | Compile a file or project into a distributable for one or more platforms. |
ast | Draw the syntax tree of a file or project as SVG files. |
visualize | Write one SVG of a file’s syntax tree to standard output. |
convert | Turn 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.
| Flag | Effect |
|---|---|
| (none) | Cranelift JIT, the default. Falls back to the interpreter for the whole program if the JIT can’t compile it. |
--interp | Tree-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 --O3 | JIT 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_serveorlingtp_serve(or a localized alias such asเว็บเสิร์ฟ) run on the interpreter automatically, because the JIT doesn’t support closure arguments yet. Theling file.lingshorthand skips this check, so useling runfor servers. - On the JIT, an unknown function returns
()silently. The interpreter reportsunknown 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,
lingprints[detected language: ...]to standard error before running. - A missing file prints
[ling] error: file does not exist: <path>. Parse errors areerror[parse]: ..., runtime errors areerror[runtime]: ...with a traceback. All of these exit with status 1.
ling build
Compiles a program or a project into a distributable.
| Option | Meaning |
|---|---|
<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. |
--pack | Embed the [includes] resources and the program in the executable, so it is one self-contained file. |
--aot | Compile ahead of time to native code instead of embedding the interpreter. |
| Platform | Aliases | Output |
|---|---|---|
web | WebGL/WebAssembly bundle, built by lingc | |
win | windows | Windows executable |
lin | linux | Linux executable |
mac | macos, darwin | macOS (Intel) executable |
macarm | mac-arm, mac-arm64, macos-arm64, apple-silicon | macOS (Apple Silicon) executable |
pios | pi, raspios, linux-arm64, linarm, arm64 | Raspberry Pi OS / 64-bit ARM Linux |
kernel | bare | LingOS bare-metal kernel image (os profile) |
rpi | raspberrypi | LingOS image for Raspberry Pi (os profile) |
lingos | app, apps | LingOS userland app (os profile) |
lingos-rpi | apps-rpi, app-rpi | LingOS 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.
| Key | Meaning |
|---|---|
name | Project name, used for the executable. |
version | Version string. Default 0.1.0. |
entry | Entry program relative to the manifest. Default main.ling. |
kind | bin (default), web, game, ui, ai, crypto, lib, polyglot, kernel. |
icon | Icon file. |
targets | Default platforms, e.g. targets = ["win", "lin", "web"]. |
pack | pack = true is the same as --pack. |
includes | Resource globs, or an [includes] section with one quoted pattern per line. * matches inside a folder, ** across folders. |
ling-features | Cargo 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.
| Option | Meaning |
|---|---|
[path] | File or directory, default .. |
--technical, --artwork, --ling | Pick one or more drawing styles. With none, all three are made. |
--all | All 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
| Command | Aliases | Purpose |
|---|---|---|
new <name> | create | Create a project folder. |
init | initialize | Create a project in the current folder. |
run | execute, start | Run the project. |
test | verify | Run the project’s tests. |
build | compile, make | Build a native executable. |
clean | purge, clear | Delete build output. |
tree | structure, ls | Print the project tree. |
manifest | show, info | Print the manifest. |
normalize <lang> | norm, localize | Rewrite the project into another language. |
add <package> | install, include | Install a package from the registry. |
search <query> | find, seek | Search the registry. |
publish | release, share | Publish the project. |
login <api-key> | sign-in, auth | Save registry credentials. |
logout | sign-out, deauth | Forget credentials. |
doc | docs, document | Build documentation. |
bench, update | Run cargo bench / cargo update. | |
wizard | guide, create-wizard | Interactive project creator. |
seed | Integrity fingerprint of the project. | |
ast, convert | Forwarded to ling ast / ling convert. | |
check, fmt, translate | Don’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:
| Language | Manifest | Sources | Entry | Tests | Build |
|---|---|---|---|---|---|
| English | Ling.toml | src | start.ling | tests | build |
| 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
cleandeletes the build and lock folders (buildand.lock, or their localized names) and runscargo cleanif there is a Rust crate.treeprints the project’s folder tree.manifestprints 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.
| Option | Effect |
|---|---|
--dry-run, -n | List the changes without touching anything. |
--content-only | Rewrite file contents, keep the names. |
--files-only | Rename 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:
normalizerewrites 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.
| Command | What it does |
|---|---|
login <api-key> | Saves the key to ~/.lingfu/credentials.toml. |
logout | Removes the saved credentials. |
publish | Packs 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
| Option | Meaning |
|---|---|
-o <out.ling> (or --out) | Output path. Default: the input name with .ling. |
--no-compression | Write numbers as plain lists instead of compressed blobs. |
What each format becomes
| Input | Generated bindings | Profile |
|---|---|---|
.gltf, .glb | Per 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>_dur | audio |
.mid, .midi | <name>_notes, a flat list of [time, dur, midi, vel, channel] per note, and <name>_dur | audio |
.svg | <name>_xy (points), <name>_lens (points per polyline), and draw_<name>(ox, oy, scale) | any |
.blend | Exported 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
| Crate | Version | What it is |
|---|---|---|
ling-lang | 2030.1.53 | The 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.19 | The project manager: lingfu new, run, build, normalize and more. See lingfu. |
Compiler
| Crate | Version | What it is |
|---|---|---|
ling-core | 2030.0.9 | Core types, errors and compiler infrastructure. |
ling-lex | 2030.0.8 | Lexical analysis and polyglot tokenization. |
ling-ast | 2030.0.8 | Abstract syntax tree types. |
ling-polyglot | 2030.0.8 | The lexicon system for keywords and builtins in 16+ human languages. |
ling-mir | 2030.0.12 | Mid-level intermediate representation for the code generators. |
ling-codegen | 2030.0.13 | Code generation backends (bytecode, WASM, native). |
ling-macro | 2030.0.8 | Procedural macros for the Ling ecosystem. |
ling-runtime | 2030.0.8 | Runtime support: garbage collector, allocator, standard library. |
ling-wasm | 2030.0.16 | The WebGL2 WebAssembly runtime used by ling build --platform web. |
Graphics, UI and input
| Crate | Version | What it is |
|---|---|---|
ling-graphics | 2030.0.13 | 3D/4D rendering, geometry, animation and font tools. |
ling-gl | 2030.0.10 | GPU rasteriser for projected scenes (wgpu: Vulkan, Metal, DX12; WebGL2 on wasm). |
ling-gpu | 2030.0.10 | GPU compute (CUDA via cudarc, with a CPU fallback). |
ling-ui | 2030.0.9 | Retained-mode widgets and flex layout (ui_*). |
ling-animation | 2030.0.8 | Anima, the unified animation system: one rig, any target. |
ling-input | 2030.0.9 | Sensorium: gamepads, joysticks, haptics, motion, XR controllers, touch controls. |
ling-paint | 2030.0.1 | LingAnime paint engine: layers, brushes, vectors, halftone, 2.5D rigs, pen tablets (art_*). |
ling-icon | 2030.0.9 | Rasterizes SVG/PNG icons to multi-resolution .ico and embeds them in Windows executables (ling build --icon). |
Games and physics
| Crate | Version | What it is |
|---|---|---|
ling-game | 2030.1.9 | Game engine: ECS, physics and scene management. |
ling-physics | 2030.1.18 | Physics, world generation, hyperbolic geometry, glTF loading. |
ling-body | 2030.0.2 | Acoustic bodies: humanoid SDF scaffolds, FDTD wave solver, membranes, mesh and WAV codecs. |
ling-emu | 2030.0.1 | Console-emulation host (emu_*): SNES and N64 cores. |
Audio and music
| Crate | Version | What it is |
|---|---|---|
ling-audio | 2030.0.13 | 4D positional audio synthesis and WAV background music. |
ling-music | 2030.0.9 | Music decoding, BPM and key analysis, synthesis, rhythm-game and karaoke tools. |
ling-mic | 2030.0.12 | Microphone input and real-time audio capture. |
ling-daw | 2030.0.2 | DAW engine behind LingStationX: synth, drums, effects, mixer, sequencer. |
ling-osdaw | 2030.0.2 | LingStation for LingOS: a no_std tracker sequencer and synthesizer. |
Network, web and security
| Crate | Version | What it is |
|---|---|---|
ling-http | 0.1.8 | HTTPS/JSON/SQLite framework on axum. Ling’s http_serve runs on it. See ling-http and ling-web. |
ling-web | 0.1.9 | The Flask-style layer on ling-http: sessions, flash messages, templates, static files, blueprints, CSRF. |
ling-net | 2030.0.9 | Async networking: HTTP, WebSocket, QUIC and peer-to-peer. |
ling-crypto | 2030.1.13 | Post-quantum and classical cryptography: ML-KEM-768, hybrid KEM, AES-GCM, XChaCha20, BLAKE3, SHA-3, Argon2id, Shamir, Schnorr ZKP, VRF. no_std-capable. |
AI
| Crate | Version | What it is |
|---|---|---|
ling-ai | 2030.0.10 | Tensors, neural networks and LLM inference. |
ling-llm | 2030.0.2 | A no_std GGUF inference engine for Qwen3 that runs on the CPU without an operating system (for LingOS). |
ling-diffusion | 2030.0.1 | In-process Stable Diffusion (SD 1.x / SDXL) behind the sd_* builtins. |
LingOS
| Crate | Version | What it is |
|---|---|---|
ling-kernel | 2030.1.37 | Minimal kernel runtime: no_std CPU intrinsics, VGA, serial, boot. |
ling-user | 2030.1.4 | Userland runtime for Ling programs on LingOS. |
Bindings
| Crate | Version | What it is |
|---|---|---|
ling-py | 2030.0.8 | Python 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:
| Profile | Crates |
|---|---|
web | ling-http, ling-crypto, ling-icon, lingfu |
privacy | web plus ling-net, ling-ui |
game | ling-physics, ling-gpu, ling-game, ling-animation, ling-input, ling-body, ling-ui, ling-icon |
ai | ling-ai, ling-music |
audio | ling-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?
| Concern | Ling (http_serve) | Rust with ling-http / ling-web |
|---|---|---|
| Concurrency | One handler at a time on the interpreter | Async handlers on a thread pool |
| JSON bodies | Build and parse by hand | serde structs, Json<T> |
| Sessions, CSRF, flash, templates | Build them yourself from db_* and cookies | Provided by ling-web |
| Response headers and middleware | A fixed set | Any header, any tower layer |
| Edit cycle | Edit and ling run | Compile 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
| Item | What 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 owntower-httplayers 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
| Item | What 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. |
Session | Extractor 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-backednotesCRUD resource with a health check, over HTTP or HTTPS:cargo run -p ling-http --example hello --features dev-certs -- --port 6666crates/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
| Page | Contents |
|---|---|
| Keywords | Reserved words and what each one really does |
| Types | The type names |
| Literals and Operators | How to write values, and the operators |
| Builtins by Crate | Builtin 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. |
where | where | where | where | where | Constraint clause after a function signature. Skipped, no effect. |
post | 出 | 投稿 | 게시 | ส่ง | Reserved word; has no effect. |
give | 予 | 渡す | 전달 | ให้ | Reserved word; has no effect. |
fit | fit | fit | fit | จับคู่ | 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
| Literal | Meaning |
|---|---|
42, 3.14 | Number. 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, false | Boolean |
() | Unit, the “nothing” value |
[1, "two", 3.0] | List; mixed types, indexed from 0 |
0..5 | Range, half-open: 0, 1, 2, 3, 4. Used with for. |
|x| x + 1 | Function 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:
| Operator | Meaning |
|---|---|
. () [] :: .. | Field or method, call, index, path, range |
-x !x | Negate, 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_rgb | HSV转RGB | HSV変換RGB | HSV변환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_begin | SVG开始 | SVG開始 | SVG시작 | เริ่มSVG |
svg_rect | SVG矩形 | SVG矩形 | SVG사각형 | SVGสี่เหลี่ยม |
svg_circle | SVG圆 | SVG円 | SVG원 | SVGวงกลม |
svg_line | SVG线 | SVG線 | SVG선 | SVGเส้น |
svg_polyline | SVG折线 | SVG折れ線 | SVG꺾은선 | SVGเส้นหัก |
svg_text | SVG文字 | SVG文字 | SVG글자 | SVGข้อความ |
svg_end | SVG结束 | 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 | 投影3D | 3D投影 | 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 | 载入MIDI | MIDI読込 | 미디로드 | โหลดมิดี |
music_midi_count | MIDI数量 | MIDI数 | 미디수 | จำนวนมิดี |
music_midi_notes | MIDI音符 | MIDIノート | 미디음표 | โน้ตมิดี |
music_fft | 音乐频谱 | 音楽スペクトル | 음악스펙트럼 | สเปกตรัมเพลง |
music_midi_bars | MIDI音条 | 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
| Part | Built with |
|---|---|
| Torii gate at the far end | vtex_torii |
| Five-tier pagoda behind the gate | vtex_pagoda |
| Altar mandala: gear ring, dharma wheel, lotus, rings | vtex_spiked_cog, vtex_chakra, vtex_lotus, vtex_rings |
| Stone-tile floor with a yantra border | vtex_grid, vtex_yantra |
| Star lantern on the ceiling | vtex_star, vtex_rings |
| Ink-brush panels on the side walls | vtex_letter_rain, vtex_lotus |
| Four corner pillars | vtex_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,JADEandCRIMSONat the top of the file. - Speed up the camera by raising
orbit_spd. - Change the frequencies in
init_audioto 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
| Part | Function in the file |
|---|---|
| Grass, stone path and flower-bed patches | draw_ground |
| Sun disc, drifting clouds and horizon glow | draw_sky |
| Trees with spiral trunks and flower crowns | draw_tree, draw_trees |
| Scattered flower beds | draw_flowers |
| Pond with floating lotus, a fountain and ripples | draw_pond |
| Wooden shed with a door, window and roof | draw_shed |
| Two faint “echo” copies of the scene from earlier frames | draw_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_handorbit_vto move the camera closer or further away. - Move the pond with
PXandPZ, or the shed withSXandSZ. - Change the pentatonic frequencies
PG3toPE4to 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
| Key | Action |
|---|---|
W / S | Walk forward / back |
A / D | Step left / right |
Q / E | Turn left / right |
Space | Jump |
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 factor1 − |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. Trycylinderor another shape from 3D Shapes and Meshes. - Raise the ring limit (
ring <= 4) for a bigger world. - Change
STEPandTURNto 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
| Key | Action |
|---|---|
W / S | Push the ball forward / back |
A / D | Push the ball left / right |
Space | Hold to charge a jump, release to jump |
← / → | Orbit the camera |
↑ / ↓ | Tilt the camera |
Z / X | Zoom 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 byELASTICITY = 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
Spaceon the ground builds up a charge, up toMAX_CHARGE. Releasing it launches the ball. A small meter at the ball shows the charge. - The ball. Drawn as a spinning
vtex_chakrawheel 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_tonevoice 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,DAMPINGandELASTICITYat 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_3dcalls. - Map another value to sound, for example the charge level to the pitch.