Help with Metatables!

Hey developers.

I’m currently working on one of my games and I would like to use metatables in a scenario where I have a module script which returns all the stats of a monster and I want to implement a metamethod so that if the stats table is missing a value, it will reach to another module which contains the “template” of the stats table. Problem is, I have no idea in how I could find the specific asset considering I have a good sized table.

I do have the basics of how metatables should be approached and I looked up some workarounds and tried some methods but I can’t find a working and efficient approach, any help is needed!

Thanks in advance,

1 Like
local Monster = { --Base class for all 'monsters'.
	Health = 1, --Default stats.
	Speed = 1,
	Damage = 1,
	Climb = 1
}

local Zombie = {} --Class for 'zombies'.
setmetatable(Zombie, {
	__index = Monster --'Zombie' class inherits from the 'Monster' class.
})

function Zombie.new() --Class constructor for 'zombies'.
	local NewZombie = {} --New 'zombie' object.
	setmetatable(NewZombie, {
		__index = Zombie --'Zombie' object inherits from the 'Zombie' class.
	})
	
	NewZombie.Health = 5
	NewZombie.Speed = 2
	NewZombie.Damage = 10
	--Notice we haven't defined its 'Climb' stat.
	return NewZombie
end

function Zombie:GetClimb() --Function that gets a 'zombie' object's climb stat.
	return self.Climb
end

local Zombie1 = Zombie.new() --Construct a 'zombie' object.
local Climb = Zombie1:GetClimb() --Call the 'GetClimb' method on the object.
print(Climb) --'1', the 'zombie' object has inherited the 'climb' stat's default value from the 'Monster' base class.

Here’s a relatively easy to follow script I just wrote.

1 Like

Awesome, thanks for the help! I’ll check the script later on and give a response if I weren’t able to reach my goal but this should suffice.