Why does this give me "C stack overflow"?

For some reason this just gives the error message “C stack overflow”

local foo = {
    __call = function(_, bar) 
        print(bar) 
    end,

    __index = function(t, baz)
       t:__call(baz)
    end
}

local qux = setmetatable({}, foo)

qux["foobar"](1, 2, 3)

Am I doing something wrong?

This is super advanced stuff… Problem stems from the __index metamethod recursively calling the __call method via t:__call(baz), which triggers the __index again, creating an infinite loop.

Directly call the function without accessing it through t.

local foo = {
    __call = function(_, bar) 
        print(bar) 
    end,

    __index = function(_, baz)
       foo.__call(_, baz)
    end
}

local qux = setmetatable({}, foo)

qux["foobar"](1, 2, 3)
3 Likes

oh I thought stack overflow meant smth else but it meant this now i understand thx

Recursive codes are always a bit to deal with.

1 Like

This doesn’t work cuz it is accessing foo while it is still being initialized

Also I found out I can just do getmetatable(t):__call(baz)

But doing that is kind of tedious is there any other way or do I have to do that

EDIT: I will just mark this as the solution I guess

You do understand I’m scripting off the top of my head here without testing, right?
Just seeing the problem is only 1/2 of the work … try this. (refine, refine, refine)

local foo = {
    __call = function(_, bar) 
        print(bar) 
    end,

    __index = function(t, baz)
       t(baz)
    end
}

local qux = setmetatable({}, foo)

qux["foobar"](1, 2, 3)
1 Like

Wow this is way better than the one I made thank you very much

1 Like

:eyes: … t:__call(baz)
One line difference.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.