Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

What are metatables, and how to use them?

Hello everyone. I saw something that involves metatables recently, and from what I see, they are really useful. Just, I don't understand them. I've read the Wiki, but for the first time in ever, I actually don't understand it. They seem so useful but so hard to learn.

I would be happy if someone could dumb down what metatables are, how to use them, what _index and all those other things are, basically everything you know about metatables simplified. Thanks so much, I would love to unlock the creative power of metatables!!

(sorry is this seems like a broad question)

1 comment

0

Metatables are used when math is performed on a table.

1 answer

✓ Accepted answer

The analogy that I'd heard once before and tend to think of as a good starting point is that they're like events, but for tables.

Each metamethod is unique, but once you get the idea for one of them the rest should come pretty easily.

Here's an example of using the __index and __newindex metamethod which only fire when indexing a position thats value is currently nil.

local someTable = {"cat", 7, "apple"};
local someTable2 = setmetatable({}, {
	__index = function(t, k)
		-- someTable2 is always empty so this metamethod should always fire
		if (type(k) == "number") then
			k = k + 1; -- now the table is zero-indexed b/c 0 becomes 1 and so forth
		end;
		return someTable[k];
	end;
	__newindex = function(t, k, v)
		-- add new indexes to someTable with adjsuted index
		if (type(k) == "number") then
			k = k + 1;
		end;
		someTable[k] = v;
	end;
});

print(someTable2[0]) -- cat
print(someTable2[1]) -- 7
print(someTable2[2]) -- apple

someTable2[1] = false;

print(someTable2[0]) -- cat
print(someTable2[1]) -- false
print(someTable2[2]) -- apple

This page gives an example of all the metamethods in use, hopefully that's enough to get you started.

This discussion is preserved as it was. New answers, comments, and votes are closed.