Help understanding custom classes/metamethods

So I’ve been noticing that in a lot of posts on the DevForum and other open-sourced game engines and frameworks, this exists:

local wid = {}
wid.__index = wid

function wid.Create(no)
	local self = {}
	self.no = no
	
	return setmetatable(self, wid)
end

return wid

But I have absolutely no clue what this is supposed to do, or how to understand it. Any help, pls?


To note; I based that code off a post I saw Tiffblocks make (which I don’t understand). The code was as follows:

local RunService = game:GetService("RunService") -- services go first

local Helper = require(script.Parent.Helper) -- then requires

local randomNumberByFairDiceRoll = 4 -- then constants

local Widget = {} -- then the module itself

Widget.__index = Widget

setmetatable(Widget, Superclass) -- optional base class

function Widget.new(foo)
    local self = {}
    self.foo = foo

    return setmetatable(self, Widget)
end

function Widget:Frobnicate(value)
    local res = self.foo
    self.foo = value
    return res
end

return Widget
local wid = {}
wid.__index = wid

function wid.Create(no)
	local self = {}
	self.no = no
	
	setmetatable(self, wid)
end

return wid

In that code, they make it so that whenever you try to index an Instance of the wid class, you instead index the wid table that has all the methods.

1 Like

Metatables are really cool. I won’t be doing them justice trying to explain in a DevForum post. Instead have a wiki page on them:
http://wiki.roblox.com/index.php?title=Metatable

1 Like

Forgot the return statement there, edited in OP, but thanks for the reply.

Also, check out this thread if you want to explore how the code in your initial post may help abstracting code into objects.

2 Likes

Oh yeah I’ve been looking for this, makes it easier to understand for me.

Yah I was wondering why there was no return.