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?
✓ ANSWER ACCEPTED
What is a metatable and how can 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
This discussion is preserved as it was. New answers, comments, and votes are closed.

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