AustnBlox
(Austin)
August 23, 2023, 8:35am
#1
How does the .__index metamethod work in this situation?
local Car = {}
Car.__index = Car
function Car.new(position, driver, model)
local newcar = {}
setmetatable(newcar, Car)
newcar.Position = position
newcar.Driver = driver
newcar.Model = model
return newcar
end
return Car
2 Likes
Remingling
(Remingling)
August 23, 2023, 8:51am
#2
Here’s a good explanation on metatables
__index is a metamethod, which metamethods are used with metatables. If you’ve ever learned about operator overloading which is a concept in some other languages (like C#, for example) it’s pretty similar to that idea.
There’s actually quite a few threads that were already made that are pretty intuitive tutorials as to how metatables/metamethods function.
A technical definition though:
The __index metamethod will fire when you index something in a table that does not exist. You can assign an __index key to either some value, or a function as a handler. The table, along with the index, will be passed as arguments to the function if you assign it to a function rather than a value.
It’s actually pretty cool. Here’s another example using code:
local myMetamethods = {}
--//Assign metamethod
myMetatable.__index = function(table, index)
print("Index of: "..index.." was not found in "..table)
end
--//Create the metatable
local myMetatable = setmetatable({}, myMetamethods)
myMetatable.apples = 2 --//The __index metamethod will not be invoked, as a new index was created in our table.
print(myMetatables.oranges) --//This index does NOT exist in our table, so our metamethod which is attached to this metatable will invoke, causing the function to execute.
Hope this helps a bit. I can clarify anything that seems confusing. The concept of metatables and metamethods is definitely more complex if you don’t have a strong understanding of tables and table manipulation already.
1 Like
When you create a car instance, your new car instance has access to Car.new
, without creating duplicate functions.
1 Like
Anytime you try to index something within newcar
that doesn’t exist within it, instead of returning nil
right away it will search within the Car
table to see if what you index exists within Car
instead, and returning whatever that value is (or nil
if it also doesn’t exist in there)
1 Like
system
(system)
Closed
September 6, 2023, 9:30am
#5
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.