Library and Table Access Metamethods

The metatable __toString method

  • It is common for libraries to define metatable and metamethods

    • The print command looks for the __tostring metamethod
      • The effect of putting the tostring method in the metatable can be seen:
        • uncomment the mt.__tostring = Set.tostring line in the example for sets

The index and newindex metamethods

  • When an access to an index in a table returns a nil
  • The interpreter looks for an __index metamethod

    • If found the metamethod returns the result rather than nil
    • __index can be set to a function, or a table
    • If set to a table a lookup is done in the table for the key passed in
    • If a function the function is called with the table and key as parameters
    • To access a table without invoking __index Use rawget(t,i)
  • __newindex is used for table updates

    • if the index absent then the __newindex function is called if it exists
    • rawset(t,i) is used to bypass the check
    • If a table is assigned to __newindex then the assignment is made in this table