Maps in Lua
To create an empty table, you can use {}
.
Set key/value pairs using typical table[key] = val
syntax.
Printing a table with print
will not show all of its key/value pairs well. We’ll use a loop for that.
Get a value for a key with table[key]
.
If the key doesn’t exist, nil
is returned, which can be used to check the presence of a key.
The #
operator returns the number of key/value pairs when called on an array (not a generic table). Instead, you can count the pairs manually.
To remove key/value pairs from a table, set its value to nil
.
To clear all key/value pairs from a table, you can iterate over it and set all values to nil
.
You can also declare and initialize a new table with some values in the same line.
If you need to check if two tables are equal, you would typically write a custom function to compare their contents.
Note that tables appear in the form {k = v, k = v}
when printed with print
.