Why use setmetatable instead of just creating a basic class?

i’m looking into setmetatable… and seeing a lot of utils using it but not actually using any metamethods… what’s the benefit of using setmetatable if you’re not going to use any of the metamethods? you could just create a basic class without setmetatable.

1 Like

if you are referring to this way of implementing an OOP class

local class = {}
class.__index = class

function class.new()
    local self = setmetatable({}, class)
...

then you are using the default .__index metamethod, which, when fired, looks up the index in the provided table.

1 Like

okay right. am just not seeing a need for that when creating a simple utility. say a countdown util. where you may just want to start a countdown and have events on countdown finish or per tick. wouldn’t it be fine to not use setmetatable. or what would the benefits be of using setmetatable in that situation?

That is purely your decision and depends on your knowledge and personal development style.
Many people choose to use an OOP (implemented with metatables) approach for everything, just for the sake of being consistent with their code in general or for some other reason. Not necessarily because it is the best.

1 Like