Metatables, the tool you need

Recently, i was invited to help dev a game with a group of people i haven’t worked with in a very long time. As you all may have known from one of my previous blog post about how i create objects with modulescripts, you may have noticed i use metatables and briefly mentioned it in the blog post. If you haven’t looked into the resources i provided in that post, then you should as that would greatly help you understand what I’ll be talking about in this post.

As i was looking over the scripts the other team members had edited to make the game to where it was, i saw this:

For those who do not know what this is, this is a list of services Roblox provides being saved into variables and most of them not being used in the script (i know, i checked). I thought, “there has to be a better way of getting/using a service”. Guess what, there is! Introducing


Oh wait, these aren’t new to you guys… kinda. Okay, so skipping the intro of metatables and going straight to the bone. A metatable has various metamethods which can be used to create pretty amazing stuff. In this case, to make our lifes easier and code much more elegant to read. If you click the metamethod link from one of the previous sentences you may have seen a metamethod called “.__index” which we have used. We can use this metamethod to make our life easier (again):

How We Make Our Life Easier (again)

Firstly, we look at the description of the metamethod “.__index” which can be found on the Lua or Roblox site. By reading, we know that this method is called when a table is indexed, by either “.” or with brackets it also passes two arguments into the function when invoked. To use this, we could setup a function that returns the service when indexed, when we need it. Like so:

Then we can just require the ModuleScript and index the variable where the modulescript is required and use any service when we need it!

Goodbye long-list of variables, hello no-list!


Of course, the only downside i see to using this is that there is no code-completion. You would either have to write it all down from memory or look at the documentation while indexing to make sure you have the name written down correctly. Also, you might want to add a cache system where it caches the service instead of having to get it everytime it is called.

Published by mawesome4ever

I am a scripter. I enjoy scripting things in Lua and enjoy teaching it as well as helping other with the language.

Leave a comment

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: