Skip to content
Stjepan Bakrac edited this page May 22, 2020 · 3 revisions

A struct object as created by struct.new or struct.from_ptr is a cdata object. While it can be any type of cdata only structs worth examining, as other types are converted to Lua types in creation.

A struct is a native version of a Lua table. It is essentially a key-value-mapping, but it is much more restricted than a Lua table. For a proper description see the struct definition page.

Here we will describe how it differs from a regular LuaJIT cdata object. For this page we will use this example:

localobject=struct.new(struct.struct({
int_field= {struct.int32},
string_field= {struct.string(20)},
inner= {struct.struct({
bool_field= {struct.bool},
array_field= {struct.int32[10]},
})},
bits_field= {struct.bits(4)},
}))

This would create the following C struct definition:

struct {
int32_tint_field;
charstring_field[20];
struct {
boolbool_field;
int32_tarray_field[10];
} inner;
charbits_field[4];
};

If we just defined that struct directly without struct.struct we would get the exact same C definition, but we would not have the metatable. The struct library applies a metatable to every struct - and wraps arrays in structs as well to be able to assign them a metatable, too. That means we get to do the following things, all of which would error with regular C structs:

print(object.string_field) -- This automatically converts to a Lua stringprint(#object.inner.array_field) -- # does not normally work on arraysprint(object.inner.array_field[13]) -- Would throw a Lua error instead of potentially segfaultingobject.inner.array_field= {1, 2, 3} -- Normally arrays cannot be assigned to like thatforkey, valueinpairs(object.inner) do-- Structs cannot normally be iteratedprint(key, value) -- Would print the struct key and corresponding valueendforindex, valueinipairs(object.inner.array_field) do-- Arrays cannot normally be iteratedprint(index, value)
endobject.bits_field[22] =true-- Single bits cannot normally be assigned to like this

These are the most commonly used features. There are other converters which also provide some additional behavior not normally found in LuaJIT structs.

These changes were made to offer some convenience over regular cdata. These features try to not impair native struct performance, although it is not possible to avoid it in some cases (like string conversions).

Clone this wiki locally