#_index

1 messages · Page 1 of 1 (latest)

undone sable
#

How to use _index

sinful tiger
#
-- Create a base class
local Animal = {}
Animal.__index = Animal

function Animal.new(name)
    local self = setmetatable({}, Animal)
    self.name = name
    return self
end

function Animal:speak()
    print(self.name .. " makes a noise!")
end

-- Create a derived class
local Dog = setmetatable({}, Animal) -- Dog inherits from Animal

function Dog.new(name)
    local self = Animal.new(name) -- call the base class constructor
    setmetatable(self, Dog)
    return self
end

function Dog:speak()
    print(self.name .. " barks!")
end

-- Create instances
local aDog = Dog.new("Rex")
aDog:speak()  -- Outputs: Rex barks!

local anAnimal = Animal.new("Generic Animal")
anAnimal:speak()  -- Outputs: Generic Animal makes a noise!
#

Generic example

#

It's used in object oriented programming

#

Think of the Animal table as a book of instructions (methods).

The __index setting says: "If I don’t find something in my own instance, check this book for more instructions."