July 2018
Beginner
202 pages
5h 42m
English
When you try to access a nonexistent field in a table, the result is nil. However, if the table being accessed has a meta table and that meta table has an __index meta method, the meta method will be called.
There are two tables, x and y. Neither table has a hello key, but both tables try to print this key. In both instances, the print statement will result in nil:
x = { foo = "bar"}y = { }print (x.foo) -- barprint (x.hello) -- nilprint (y.foo) -- nilprint (y.hello) -- nil
To fix this, create a meta table with an __index meta method. _index takes two arguments. The first argument is the table that is being indexed, the second argument is the key.
The following code creates two meta tables, z and w; both have an __index meta method. ...