Skip to content

Quickstart Guide

Aeron Avery edited this page Jul 19, 2019 · 2 revisions

This page will give a quick tutorial on how to use zig-toml.

There are only two functions that are related to parsing: parseFile and parseContents.

parseFile requires a std.mem.Allocator and a filename.

parseContents requires a std.mem.Allocator and a string containing the TOML that is to be parsed.

pub fn parseFile(allocator: *std.mem.Allocator, filename: []const u8) !*Table
pub fn parseContents(allocator: *std.mem.Allocator, contents: []const u8) !*Table

Both have a potential to return errors, if there are no errors they return a *Table. Table has a function deinit that will clean up all of its children tables and all of its key-value pairs.

// main.zig
const std = @import("std");

pub fn main() !void {
    var table = try parseContents(std.heap.c_allocator, 
      \\ [foo]
      \\ bar="foobar"
      \\
    );
    defer table.deinit();
}

Now that we have a Table we can retrieve key-value pairs and other tables. The Table that is returned from the parse functions is called the "global table." It has no name and is the root table for all other tables defined within the file.

To get a key-value pair, use the function table.getKey. This function takes the key name as a string. If the key-value pair is found it returns a Value.

Value is a tagged union that contains is defined as follows:

const Value = union(enum) {
    None, // the user should never see this value
    String: []const u8,
    Boolean: bool,
    Integer: i64,
    Array: DynamicArray,
};

where DynamicArray is a std.TailQueue(Value).

To get a table, use the function table.getTable. This function takes the table name as a string. If the table is found it returns a Table.

There are plans for a function that lets you easily specify the path as a string, e.g. getKeyWithPath("foo.bar"), but until then getKey and getTable are not recursive so you need to manually type function calls to get to your desired path.

// main.zig
const std = @import("std");

pub fn main() !void {
    var table = try parseContents(std.heap.c_allocator, 
      \\ [foo]
      \\ bar="foobar"
      \\
    );
    defer table.deinit();
    if (table.getTable("foo")) |foo| {
        if (foo.getKey("bar")) |bar| {
            std.debug.assert(std.mem.eql(u8, bar.String, "foobar"));
        }
    }
}
Clone this wiki locally