Hello, can someone answer on this short question: what’s diffirence between __index and __newindex in metatables?
2 Likes
x[y]
(OP_GETTABLE) fires __index
as a fallback when there’s no primitive get for the type or the primitive get of the table is nil
.
x[y] = z
(OP_SETTABLE) fires __newindex
as a fallback when there’s no primitive set for the type or the primitive get of the table is nil
.
So basically, __index
is get when the table is nil
and __newindex
is new set when the key
of the table doesn’t exist (is nil
).
1 Like
That explanation is pure madness! Anyway, in Roblox metatables there’s a much simpler explanation:
In other words
__index(table, index)
is a function that you manually write in a metatable. For example:
myMetaTable = {
__index = function(table, index)
print("Sorry, but the element ".. tostring(index).. " does not exist.")
-- runs when you try to index a nil element of the table this metatable is connected to, table[index]
end,
__newindex = function(table, index, value)
print("Sorry, but the element ".. tostring(index).. " can't be set to ".. tostring(value).. " because this element does not exist.")
-- runs when you try to index and set a nil element of the table this metatable is connected to, table[index] = value
end
}
3 Likes