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 os

After 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.0

Importing 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) ## 4

Alias

lhj
summon math as m

echo m.sin(0)   ## 0.0

Package 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.0

Standard library modules

ModuleWhat it has
mathsqrt, floor, ceil, abs, pow, sin, cos, tan, log, log2, log10, pi, e
stringsupper, lower, strip, split, join, replace, starts_with, ends_with, contains, pad_left, pad_right
osgetenv, setenv, getcwd, listdir, path_exists, read_file, write_file, time, sleep, exit
ioopen, close, readline, readlines, write
collectionsStack, Queue, LinkedList, Counter
randomrand, randint, choice, shuffle, seed
json_modencode, 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