Search code examples
luametatable

Why in lua, whith metavalue __index, t = {_index} is nil?


When, in lua, I run this code, the metavalue __index is nil

t = {__index = t}
print(t.__index)
--prints nil

but if I write it like this...

t = {}
t.__index = t
print(t.__index)
--prints table ****

... it works My question is why.


Solution

  • In t = {__index = t} t is whatever you assigned to t befor that line. In your case you never assigend a value to t so t is a nil value.

    This is basically equivalent to

    do
       local x = t
       t = {__index = x}
    end
    

    As t is nil this is equivalent to

    do
       local x = nil
       t = {__index = x}
    end
    

    or

    do
       t = {__index = nil}
    end
    

    or

    t = {}
    

    In the second snippet

    t = {}
    t.__index = t
    

    you assign an empty table to t. So t.__index = t assigns that empty table to t.__index

    See Visibility Rules

    Notice that, in a declaration like local x = x, the new x being declared is not in scope yet, and so the second x refers to the outside variable.

    Edit

    sorry but I didn't understand : with t= {text = "hello"} t.text is not nil

    t = {text = "hello"} is equivalent to

    do
       local x = {}
       x.text = "hello"
       t = x
    end
    

    here you assign a string value. Not a nil value as in your first example.