What is the use of setmetatable in scripts? How does it help keep my code organized?

I’m no good scripter by any chance and I personally find it difficult to grasp some things in scripting. However I’ve read the wiki and outside material in regards to metatables from which I only gather are just tables with additional functions. One thing I fail to understand is what use for me is a piece of code like this;

local ModuleName = {}
ModuleName.__index = ModuleName

ModuleName.Name = 'Name'

function ModuleName.new()
local self = setmetatable({},ModuleName)
-- some stuff here
return self
end

function ModuleName:SelfStuff()
self.Name = 'ObjectName'
end

return ModuleName

What can I achieve with this? Does it make modularity of my code better? Roblox uses this in their core scripts, which makes it difficult for me to see what actually goes on in there and I would like to understand this alot better.

1 Like

Setmetatable is used to convert Lua to the object oriented paradigm. This is something that you shouldn’t worry about if you’re just starting to learn to script; it will just confuse you further. You shouldn’t worry about it right now and you should focus on learning more essential things first. If you’re interested in oop, there are a lot of YouTube videos that can show you how it works. https://www.youtube.com/results?search_query=oop+in+lua

Let’s say that with this method I want to create a class BasicTool that allows me to create a new object, with equip, unequip and so it loads animations. From that I want to create BasicWeapon that will be a class for all weapons since they behave similar to each other, but aren’t simple enough to use BasicTool as a class. In addition to BasicWeapon I will be adding BasicConsumable, similar behavior to a BasicTool however it now has additional behaviors that again make it much more complex than a BasicTool, but it also is simple enough to be used in majority of consumable objects.

Would this be a correct way of using OOP in Lua? Or is this considered bad practice for using things for what may seem slightly trivial things?

Yes, you would be inheriting the Tool class and creating the consumable and weapon class from it. Here’s a video on inheritance https://www.youtube.com/watch?v=ajOYOxCanhE

Thank you for the explanation!

1 Like

For the sake of clarification: metatables can be used for OOP-in-Lua, but metatables (more specifically metamethods, a metatable is just an attached table) are just used to overload certain behaviours for tables and userdata. It is possible to use metatables outside of an OOP-like environment.

1 Like