This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Thegameboy's profile picture

__index trouble

Started by Thegameboy, 27 December 2015 - 11:54 PM
Thegameboy #1
Posted 28 December 2015 - 12:54 AM
Recently this little happy bug popped up out of nowhere. Can anyone tell me why this does not seem to work?


local p = {
  x = 1,
  __index = p
}

local tble = {}
setmetatable(tble,p)
print(tble.x) --> outputs nothing

but then yet this does?


local p = {
  x = 1,
}

local tble = {}
setmetatable(tble,p)
p.__index = p
print(tble.x) --> outputs "1"
Edited on 27 December 2015 - 11:55 PM
Lyqyd #2
Posted 28 December 2015 - 02:46 AM
In the first example, the table p isn't finished being declared when you try to reference it from itself for the __index entry.
KingofGamesYami #3
Posted 28 December 2015 - 04:17 AM
That is to say, you can't reference something that isn't defined yet.

Properly, you would do this:


local tbl = {}
local mt = {
  __index = {
    x = 1,
  },
}
setmetatable( tbl, mt )
print( tbl.x ) -->outputs 1

I'm not sure what crazy things you're trying to do by declaring the metatable the same as the __index key - that might be a little weird if you use other keys, such as __newindex or __call.
Edited on 28 December 2015 - 03:17 AM