The power of Lua's tables and metatables

wrldwzrd89 profile image Eric Ahnell ・1 min read

Lua is a very interesting language, at least to me, since it has only one structured data type - the table - but that one type can do a LOT more than just tabular data storage. It can function like an indexed array, like a dictionary (key + value storage), a function lookup (since values can be functions), a means of defining class-like entities, and even modifying the meaning of table operations by changing the metatable associated with the table. It can even do all of the above at once!

Another nice feature of tables is that they're a wonderful fit for "data as code" - the default high scores for a game, a collection of translated strings, or the cached values from the last time data was fetched are all great fits for storage in a Lua table. Furthermore, loading these is easy - it's sufficient to load them like you would any other Lua file, then execute the loaded data and store the result to a variable. Finally, if you combine data as code with serialization, then you have the recipe for a self-modifying script. Careful with that...

Posted on by:

wrldwzrd89 profile

Eric Ahnell


Indie game maker, professional user of Python and C#; programming addict in general.


markdown guide