Metatables help

I learned metatables rcenetly and I’m trying to implement it in my recent game, I’m making a fighting game with different fighting stances/styles.

I made a module that returns a table with all the styles and all of their animation, but I want to set default animations so if the style doesnt have a unique block animation it uses the default one but since I’m using a dictionary I’m not sure how I can do such thing with metatables.

local module = {}


local default_animations = {
	["Block"] = "123123213",
}

module.Styles = {
	["Street Fighting"] = {
		["1"] = "1231232",
		["2"] = "123123",
		["Skills"] = {}
	}
}

for i,v in pairs(module.Styles) do
	print(v)
	if typeof(v) == "table" then
		setmetatable(v, default_animations)
		v.__index = default_animations
	end
end





return module

Server Script Test:

local module = require(game.ReplicatedStorage.Styles)


print(module.Styles["Street Fighting"].Block)
2 Likes

__index passes a table and an index, so you can go through the default animations like this:

local metamethods = {}
metamethods.__index = function(table, index)
	return default_animations[index]
end

for i,v in pairs(module.Styles) do
	print(v)
	if typeof(v) == "table" then
		setmetatable(v, metamethods)
	end
end
1 Like

Why did you make a new table to do this? (It works thanks)

Since all the animation styles are being directed to the same table (default_animations) you can use the same exact metamethod for all of them.

1 Like

But how is it any different if I set their metatable to the default_animations table?

Never mind, the problem is that I was using index inside of the loop itself the table doesnt matter.

1 Like