Lesson 13 of 15

Metatables

Metatables

Metatables let you customize how tables behave. The most common use is the __index metamethod, which provides default values or inheritance.

local defaults = {color = "red", size = 10}
local obj = {size = 25}
setmetatable(obj, {__index = defaults})

print(obj.size)   -- 25  (own field)
print(obj.color)  -- red (from defaults)

Object-Oriented Pattern

Metatables enable OOP in Lua:

local Animal = {}
Animal.__index = Animal

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

function Animal.speak(self)
  print(self.name .. " says " .. self.sound)
end

Your Task

Create a simple "class" using metatables. Create a Dog table with a new constructor and a bark method.

JS Transpiler loading...
Loading...
Click "Run" to execute your code.