Contents

Searching...

Serialization

Defalte & Inflate

All of your data resides in memory during execution. Once your program concludes, the data is lost.

Serializing data to disk preserves its structure to be used later. Multiple programs can access the same information from disk. Kal embeds extra information in binary form so that it can be read more efficiently.

Values of any of the 5 primitive types can be serialized using the
binWrite
statement.
var data = "Secret".
binWrite data "file.bin".

serialize.kal

A file named
file.bin
should appear in your directory. Use
binRead
to deserialize the file back into a variable.
binRead "file.bin" -> value.
stdout value "\n".

deserialize.kal

You can serialize complex information to a binary file.
var data = #(
    name -> "Earth",
    category -> "Planet",
    moon -> 1,
    biomes -> [
        "Desert",
        "Forests",
        "Mountains",
        "Oceans"
    ],
    aliens -> null
).
binWrite data "earth.bin".

writeEarth.kal

Deserialize it back:
binRead "earth.bin" -> data.
stdout data "\n".

readEarth.kal

Kal takes serialization further allowing you to serialize your programs into special files called KAST (Kal Abstract Syntax Tree) files.

A KAST file is a single bundle of your entire project. It preserves the parsed code, preprocesses imported source files all in one single distributable file.

Consider the following code example which revisits the greet function:
fn greet -> name {
    stdout "Hello " name "\n".
}

lib.kal

@lib
:greet "Earth".

main.kal

The following example is made up of two files:
lib.kal
and
main.kal
with
main.kal
being the entry point. While distribution, you'll always be required to pair these files together keeping the folder structure intact. One cannot run without the other. You may also have third party packages included in your project.

You can easily generate a single, bundled and distributable KAST file using the
-k
flag.
$ kal -k main.kal
This produces a
main.kast
file in the same folder. Run the KAST file like any other Kal program.
$ kal main.kast
Try deleting the
main.kal
and
greet.kal
files.
main.kast
will still execute since it's now independent of the original source code.

You can produce a KAST file with some other name by pairing the
-k
flag with the
-o
flag.
$ kal -k main.kal -o project
$ kal project.kast
Never manually modify a generated KAST file. Kal can fail at executing a KAST file with modified encoding.