![]() |
Programming in Lua | ![]() |
Part II. Tables and Objects Chapter 13. Metatables and Metamethods |
__newindex
MetamethodThe __newindex
metamethod does for table updates what
__index
does for table accesses.
When you assign a value to an absent index in a table,
the interpreter looks for a __newindex
metamethod:
If there is one, the interpreter calls it
instead of making the assignment.
Like __index
, if the metamethod is a table,
the interpreter does the assignment in that table,
instead of in the original one.
Moreover, there is a raw function that
allows you to bypass the metamethod:
The call rawset(t, k, v)
sets the value v
in key k
of table t
without invoking any metamethod.
The combined use of __index
and __newindex
metamethods
allows several powerful constructs in Lua,
from read-only tables to tables with default values to
inheritance for object-oriented programming.
In the rest of this chapter we see some of these uses.
Object-oriented programming has its own chapter.
Copyright © 2003-2004 Roberto Ierusalimschy. All rights reserved. |
![]() |
![]() |