How does the .__index metamethod work in this situation?

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

Here’s a good explanation on metatables

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

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