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.
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.
t = {__index = t}
t
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
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
t.__index = t
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.
sorry but I didn't understand : with t= {text = "hello"} t.text is not nil
t = {text = "hello"} is equivalent to
t = {text = "hello"}
do local x = {} x.text = "hello" t = x end
here you assign a string value. Not a nil value as in your first example.
In
t = {__index = t}tis whatever you assigned totbefor that line. In your case you never assigend a value totsotis a nil value.This is basically equivalent to
As t is nil this is equivalent to
or
or
In the second snippet
you assign an empty table to
t. Sot.__index = tassigns that empty table tot.__indexSee Visibility Rules
Edit
t = {text = "hello"}is equivalent tohere you assign a string value. Not a nil value as in your first example.