New: Nitro Boost our Discord server and receive full donation perks here on the website! Join the Scripting Helpers Discord Server to learn more! You can also Support on Patreon as always.
Still have questions? Join our Discord server and get real time help.
0

# How to properly use metatables as classes?

Edited 4 days ago

So recently I've been using metatables to behave as classes pretty frequently. I read, however, that whenever a table is indexed in lua, it checks to see if the index is nil in the original table first and then references the metatable. Does this mean that it would be more efficient to create a new set of functions for each 'subclass' and abandon metatables since I do not need to update class functions dynamically? Or would that be a waste of memory?

Here's a better demonstration of what I mean to say. Which of these methods is more efficient for making classes which do not need to share data or dynamically change?

Metatable:

local cas = game:GetService("ContextActionService")

local Action = {}
Action.__index = Action

function Action:new(name)   --class constructor

local action = {}
action.name = name

return setmetatable(action, self)   --Each subclass has table Action as a metatable and shares its functions
end

function Action:Bind()  --example function

cas:BindAction(self.name, self.Handler, false, self.binding)

end



Constructor Function:

local cas = game:GetService("ContextActionService")

local function newAction(name)  --class constructor

local action = {}
action.name = name

function action:Bind()  --example function, each class has its own copy of the function

cas:BindAction(name, self.Handler, false, self.binding)

end

return action

end



My guess is that metatables are only useful for class structures when the subclasses have to communicate with each other, and so I should use the second method when possible to maximize read time.

1
Unless this is being used in code which needs to be as performant as possible (like when something is slow), you shouldn't worry about small optimizations like this. hiimgoodpack 1928 — 4d
0
I'm currently working on user input so I want the read time to be as fast possible. I'm also using class structures for most of the functionality in my game so I'd like to know best use cases aquathorn321 775 — 4d
1
like hiim said, you'll be fine writing the function outside of the constructor. you won't see much of a performance difference at all. being able to read the code is much more important royaltoe 3678 — 4d
0
Thanks for the feedback. My goal is really just to have responsive input and to mitigate server traffic so that I don't have issues when I'm running servers with 30+ people. I really have no experience with running a game yet so I'm not sure how efficient I need to be. aquathorn321 775 — 4d