Files and the standard library

You’ll meet: import, os, math, time, rand, tests

Splitting a program into files

import utils brings in the file utils.rex that sits next to your main file. Use its contents with the module name in front. Only things marked pub can be used from outside.

utils.rex:

pub const SCALE = 10

pub struct Vec2 {
    pub x, y: float
    pub func scaled(k: float): Vec2 { return Vec2{x * k, y * k} }
}

pub func double(n: int): int { return n * 2 }

func secret() {} // private: only this file can call it

main.rex:

import utils

func main() {
    print(utils.double(4), utils.SCALE)
    var v = utils.Vec2{1.0, 2.0}
    print(v.scaled(3.0))
}
  • Folders work too: import tools.fs is the file tools/fs.rex, used as fs.name.
  • Dots at the start go up a folder: import ..shared.utils is ../shared/utils.rex, and import ...engine.engine is ../../engine/engine.rex (one dot fewer than the number of folders up, so .. is one folder up, ... is two). It is still used as utils.name / engine.name. Every import is counted from the folder of the file you run, also inside other files, so a file in engine/ that needs its neighbour engine/util.rex writes the same path as you would.
  • Fields are private as well unless written pub x: int.
  • Every file has its own names, so two files can both define helper.
  • Import loops and missing files are errors. An error message names the file it is in.

Bigger projects

When a project has several folders, put an empty file named rex.toml in its top folder. Every import is then counted from that folder, in every file, wherever the file sits:

Klein/
  rex.toml
  engine/engine.rex
  game/app/main.rex
import engine.engine // the same line works in game/app/main.rex and in any other file

rex init writes one for you. The same file lists the packages the project uses (see chapter 14).

Rex finds the nearest rex.toml above the file you run (and above each file you open in an editor). Without one, imports are counted from the folder of the file you run, as above. With one, even a file next to your main file is imported with its full path (import game.app.util).

Built-in modules

Import them like your own files: import os.

os

os.args list of command-line words (args[0] is the program)
os.read_file(path) (string, error)
os.write_file(path, text) error
os.append_file(path, text) error
os.exists(path) bool
os.read_line() next line typed on the keyboard, or nil at the end
os.env(name) the environment variable, or nil
os.exit(code) stop the program

math

sqrt pow floor ceil round trunc sin cos tan asin acos atan atan2 exp log log10 hypot min max abs, and the values PI and E.

import math

func main() {
    print(math.sqrt(16), math.pow(2, 10), math.max(3, 9), math.PI)
}
4.0 1024.0 9 3.14159265358979

time

time.now() gives seconds as a float. time.sleep(seconds) waits.

rand

rand.int(a, b) a whole number from a up to, not including, b (like a..b)
rand.float() a number from 0 up to, not including, 1
rand.seed(n) start from a fixed point: the same seed gives the same numbers every run

Without rand.seed, every run gives different numbers.

import rand

func main() {
    var die = rand.int(1, 7) // 1 to 6
    print(die >= 1 && die <= 6)
    var hit = rand.float() < 0.25 // true one time in four
    print(hit == true || hit == false)
}
true
true

Not for passwords or keys: it is fast, not secure.

Strings

upper lower trim split lines fields replace repeat contains starts_with ends_with index_of to_int to_float, plus len() and slicing.

func main() {
    var csv = " a, b ,c "
    for part in csv.split(",") {
        print("[" + part.trim() + "]")
    }
    print("x".repeat(3), "Hello".lower(), "a-b".replace("-", "+"))
    print("hello".index_of("l"), "hello".index_of("z"))
}
[a]
[b]
[c]
xxx hello a+b
2 -1

A list of strings can be joined: ["a", "b"].join("-").

Testing

assert(condition) stops the program when the condition is false, with the line it is on. Add a message as a second argument: assert(n > 0, "n is {n}").

Write tests as functions whose names start with test_, in any .rex file. They take nothing and return nothing, or an error (a returned error fails the test).

func add(a, b: int): int {
    return a + b
}

func test_add() {
    assert(add(2, 2) == 4)
    assert(add(-1, 1) == 0, "adding opposites")
}

func test_parse(): error {
    var n = "42".to_int()?
    assert(n == 42)
    return nil
}

rex test runs the tests in every .rex file in this folder and the folders below it (or rex test file.rex, rex test folder):

ok    calc.rex: test_add
ok    calc.rex: test_parse

2 passed, 0 failed

Every test runs on its own, so one that fails (or stops with a panic) doesn’t stop the rest. What a failed test printed is shown under it. A file’s main is not run by rex test.

A program that reads input

import os

func main() {
    var total = 0
    for {
        var line = os.read_line()
        if line == nil { break }
        var n, err = line.trim().to_int()
        if err != nil {
            print("skipping:", line)
            continue
        }
        total += n
    }
    print("total", total)
}

Next: Cheatsheet

Spotted a mistake? This page comes fromdocs/10-modules-and-stdlib.md in the Rex repo.