## Lua calling a metatable's metatable function

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Drakkahn
Prole
Posts: 24
Joined: Sat Jan 17, 2015 11:09 pm

### Lua calling a metatable's metatable function

First off, this does not involve the love library in anyway, this is about lua.

Okay, so I have custom index for my metatable, which works fine and dandy. However, I'm trying to call the metatable's metatable and I can't seem to get it to work. I keep getting the error "stack overflow"

EXAMPLE CODE:

Code: Select all

variables={}
test={}
test_mt={}
test_mt.__index=function(tbl,key)

if variables[key]~=nil then return variables[key]
else

local mt=getmetatable(tbl)
mt.__index(tbl,key)

end

end

test_mt2={}
test_mt2.__index=function(tbl,key)

print(tostring(tbl) .. "." .. key .. " has not been set in variables!")
return nil

end

setmetatable(test_mt,test_mt2)
setmetatable(test,test_mt)

print(test.stuff)

s-ol
Party member
Posts: 1077
Joined: Mon Sep 15, 2014 7:41 pm
Location: Cologne, Germany
Contact:

### Re: Lua calling a metatable's metatable function

Drakkahn wrote:First off, this does not involve the love library in anyway, this is about lua.

Okay, so I have custom index for my metatable, which works fine and dandy. However, I'm trying to call the metatable's metatable and I can't seem to get it to work. I keep getting the error "stack overflow"

EXAMPLE CODE:

Code: Select all

variables={}
test={}
test_mt={}
test_mt.__index=function(tbl,key)

if variables[key]~=nil then return variables[key]
else

local mt=getmetatable(tbl)
mt.__index(tbl,key)

end

end

test_mt2={}
test_mt2.__index=function(tbl,key)

print(tostring(tbl) .. "." .. key .. " has not been set in variables!")
return nil

end
setmetatable(test_mt,test_mt2)
setmetatable(test,test_mt)

print(test.stuff)
getmetatable(tbl) is test_mt, so your __index calls itself infinetely, causing a stack overflow.

s-ol.nu /blog  -  p.s-ol.be /st8.lua  -  g.s-ol.be /gtglg /curcur

Code: Select all

print( type(love) )
if false then
baby:hurt(me)
end

Drakkahn
Prole
Posts: 24
Joined: Sat Jan 17, 2015 11:09 pm

### Re: Lua calling a metatable's metatable function

Ya it just hit me, thanks alot.

For anyone who was wondering how I fixed it I changed:

Code: Select all

mt.__index(tbl,key)
To:

Code: Select all

mt.__index(mt,key)

### Who is online

Users browsing this forum: Bing [Bot] and 57 guests