#setmetatable issue

1 messages · Page 1 of 1 (latest)

stuck perch
#

does setmetatable() work in local scripts? i cant understand, why this doesnt work

local a = setmetatable({}, {val=5})
print(a.val)```

(gives nil when i expect 5)

i also tried using module script, but that also doesnt help
```lua
local test2 = {}
test2.__index = test2

function test2.new()
    return setmetatable({}, {val=5})
end

return test2



local t2 = require(script.Parent.test2)

local obj = t2.new()
print(obj.val)

how to fix it?

dusk zephyr
#

you just got really confused

#

even me got a little confused reading that

#

an easy example would be:

stuck perch
#

maybe im wrong...

dusk zephyr
#
local t = {};
local mt = {};
mt.__index = {val = 5;};

setmetatable(t, mt);

print(t.val);
#

this would print 5

#

tell me if any doubts

stuck perch
dusk zephyr
#

because the metatable is what contains the metamethods

#

and the __index metamethod is one of them

#

you can read this tho

#

specifically this

stuck perch
#

so its smth like operator overriding for table mt
and then u pass methods from mt to t with setmetatable()?

dusk zephyr
#

basically yep

stuck perch
#

alr, how linking in lua works? like setmetatable() copies everything from mt or basically links t to mt? taking into account that u type __index before setmetatable() the 1st variant should be correct

frigid coyoteBOT
#

studio** You are now Level 3! **studio

dusk zephyr
#

basically take the steps of indexing like this:

1 - it will look up for key first in t
2? - if it does not exist in t it will look if the table owns a metatable
3 - if it does, it will check up if __index metamethod is there
4 - (in this case, we'll think out of __index being a table) if the metamethod is there, it will try to look up for key in the metatable, so no, it does not copy and it is good to imitate OOP

edgy cloud
#

That's all

stuck perch
dusk zephyr
stuck perch
dusk zephyr