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
This is my understanding so far, first when you call Car.New it runs the function thats inside the Car table.
Second it creates a new car table and creates a metatable with the __index metamethod
third it creates new properties for newcar which triggers the metamethod
Lastly the metamethod runs the function Car ? This part is confusing
So, .__index is used to redirect the script to the metatable if the table has a nil value that you’re trying to index.
First, let’s take a look at the code, and form some pseudocode to understand it better. The Car.new() function returns a table called newcar. But all of the functions/constructors we are creating, such as Car.new() are for the metatableCar.
Say you add a function:
function Car:Brakes(speed) --slow down the car
self.Speed = speed --self will be the newcar table, a particular object
end
Now if we use the code in another script:
local car = Car.new(pos, dr, model) --returns the newcar table
car:Brakes(15) --we've called :Brakes on newcar, but the function is defined for the metatable Car
So, this is where the index metamethod comes in. It looks if :Brakes exists in newcar, which it doesn’t, meaning the .__index will fire. The metamethod will make Lua look inside of Car, in which the Brakes function does exist.
You can also think about it this way: “Car” is the class, not a particular object. newcar is the particular object, so instead of having to pass newcar as a parameter each time a function is called, you can redirect Lua so that the class functions are applied to the object. Essentially it’d be like:
function newcar:Brakes()
end
If you want to learn more, check out these awesome resources:
No it doesn’t this is how it works. When you index an table in lua and the value of the index is nil lua checks if that table has an metatable, if it does have a metatable it checks if the metatable has the .__index metamethod, if it does it tries to find the index in the table attached to this metamethod in the case you showed it is attached to the metatable itself. , if it finds the index is the table then it returns that value aissgned to the key. This is if you set the .__index of a metamethod as a table, you can also set it as a function, but I won’t be telling it here.