Jump to content




__index trouble


  • You cannot reply to this topic
2 replies to this topic

#1 Thegameboy

  • Members
  • 21 posts

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 by Thegameboy, 28 December 2015 - 12:55 AM.


#2 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

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.

#3 KingofGamesYami

  • Members
  • 3,002 posts
  • LocationUnited States of America

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 by KingofGamesYami, 28 December 2015 - 04:17 AM.






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users