struct_object - Windower/packages GitHub Wiki

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:

local object = 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_t int_field;
    char string_field[20];
    struct {
        bool bool_field;
        int32_t array_field[10];
    } inner;
    char bits_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 string
print(#object.inner.array_field) -- # does not normally work on arrays
print(object.inner.array_field[13]) -- Would throw a Lua error instead of potentially segfaulting
object.inner.array_field = {1, 2, 3} -- Normally arrays cannot be assigned to like that
for key, value in pairs(object.inner) do -- Structs cannot normally be iterated
    print(key, value) -- Would print the struct key and corresponding value
end
for index, value in ipairs(object.inner.array_field) do -- Arrays cannot normally be iterated
    print(index, value)
end
object.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).

⚠️ **GitHub.com Fallback** ⚠️