From 1f61d7346b757b566f73ba91770d175f571073f2 Mon Sep 17 00:00:00 2001 From: Junseo Yoo Date: Wed, 5 Jun 2024 14:40:21 -0700 Subject: [PATCH] Added more clarifications on interactions of index and classes --- docs/index-type-operator.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/index-type-operator.md b/docs/index-type-operator.md index dc774a5..0091e9f 100644 --- a/docs/index-type-operator.md +++ b/docs/index-type-operator.md @@ -76,7 +76,15 @@ type idxType3 = index -- idxType3 = number | string type idxType4 = index -- Error message: Property '"age" | "alive"' does not exist on type 'Person | Person2' ``` -In the circumstance that the indexee is a type class or table with an `__index` metamethod, `index` will *only* invoke `__index` if indexer is not found within the current scope. +In the circumstance that the indexee is a type class or table with an `__index` metamethod, the `__index` metamethod will *only* be invoked if the indexer is not found within the current scope: +```lua +local exampleClass = { Foo = "eight" } +local exampleClass2 = setmetatable({ Foo = 8 }, { __index = exampleClass }) +local exampleClass3 = setmetatable({ Bar = "nine" }, { __index = exampleClass }) + +type exampleTy2 = index -- exampleTy2 = number +type exampleTy3 = index -- exampleTy3 = string +``` Implementation is straight forward: the type of the indexee will be determined (table, class, etc) -> search through the properties of the indexee and reduce to the corresponding type of the indexer if it exists; otherwise, reduce to an error.