Files
rexlang/docs/10-modules-and-stdlib.md
T
Your NameandClaude Opus 5.5 7cf9727bcd Rename the language from Dino to Rex
Files use .rex, the command is rex, and the crate, runtime prefixes,
docs, editor files and examples all use the new name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 13:51:23 +01:00

124 lines
2.7 KiB
Markdown

# 10. Files and the standard library
## 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`:
```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`:
```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`.
- 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.
## 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`.
```rex
import math
func main() {
print(math.sqrt(16), math.pow(2, 10), math.max(3, 9), math.PI)
}
```
```text
4.0 1024.0 9 3.14159265358979
```
### time
`time.now()` gives seconds as a float. `time.sleep(seconds)` waits.
### Strings
`upper lower trim split lines fields replace repeat contains starts_with ends_with
index_of to_int to_float`, plus `len()` and slicing.
```rex
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"))
}
```
```text
[a]
[b]
[c]
xxx hello a+b
2 -1
```
A list of strings can be joined: `["a", "b"].join("-")`.
## A program that reads input
```rex
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](11-cheatsheet.md)