Inheritance in metatables; easy guide

Hello! Today I will teach you about inheritance and how to use it.

Quick summary: inheritance is when one table can use the functions or in other words, the “basis” of the parent table. Basically, it’s like having a parent class called “Food”, and having children of it such as a burger and soup. Here’s a quick diagram:


For this, you’ll need some table usage background.

Usage:

Let’s say you are making a… cooking system! You might not want to copy and paste every function as it’s very inefficient. This way, you can save yourself that time and many, many, MANY lines of code.
So, let’s get started!

Step 1: create your parent table

--step 1: parent table
local Food = {}
Food.__index = Food-- this line is very important, 
--when we set the metatable it will actually inherit it
--it using this line, as the.__index function in metatables
--makes it so if the table that the metatable has been set to, in our case
-- burger or soup. So essentially what will happen is if there's no such 
--function in the burger or soup table
--these tables will just "copy" the function from the parent food table
--and use it as their own. Useful, huh?
--it will search through the food table for that function or variable
Food.Price = 0
Food.CookLevel = 0
function Food:Cook()
    self.CookLevel = 1
    return "Cooked"
end

Step 2: Make the child table

local Soup = {}
local Burger = {}

Step 3: most important, parent the tables!

setmetatable(Soup, Food)
setmetatable(Burger, Food)

Step 4: Cook the food!

Soup:Cook()
Burger:Cook()

print(Soup.CookLevel)
print(Burger.CookLevel)

Output:
image

End code:

local Food = {}
Food.__index = Food
Food.Price = 0
Food.CookLevel = 0
function Food:Cook()
	self.CookLevel = 1
	return "Cooking"
end

local Soup = {}
local Burger = {}

setmetatable(Soup, Food)
setmetatable(Burger, Food)

print(Soup:Cook())
print(Burger:Cook())

print(Soup.CookLevel)
print(Burger.CookLevel)

Thanks for reading! Was it helpful?

Did you find this useful?
  • Yes
  • No

0 voters

14 Likes

If you didn’t find it useful and you don’t know programming/have complaints, tell me why here!

1 Like

Reason why I personally didn’t find this useful, is due to the fact that there are already a load of topics that discuss metatables. That also includes pretty much everything in this tutorial.

Tons of Posts

All you need to know about Metatables and Metamethods

Metatables, Metamethods, ModuleScripts and OOP

Metatables, told by a guy obsessed with Lua

Metatables, metamethods for dummies

Object Oriented Programming in Roblox

Additionally this is discussed in the programming in Lua ebook
https://www.lua.org/pil/13.html

2 Likes

Yeah I know. I am just making a summary so it’s easier for people :slight_smile:

10 Likes

I watched so much tutorials and i am not someone who is good at learning from reading, but your tutorial was ligit the best i now understand the inheritance and __index use thanks so much!

2 Likes