LGI Variant support

LGI provides extended overrides for supporting GLib's GVariant type. it supports folloing operations with variants:

Creation

Variants should be created using GLib.Variant(type, value) constructor. Type is either GLib.VariantType or just plain string describing requested type of the variant. Following types are supported:

There are two convenience exceptions from above rules: - when array of dictionary entries is met (i.e. dictionary), value is expected to contain Lua table with keys and values mapping to dictionary keys and values - when array of bytes is met, a bytestring is expected in the form of Lua string, not array of byte numbers.

Some examples creating valid variants follow:

GLib = require('lgi').Glib
local v1 = GLib.Variant('s', 'Hello')
local v2 = GLib.Variant('d', 3.14)
local v3 = GLib.Variant('ms', nil)
local v4 = GLib.Variant('v', v3)
local v5 = GLib.Variant('as', { 'Hello', 'world' })
local v6 = GLib.Variant('ami', { 1, nil, 2, n = 3 })
local v7 = GLib.Variant('(is)', { 100, 'title' })
local v8 = GLib.Variant('a{sd}', { pi = 3.14, one = 1 })
local v9 = GLib.Variant('aay', { 'bytetring1', 'bytestring2' })

Data access

LGI implements following special properties for accessing data stored inside variants

Examples of extracting values from variants created above:

assert(v1.type == 's' and v1.value == 'Hello')
assert(v2.value == 3.14)
assert(v3.value == nil and #v3 = 0)
assert(v4.value == nil and #v4 = 1)
assert(v5.value == v5 and #v5 == 2 and v5[2] == 'world')
assert(#v6 == 3 and v6[2] == nil)
assert(v7.value[1] == 100 and v7[1] == 100 and #v7 == 2)
assert(v8.value.pi == 3.14 and v8.value['one'] == 1 and #v8 == 2)
assert(v9[1] == 'bytestring1')
for k, v in v8:pairs() do print(k, v) end

Serialization

To serialize variant into bytestream form, use data property, which return Lua string containing serialized variant. Deserialization is done by Variant.new_from_data constructor, which is similar to g_variant_new_from_data, but it does not accept destroy_notify argument. See following serialization example:

local v = GLib.Variant('s', 'Hello')
local serialized = v.data
assert(type(data) == 'string')

local newv = GLib.Variant.new_from_data(serialized, true)
assert(newv.type == 's' and newv.value == 'Hello')

Other operations

LGI also contains many of the original g_variant_ APIs, but many of them are not useful because their functionality is covered in more Lua-native way by operations described above. However, there there are still some useful calls, which are enumerated here. All of them can be called using object notation on variant instances, e.g. `local vt = variant:get_type()` See GLib documentation for their closer description.