Modules
Importing — summon
summon loads a module. Built-in modules (math, strings, os) and installed stdlib modules work by name:
lhj
summon math
summon strings
summon osAfter importing, access the module's functions through dot notation:
lhj
summon math
echo math.sqrt(16) ## 4.0
echo math.floor(3.9) ## 3
echo math.pow(2, 8) ## 256.0Importing from a file
To import from another .lhj file, use the file path (without extension):
lhj
summon "./utils" ## imports utils.lhj from the same directory
summon "../lib/helper" ## relative path
utils.say_hello()Selective import
Pull specific names directly into the current scope:
lhj
summon math pick sqrt, floor, ceil
echo sqrt(9) ## 3.0
echo floor(4.7) ## 4Alias
lhj
summon math as m
echo m.sin(0) ## 0.0Package imports
Packages installed with legion pkg install are importable by name:
lhj
summon legion-colors as colors
colors.red("Error!")
colors.green("Success")Creating a module
Any .lhj file works as a module. Functions and variables defined at the top level are exported automatically:
lhj
## utils.lhj
blade double(n):
release n * 2
blade triple(n):
release n * 3
forge VERSION = "1.0"Then from another file:
lhj
summon "./utils"
echo utils.double(5) ## 10
echo utils.VERSION ## 1.0Standard library modules
| Module | What it has |
|---|---|
math | sqrt, floor, ceil, abs, pow, sin, cos, tan, log, log2, log10, pi, e |
strings | upper, lower, strip, split, join, replace, starts_with, ends_with, contains, pad_left, pad_right |
os | getenv, setenv, getcwd, listdir, path_exists, read_file, write_file, time, sleep, exit |
io | open, close, readline, readlines, write |
collections | Stack, Queue, LinkedList, Counter |
random | rand, randint, choice, shuffle, seed |
json_mod | encode, decode |
stdlib examples
lhj
summon strings
forge s = " Hello, World! "
echo strings.strip(s) ## "Hello, World!"
echo strings.upper(s) ## " HELLO, WORLD! "
echo strings.split("a,b,c", ",") ## ["a", "b", "c"]
echo strings.join(["x", "y", "z"], "-") ## "x-y-z"lhj
summon random
echo random.randint(1, 10) ## random integer 1..10
forge items = ["sword", "axe", "bow"]
echo random.choice(items) ## random item
random.shuffle(items)
echo items