Skip to content
TheFlyingFiddle edited this page Jul 11, 2015 · 13 revisions

This tutorial will show you how to encode a value in the TIER format. To keep it simple we will encode an integer value. Let's get started!

First we need to access the encoding api. This is done by importing the tier module. This module contains all that we need to encode values.

local tier = require"tier"

Before we can begin encoding we need an output stream to write to. This can be any output stream but for this tutorial we will use a normal file stream.

--Open a file stream in binary write mode.
local output_stream = assert(io.open("Encoded.dat", "wb"))

To encode data we need a writer and a encoding object.

local writer  = tier.writer(output_stream)
local encoder = tier.encoder(writer)

We also need something to encode.

local the_meaning_of_life = 42

Now that we have something to encode we need to create a mapping from the lua value to the encoding representation. The encoding.primitive module contains a set of standard mappings for numbers. For now we will use int32 representation. That is the number will occupy 4 bytes in the output.

local mapping = tier.primitive.int32

Our setup is now complete and we can start encoding. This is done by calling the encode method on the encoder object with the mapping of our choice and the data.

encoder:encode(mapping, the_meaning_of_life)

Now we could continue and encode more values to the output stream, but for now, we are done. To complete the encoding we need to close the encoder, flushing any temporary data. We also close the file stream. After closing the encoder we can no longer encode values through it.

encoder:close()
output_stream:clear()

This marks the end of this tutorial. In the next tutorial Decoding a value we will see how to decode the value we just encoded.

###Full code of the tutorial

local tier = require"tier"

local output_stream = assert(io.open("Encoding.dat", "wb"))
local writer  = tier.writer(output_stream)
local encoder = tier.encoder(writer)

local the_meaning_of_life = 42
local mapping = tier.primitive.int32

encoder:encode(mapping, the_meaning_of_life)
encoder:close()
output_stream:close()

Clone this wiki locally