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:
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?
- Yes
- No
0 voters