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

What is a metatable and how can you use it to make a userdefined class?

Hello, I am trying to find a way to make a userdefined class in Lua, and somebody told me that I need to use a metatable for that. I looked up "metatable" on the ROBLOX Wiki, and the Wiki gave a vague article. Can you thoroughly explain what a metatable and how do you use it to make a userdefined class?

1 answer

✓ Accepted answer

Metatables

Metatables are extra tables attached to data types such as tables, userdata, and even strings (Although you can't change the string metatable in Roblox) which describe how they behave in certain situations when a script tries to manipulate them.

To create a pseudoclass with Lua, you simply want to make a constructor which makes a new table and forces it to inherit from a class table.

local Object = {};
function Object:new(...) -- Sugar for Object.new = function(self, ...)
	return setmetatable({...}, self)
end
Object.__index = Object
function Object:Print()
	for k,v in next, self do
		print(k,v)
	end
end

local List = Object:new("This", "Is", "Basic")
Object:Print()
--> 1 This
--> 2 Is
--> 3 Basic

1 comment

1

Would using Object.new be more idiomatic than Object:new since Object.new is not really a "method"?

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