Help with meta tables

I am messing around with metatables as I’m new to this but how would I return the string if the user does not exist in the following code:

local PlayerData = {
	Ie_fishe = {
		Inventory = {
			Primary = "M4A1";
			Secondary = "Glock-19"
		};
	};
	bob= {
		Inventory = {
			Primary = "Vulcan";
			Secondary = "Glock-18"
		};
	};
}

setmetatable(PlayerData, {
	__Index = function()
		return {
			"No data!"
		}
	end;
	
})

print(PlayerData["Ie_fishe"].Inventory.Primary)
print(PlayerData["bob"].Inventory.Primary)
print(PlayerData["danny"].Inventory.Primary)

I wanna have it check the first table aka the user table first before proceeding into the inventory

First of all, it’s __index, not __Index. If I got it right, you wanna receive “No data!” if player doesn’t exist. The simple solution would be returning an empty inventory table where all slots are set to No Data, like this:

setmetatable(PlayerData, {
	__index = function()
	    return {
        	Inventory = {
                Primary = "No data!";
                Secondary = "No data!"
            }
        }
	end
})

However, if you’re planning on adding even more slots, you can set another metatable.

setmetatable(PlayerData, {
	__index = function()
	    return {
        	Inventory = setmetatable({}, {__index = function()
                return "No Data!"
            end})
        }
	end
})

Though, if I were you, I wouldn’t overuse metatables for such purposes. They tend to be confusing at times and might even hurt performance.

1 Like