Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 7 years ago

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

Log in to vote
1
Answered by 7 years ago

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
Would using Object.new be more idiomatic than Object:new since Object.new is not really a "method"? BlueTaslem 18071 — 7y
Ad

Answer this question