Build a compact BitArray custom type with the Lua C API, including userdata storage, bit operations, index validation, metatables, and Lua-style access.
A Lua table can represent a Boolean array, but a native bit array can store each value in one bit. This example focuses on the API design needed to expose a custom C type safely.
A flexible array member is available in C99. Allocate enough words for the requested number of bits and check for overflow before calculating the byte count.
local bitarray = require("bitarray") local values = bitarray.new(1000) values[10] = true print(values[10]) -- true print(#values) -- 1000 print(values) -- BitArray(1000)
Full userdata owns its storage and supports metatables. Light userdata is only a raw pointer value: it has no per-value metatable and is not managed as an owned buffer, so it is better suited to identity keys and non-owning native references than to this array type.