Skip to content

SwaziLang Complete Reference

Comprehensive tabular reference for SwaziLang built-in globals, objects, modules, methods, and runtime behaviors.


Table of Contents

  1. Quick Start
  2. Global Functions
  3. Global Objects
  4. Built-in Modules
  5. Member Methods by Type
  6. Muda Time API
  7. Async API & Event Loop
  8. Module System
  9. Error Handling
  10. Common Patterns
  11. Troubleshooting

1. Quick Start

Running Programs

CommandDescription
swazi main.slRun with explicit .sl extension
swazi main.swzRun with explicit .swz extension
swazi mainAuto-tries: main, main.sl, main.swz

Key Rules

  • Entry file starts in global environment
  • Import other modules using tumia
  • Use relative paths for local files: tumia "./math.sl"
  • Use bare names for built-ins: tumia "fs"

2. Global Functions

FunctionParametersReturnsDescription
ainaya()valuestringInspect runtime type: "namba", "neno", "bool", "null", "object", "muundo", "orodha", "kazi"
Orodha()...argsarrayCreate array: () → empty, (n) → length n, (a,b,c) → [a,b,c]
Bool()valuebooleanConvert to boolean using Swazi truthiness
Namba()valuenumberConvert to number (floating point)
Neno()valuestringConvert to string
soma()prompt?stringRead line from stdin, optional prompt
Makosa()msg?throwsThrow runtime error with message
thibitisha()cond, msg?void/throwsAssert condition is truthy, throw if false
muda()...argsnumber/stringFlexible date/time helper (see Muda section)
NOW_MS()-numberCurrent epoch milliseconds (UTC)

Examples

swazi
chapisha ainaya(42)              // "namba"
data arr = Orodha(1,2,3)         // [1,2,3]
data name = soma("Name: ")       // Read input
thibitisha(x > 0, "x must be positive")

3. Global Objects

3.1 Object Utilities

MethodParametersReturnsDescription
Object.keys()objarrayArray of property names (strings)
Object.values()objarrayArray of property values
Object.entry()objarrayArray of [key, value] pairs

Example:

swazi
data person = { name: "Amina", age: 20 }
chapisha Object.keys(person)    // ["name", "age"]
chapisha Object.values(person)  // ["Amina", 20]

3.2 Hesabu (Math & Statistics)

Basic Math Operations

MethodParametersReturnsDescription
kadiria()xnumberRound to nearest integer
kadiriajuu()xnumberCeiling (round up)
kadiriachini()xnumberFloor (round down)
kubwa()a,b,...numberMaximum value
ndogo()a,b,...numberMinimum value
alama()xnumberSign: 1, -1, or 0

Logarithmic & Trigonometric

MethodParametersReturnsDescription
log()n, base?numberlog₁₀(n) or logₓ(n) if base provided
ln()nnumberNatural logarithm
sin()xnumberSine (radians)
cos()xnumberCosine (radians)
tan()xnumberTangent (radians)
hypot()x1,x2,...numberEuclidean distance

Random & Conversion

MethodParametersReturnsDescription
rand()-numberRandom in [0,1)
rand()anumberRandom in [0,a)
rand()a,bnumberRandom in [a,b)
deg2rad()degreesnumberConvert degrees to radians
rad2deg()radiansnumberConvert radians to degrees

Integer Math

MethodParametersReturnsDescription
gcd()a,bnumberGreatest common divisor
lcm()a,bnumberLeast common multiple

Statistics

MethodParametersReturnsDescription
mean()...values or arraynumberArithmetic mean
median()...values or arraynumberMedian value
stddev()...values or arraynumberStandard deviation

Utility

MethodParametersReturnsDescription
siNambaSahihi()xbooleanCheck if value is NaN
kadiriaKtkDes()x, digitsnumberRound to decimal places

Examples:

swazi
chapisha Hesabu.kadiria(3.7)           // 4
chapisha Hesabu.kubwa(1,5,3)           // 5
chapisha Hesabu.rand(1,10)             // Random between 1-10
chapisha Hesabu.mean(1,2,3,4,5)        // 3

3.3 swazi Object

MethodParametersReturnsDescription
swazi.exit()code?-Exit process (default code 0)

4. Built-in Modules

Import Syntax: tumia "module_name"
⚠️ Must use double quotes!

4.1 regex Module

MethodParametersReturnsDescription
match()str, pattern, flags?array/nullMatch pattern; with 'g' returns all matches
test()str, pattern, flags?booleanTest if pattern exists
fullMatch()str, pattern, flags?booleanTest if entire string matches
search()str, pattern, flags?numberIndex of first match or -1
replace()str, pattern, replacement, flags?stringReplace matches (all with 'g')
split()str, pattern, flags?arraySplit by pattern

Flags:

  • g = global (find all)
  • i = case insensitive
  • m = multiline (^/$ per line)

Example:

swazi
tumia "regex"
data matches = regex.match("a1 b2 c3", "\\w\\d", "g")
chapisha matches  // ["a1", "b2", "c3"]

4.2 fs (File System) Module

MethodParametersReturnsDescription
readFile()pathstring/nullRead file contents or null if not found
writeFile()path, content, binary?booleanWrite file, returns success
exists()pathbooleanCheck if path exists
listDir()path?arrayList directory contents (default ".")
copy()src, dest, overwrite?booleanCopy file/directory
move()src, dest, overwrite?booleanMove/rename file
remove()pathbooleanDelete file/directory recursively
makeDir()path, recursive?booleanCreate directory
stat()pathobjectGet file metadata

stat() Returns:

swazi
{
  exists: boolean,
  isFile: boolean,
  isDir: boolean,
  size: number,        // bytes
  modifiedAt: string,  // ISO8601 UTC
  permissions: string  // e.g. "rw-"
}

Example:

swazi
tumia "fs"
data content = fs.readFile("notes.txt")
kama content null:
  chapisha "File not found"
sawa:
  chapisha content

4.3 http Module

MethodParametersReturnsDescription
get()url, headers?stringHTTP GET request
post()url, body, contentType?, headers?stringHTTP POST request

⚠️ Requires libcurl at build time

Example:

swazi
tumia "http"
data body = http.get("https://api.example.com/data")
chapisha body

4.4 json Module

MethodParametersReturnsDescription
parse()stringvalueParse JSON string to Swazi value
stringify()valuestringConvert Swazi value to JSON string

Example:

swazi
tumia "json"
data obj = json.parse('{"name":"Amina","age":25}')
chapisha obj.name  // "Amina"

data text = json.stringify({ x: 1, y: 2 })
chapisha text  // {"x":1,"y":2}

4.5 path Module

MethodParametersReturnsDescription
join()...segmentsstringJoin path segments (normalized)
basename()pathstringExtract filename
dirname()pathstringExtract directory
extname()pathstringExtract extension (with dot)
resolve()...segmentsstringResolve to absolute path

Example:

swazi
tumia "path"
data full = path.join("/home", "user", "file.txt")
chapisha full  // /home/user/file.txt

4.6 os Module

MethodParametersReturnsDescription
platform()-stringOS: "windows", "macos", "linux", "unknown"
cwd()-stringCurrent working directory
hostname()-stringMachine hostname
tmpdir()-stringSystem temp directory
cpus()-numberCPU core count

4.7 process Module

MethodParametersReturnsDescription
getEnv()namestring/nullGet environment variable
setEnv()name, valuebooleanSet environment variable
unsetEnv()namebooleanRemove environment variable
pid()-numberProcess ID

4.8 async Module

MethodParametersReturnsDescription
subiri()cb, ...argsvoidEnqueue callback for next tick
setTimeout()ms, cb or cb, msnumberSchedule single-shot callback, returns ID
clearTimeout()idvoidCancel timeout
setInterval()ms, cb or cb, msnumberSchedule repeating callback, returns ID
clearInterval()idvoidCancel interval
nap()ms or ms, cb or cb, msnumberDelay or schedule callback

Example:

swazi
tumia "async"

async.setTimeout(1000, () => chapisha "1 second later")

data id = async.setInterval(500, () => chapisha "tick")
async.setTimeout(3000, () => async.clearInterval(id))

5. Member Methods by Type

5.1 Universal Properties

Available on all values:

PropertyTypeDescription
.ainastringType name (same as ainaya())
.ninambabooleanIs number?
.ninenobooleanIs string?
.niboolbooleanIs boolean?
.niorodhabooleanIs array?
.nikazibooleanIs function?

5.2 String Methods

Property/MethodReturnsDescription
.herufinumberString length
.herufiNdogo()stringTo lowercase
.herufiKubwa()stringTo uppercase
.sawazisha()stringTrim whitespace
.huanzaNa(prefix)booleanStarts with prefix?
.huishaNa(suffix)booleanEnds with suffix?
.kuna(sub)booleanContains substring?
.tafuta(sub, from?)numberIndex of substring (-1 if not found)
.slesi(start?, end?)stringExtract substring
.badilisha(old, new)stringReplace first occurrence
.badilishaZote(old, new)stringReplace all occurrences
.orodhesha(sep?)arraySplit into array
.unganisha(other)stringConcatenate strings
.rudia(n)stringRepeat n times
.herufiYa(index)stringCharacter at index

Example:

swazi
data s = "  Hello World  "
chapisha s.sawazisha()           // "Hello World"
chapisha s.herufiKubwa()         // "  HELLO WORLD  "
chapisha "abc".rudia(3)          // "abcabcabc"
data arr = "a,b,c".orodhesha(",") // ["a","b","c"]

5.3 Number Methods

Properties (Boolean)

PropertyDescription
.siSahihiIs NaN?
.infIs infinite?
.nzimaIs integer?
.desimaliHas fractional part?
.chanyaIs positive?
.hasiIs negative?
.witiriIs odd integer?
.shufwaIs even integer?
.tasaIs prime? (integers only)

Methods

MethodReturnsDescription
.abs()numberAbsolute value
.kadiria()numberRound to nearest
.kadiriajuu()numberCeiling
.kadiriachini()numberFloor
.kipeo(b?)numberPower (default: square)
.kipeuo(b?)numberRoot (default: square root)
.kubwa(...)numberMax with other values
.ndogo(...)numberMin with other values
.kadiriaKwa(digits?)stringFormat to fixed decimals
.kwaKiwango(factor)numberMultiply by factor

Example:

swazi
chapisha (3.7).kadiria()     // 4
chapisha (2).kipeo(3)        // 8
chapisha (16).kipeuo()       // 4
chapisha (5).tasa            // kweli (true)

5.4 Array Methods

Property/MethodReturnsDescription
.idadinumberArray length
.ongeza(...values)numberPush (returns new length)
.toa()valuePop from end
.ondoa(value)booleanRemove first occurrence
.ondoaZote(value)numberRemove all occurrences (returns count)
.ondoaMwanzo()valueShift (remove from start)
.ongezaMwanzo(...values)numberUnshift (insert at start)
.ingiza(value, index)numberInsert at index
.futa()voidClear array
.panua(otherArray)arrayConcat (returns new array)
.geuza()arrayReverse in place
.panga(comparator?)arraySort in place
.indexYa(value, start?)numberIndex of value (-1 if not found)
.tafuta(fn)valueFind first matching element
.tafutaIndex(fn)numberIndex of first match
.kuna(value)booleanContains value?
.slesi(start?, end?)arraySlice (new array)
.pachika(start, count, ...items)arraySplice (returns removed)
.badili(fn)arrayMap (new array)
.chambua(fn)arrayFilter (new array)
.punguza(fn, initial?)valueReduce
.unganisha(separator?)stringJoin to string

Example:

swazi
data arr = Orodha(1,2,3)
arr.ongeza(4)              // [1,2,3,4]
arr.panga()                // Sort in place
data doubled = arr.badili(x => x * 2)
data evens = arr.chambua(x => x.shufwa)

6. Muda (Time) API

6.1 muda() Function Signatures

SignatureReturnsDescription
muda()numberCurrent epoch milliseconds
muda("ms")numberCurrent epoch milliseconds
muda(formatString)stringFormat current time
muda(ms, format)stringFormat given milliseconds
muda(dateString)numberParse date to epoch ms
muda(dateString, format)numberParse with custom format
muda(dateString, format, zone)numberParse in specific timezone

6.2 Muda Class Constructor

ConstructorDescription
unda Muda()Current time
unda Muda(ms)From epoch milliseconds
unda Muda("ISO-string")Parse ISO date string
unda Muda(year, month, day, hour?, min?, sec?)From components

6.3 Muda Instance Methods

Getters

MethodReturnsDescription
.mwaka()numberYear
.mwezi()numberMonth (1-12)
.tarehe()numberDay of month
.sikuYaJuma(fmt?)number/stringDay of week
.saa(fmt?)number/stringHour
.dakika()numberMinutes
.sekunde()numberSeconds
.millis()numberMilliseconds (0-999)
.ms()numberEpoch milliseconds
.zone()stringTimezone (always "UTC")

Formatters

MethodReturnsDescription
.fmt(format, zone?)stringFormat with tokens
.iso()stringISO 8601 format
.object()objectObject with all components

Comparisons

MethodReturnsDescription
.eq(other)booleanEqual to?
.gt(other)booleanGreater than?
.lt(other)booleanLess than?
.diff(other, unit?)numberDifference (default: ms)

Arithmetic (Returns new Muda instance)

MethodReturnsDescription
.ongeza(unit, amount)MudaAdd time
.punguza(unit, amount)MudaSubtract time
.setiMuda(field, value)MudaSet specific field

6.4 Time Units

Unit StringAliasesDescription
"sekunde""s"Seconds
"dakika""m", "dk"Minutes
"saa""masaa", "h"Hours
"siku""d"Days
"wiki"-Weeks
"mwezi""miezi", "M"Months
"mwaka""miaka", "y"Years

6.5 Format Tokens

TokenOutputExample
YYYY4-digit year2025
YY2-digit year25
MMMMFull month nameOctober
MMMShort month nameOct
MMMonth zero-padded10
MMonth number10
DDDay zero-padded14
DDay number14
DoDay with ordinal14th
ddddFull weekdayTuesday
dddShort weekdayTue
HHHour 24h padded19
HHour 24h19
hhHour 12h padded07
hHour 12h7
mmMinutes padded05
mMinutes5
ssSeconds padded03
sSeconds3
SSSMilliseconds123
a / Aam/pmpm / PM
ZZTimezone offset+0000
ZTimezone offset+00:00
xUnix milliseconds1729023456789
XUnix seconds1729023456

Example:

swazi
data d = unda Muda(2025, 10, 14, 15, 30)
chapisha d.fmt("YYYY-MM-DD HH:mm:ss")  // "2025-10-14 15:30:00"
chapisha d.fmt("MMMM Do, YYYY")        // "October 14th, 2025"

data future = d.ongeza("siku", 7)
chapisha future.iso()

7. Async API & Event Loop

7.1 Event Loop Behavior

ConceptDescription
Callback ExecutionAll callbacks run on main evaluator thread
Timer ThreadsDetached worker threads enqueue callbacks when timers fire
Queue SafetyThread-safe queue for callback scheduling
Loop ExitEvent loop exits when queue is empty and no active timers
Error HandlingExceptions in callbacks are caught and logged (don't crash loop)

7.2 Scheduling Guarantees

GuaranteeDescription
OrderCallbacks execute in FIFO order from queue
Single-threadedNo concurrent callback execution
IsolationEach callback runs to completion before next
Best-effort timingTimers fire approximately at specified delay

8. Module System

8.1 Import Syntax

SyntaxDescription
tumia "module"Import entire module
tumia "./file.sl"Import local file
tumia {a, b} kutoka "module"Named imports
tumia a kutoka "module"Default import
tumia * kutoka "module"Wildcard import
tumia {a kama x} kutoka "module"Aliased import

⚠️ Must use double quotes for module specifiers


8.2 Export Syntax

SyntaxDescription
ruhusu nameExport single binding (default)
ruhusu {a, b}Named exports
ruhusu objExport object

⚠️ Only one ruhusu per file, must be last statement


8.3 Module Resolution

StepDescription
1Check built-in modules first
2If absolute path, use directly
3If relative, resolve from requester's directory
4Try: spec, spec.sl, spec.swz
5Cache module by canonical path

8.4 Circular Dependencies

BehaviorDescription
AllowedCircular imports don't deadlock
Partial InitExports may be incomplete during cycle
Best PracticeAvoid cycles, extract shared utilities
Cache EntryModule added to cache before evaluation

9. Error Handling

9.1 Error Functions

FunctionUsageDescription
Makosa(msg)Makosa("error")Throw runtime error
thibitisha(cond, msg)thibitisha(x > 0, "positive")Assert or throw

9.2 Try/Catch/Finally

KeywordSwaziDescription
tryjaribuTry block
catchmakosaCatch block
finallykishaFinally block

10. Common Patterns

10.1 File I/O with JSON

swazi
tumia "fs"
tumia "json"

data txt = fs.readFile("data.json")
kama txt null:
  chapisha "File not found"
sawa:
  data obj = json.parse(txt)
  chapisha obj.name

10.2 HTTP + JSON

swazi
tumia "http"
tumia "json"

data response = http.get("https://api.example.com/users")
data users = json.parse(response)
chapisha users[0].name

10.3 Scheduled Tasks

swazi
tumia "async"

data count = 0
data id = async.setInterval(1000, () => {
  count++
  chapisha `Tick ${count}`
  
  kama count == 5:
    async.clearInterval(id)
    chapisha "Done!"
})

10.4 Module Structure

math.sl:

swazi
kazi add(a, b) {
  rudisha a + b
}

kazi multiply(a, b) {
  rudisha a * b
}

ruhusu { add, multiply }

main.sl:

swazi
tumia { add, multiply } kutoka "./math.sl"

chapisha add(2, 3)       // 5
chapisha multiply(4, 5)  // 20

10.5 Date Arithmetic

swazi
data today = unda Muda()
data nextWeek = today.ongeza("siku", 7)
data lastMonth = today.punguza("mwezi", 1)

chapisha today.fmt("YYYY-MM-DD")
chapisha nextWeek.fmt("YYYY-MM-DD")
chapisha lastMonth.fmt("MMMM YYYY")

11. Troubleshooting

11.1 Common Pitfalls

IssueSolution
Wrong quotes in importsAlways use double quotes: tumia "fs"
Code after ruhusuCode after export statement won't run
Circular importsExtract shared code to third module
Mixed chagua stylesUse consistent : or {} in switch cases
Timer not firingEnsure event loop runs (program stays alive)
Regex limitationsstd::regex may not support all JS features
HTTP not workingCheck if libcurl available at build time
Precision issuesUse integers within 53-bit range for exact math

11.2 Debugging Checklist

CheckAction
Type errorsUse ainaya() or .aina to inspect types
Module not foundCheck path, extension, and quotes
Undefined variablesCheck scope and module exports
Async not workingVerify callback syntax and timer IDs
Date parsing failsCheck format string matches input
File operations failUse fs.exists() and fs.stat() to debug

12. Quick Reference Card

Most Used Functions

swazi
// Console
chapisha "Hello"
data input = soma("Prompt: ")

// Types
ainaya(value)
Bool(x), Namba(x), Neno(x)

// Arrays
data arr = Orodha(1,2,3)
arr.ongeza(4)
arr.panga()

// Objects
Object.keys(obj)
Object.values(obj)

// Math
Hesabu.kadiria(3.7)
Hesabu.rand(1, 10)
Hesabu.mean(1,2,3)

// Time
data now = muda("YYYY-MM-DD")
data d = unda Muda()
d.ongeza("siku", 1)

// Modules
tumia "fs"
tumia { add } kutoka "./math.sl"

// Async
async.setTimeout(1000, () => chapisha "Hi")

Appendix