Skip to content

Commit c936d4c

Browse files
committed
section about __index and __newindex with tables added
1 parent d58692a commit c936d4c

1 file changed

Lines changed: 32 additions & 1 deletion

File tree

tutorials/metatables/metatables.md

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,37 @@ and this prints ...
238238
67
239239
134
240240

241-
The take away of this chapter is simply that we have to take care of the things we expect from these functions, and that
241+
The take away of this section is simply that we have to take care of the things we expect from these functions, and that
242242
for `__newindex` we have to use `rawset()` if we want to set the value in the table, otherwise we get recursive calls.
243243

244+
## Tables for `__index` and `__newindex`
245+
246+
I mentioned in the beginning that instead of functions, `__index` and `__newindex` can also be used with tables. Means
247+
instead of providing a function, we provide a table. So then, let's create 2 more tables. So as we know the `__index`
248+
(reading) and `__newindex` (writing) events are only triggered if they keys dont't exist in the table `T`. But `__index`
249+
will read the value from the `LookItUpHereTable` table, and `__newindex` will set the value in the `WriteItBackHereTable` table.
250+
251+
T = { }
252+
253+
LookItUpHereTable =
254+
{
255+
IDontExistInT = "I don't exist in T, but I exist in the look up table"
256+
}
257+
258+
WriteItBackHereTable = { }
259+
260+
M =
261+
{
262+
__index = LookItUpHereTable,
263+
__newindex = WriteItBackHereTable,
264+
}
265+
266+
setmetatable(T, M)
267+
268+
-- trigger the __index event and get value from the LookItUpHereTable table
269+
print(T.IDontExistInT)
270+
271+
-- trigger the __newindex event and set the value in the WriteItBackHereTable table
272+
T.NewIndex = "I am new"
273+
print(WriteItBackHereTable.NewIndex)
274+

0 commit comments

Comments
 (0)