A pure Lua parser for the CNI configuration format using patok and piecemeal.
Usage
First, import the parser and initialize it: local cni = require 'cni':new()
.
You can initialize it later, or initialize multiple parsers.
Then, you can parse some CNI text: local f = cni:parse 'a = b'
.
The return value is the end string index of the parse - you can compare it to the lenght of your input to determine if the parse was complete.
If the parse is impossible (i.e incorrect rather than incomplete), cni:parse
will panic, so call it inside of pcall if that's unacceptable.
CNI is a streaming parser, so you can call parse again.
By default, state is kept, so section headers remain effect.
For instance, cni:parse '[a]'; cni:parse 'b = c'
is equivalent to cni:parse '[a]\nb=c'
.
If you want to reset the internal state, you can call cni:reset()
.
Once you're done parsing (or in-between parses), you can access the internal state.
There are two ways to access it: key-value mode and pseudo-structured mode.
Key-value mode has full keys. For instance, as per above, cni.kv['a.b'] == 'c'
.
Pseudo-structured mode is not native, and needs to be compiled first: local out = cni:compile()
.
Note that the compilation is cached, so calling cni:compile()
multiple times does not carry an additional performance penalty, unless you parse more data.
Afterwards, you can access the configuration data as if it was a standard lua object: out.a.b() == 'c'
.
Note that a call with ()
is required to extract the value, because it is valid for a node to be both a node and a leaf.
Such as with a = b
and a.b = c
.
For an example of use in-code, see the example.lua
file.