lua notes
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 ---@class annotations 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 const on fields, <const> only works on locals, any field can be reassigned
  • a misspelled field isnt an error, reading d.nmae just gives you nil, if you want it to fail loudly set a metatable with an __index that errors on unknown keys

for methods like a c++ class, set a metatable with __index pointing at a methods table

On this page