lua
structs
the lua equivalent of a c++ struct, a table n a constructor function
lua has no structs, you use a table, n a constructor function gives it the fixed shape
struct data_t
{
const char* name;
const char* desc;
int flags;
};becomes
---@class data_t
---@field name string
---@field desc string
---@field flags integer
local function data_t(name, desc, flags)
return { name = name, desc = desc, flags = flags or 0 }
end
local d = data_t("sword", "a pointy thing", 3)
print(d.name, d.flags)the bits that trip you up
- the
---@classannotations are optional, theyre comments the lua language server (luals) reads, so you get autocomplete n a warning on a wrong field, the closest you get to a compile time struct - theres no
conston fields,<const>only works on locals, any field can be reassigned - a misspelled field isnt an error, reading
d.nmaejust gives younil, if you want it to fail loudly set a metatable with an__indexthat errors on unknown keys
for methods like a c++ class, set a metatable with __index pointing at a methods table