Janet 1.38.0-73334f3 Documentation
(Other Versions:
1.37.1
1.36.0
1.35.0
1.34.0
1.31.0
1.29.1
1.28.0
1.27.0
1.26.0
1.25.1
1.24.0
1.23.0
1.22.0
1.21.0
1.20.0
1.19.0
1.18.1
1.17.1
1.16.1
1.15.0
1.13.1
1.12.2
1.11.1
1.10.1
1.9.1
1.8.1
1.7.0
1.6.0
1.5.1
1.5.0
1.4.0
1.3.1
)
Tables
The table is one of the most flexible data structures in Janet and is modeled after the associative array or dictionary. Values are put into a table with a key, and can be looked up later with the same key. Tables are implemented with an underlying open hash table, so they are quite fast and cache friendly.
Any Janet value except nil
and math/nan
can be a key or
a value in a Janet table, and a single Janet table can have any
mixture of types as keys and values.
Creating tables
The easiest way to create a table is via a table literal.
(def my-tab @{
:key1 1
"hello" "world!"
1 2
'(1 0) @{:another :table}})
Another way to create a table is via the table
function. This has the
advantage that table
is an ordinary function that can be passed around
like any other. For most cases, a table literal should be preferred.
(def my-tab (table
:key1 1
"hello" "world!"
1 2
'(1 0) @{:another :table}))
Getting and setting values
Like other data structures in Janet, values in a table can be retrieved with
the get
function, and new values in a table can be added via the
put
function or the set
special. Inserting a value of nil
into a table removes the key from the table. This means tables cannot contain
nil
values.
(def t @{})
(get t :key) #-> nil
(put t :key "hello")
(get t :key) #-> "hello")
(set (t :cheese) :cake)
(get t :cheese) #-> :cake
# Tables can be called as functions
# that look up the argument
(t :cheese) #-> :cake
Prototypes
All tables can have a prototype, a parent table that is checked when a key is not found in the first table. By default, tables have no prototype. Prototypes are a flexible mechanism that, among other things, can be used to implement inheritance in Janet. Read more in the documentation for prototypes.
Useful functions for tables
The Janet core library has many useful functions for manipulating tables. Below is a non-exhaustive list.
frequencies
keys
kvs
length
merge-into
merge
pairs
post-walk
pre-walk
table/getproto
table/setproto
update
values
walk
zipcoll
See the Table API documentation for table-specific functions.