DEV Community

Eric Ahnell
Eric Ahnell

Posted on

The power of Lua's tables and metatables

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...

Top comments (1)

Collapse
 
tilkinsc profile image
Cody Tilkins • Edited

I once created a fun little demon. Which took advantage of certain features of lua and most importantly - metatables and setfenv.
You can remove the ()'s to a function call when supplying a string or a table.
func({param = value}) -> func{param = value}
func("param") -> func "param"

class "some_class" {
  public = {
    some_var = 5;
    print_var = function(self)
      print(self.some_var)
    end;
  };
  protected = {
    some_var2 = 10;
  };
  private = {
    some_var3 = 15;
  };
  constructor = function(self)

  end;
  destructor = function(self)

  end;
}
register_class("some_class")

local abc = class_some_class.new()
abc.print_var()
Enter fullscreen mode Exit fullscreen mode

It even had full polymorphism.