Object Oriented Programming in Lua (Part 4 – Clean-up)

This final part of this tutorial series will talk about some ways to clean up the example from the previous part and apply it to Roblox. First thing’s first: let’s move the entire Car class defintion into its own ModuleScript called “Car” inside ServerScriptService. Now we can combine the CarMetatable and CarMethods into a single table. Just have __index refer to the table itself. Let’s call the table Car.

Next, we can package the newCar constructor into this table. Remember that setmetatable(t, mt) returns the table  t whose metatable we are setting in the function call. The constructor can be simplified to just this:

Notice that we are creating the new object table inside the setmetatable  function, which will both set the metatable and then return it from the constructor. Finally, we fix the method definitions as well.

Since this is inside a ModuleScript, return the Car table on the final line.

Since we are creating objects, we can make many of them at once with all unique identitiesstates and methods. Here’s an expansion of the previous part’s examples. This should go in a script somewhere inside your game.

And that’s it! You should download the code for the Car class and example script. Play around with creating your own classes. It’s a lot of fun and you’ll find object oriented programming is a fantastic way to make your code more organized. If you have questions, send me a direct message on Twitter or a message on Roblox.

Object Oriented Programming in Lua (Part 3 – Examples)

In this section, we will apply the information from the last two sections into an actual example. Let’s implement a Car class in which we will make Car objects. Cars have a state (like their color or speed) as well as behavior like accelerating or honking the horn. We will create fields and methods for both of these.

We start by defining a car metatable and a table of car methods. We set the __index  metamethod so when a new car object is given this metatable, we can access our methods through it.

Next, we write a function to create a new car of a certain color and set the metatable properly. Additionally, we can initialize the speed field to zero. A function like this is called a constructor.

Excellent, now write some methods for the car, like acceleration and honking the horn. Store these in the CarMethods  table. Remember that we’re going to call these methods with colon syntax, so the first argument is going to be the car we’re working with. Let’s call this first parameter  self .

An important thing to mention here is that the following function definitions are all equivalent:

For the last one, we are defining the function with a colon! This tells Lua that we’re going to implicitly create a local variable called self  which refers to the first argument to the function. Conveniently, when we call the method with the colon syntax, self is automatically filled with the car in question.

And this is all we need to have something workable. Create a new car with the newCar  function and use some of its methods (don’t forget to use a colon instead of a period)!

In the next article, we’ll talk about ways to clean up this code more.

Click here for Part 4 of this tutorial series.

Object Oriented Programming in Lua (Part 2 – Metatables)

Part 2! This is all about metatables, which will be the main tool to implement OOP in Lua. Metatables, put simply, are Lua tables that describe the behavior of other Lua tables. You can use getmetatable(tab)  and setmetatable(tab, meta)  to manage a table’s metatable:

Now that you’ve set a table’s metatable, you can now set metamethods. These are special keys in the metatable that define specific behavior when set to a function, for example: __index , __add , __sub , __tostring , __eq and others. Notice how their names all being with two underscores (_). These metamethod functions are called when you do things with the table in question. It’s important to take time and read up on the behavior of each metamethod on your own, like how __add  is called when you add two tables with the same metatable.

We’ll be using __index to implement classes and objects. This metamethod is called when you try to index a key (doing  tab[key] or tab.key, remember these are equivalent) that hasn’t been set in a table yet:

In the above example, the goodbye print statement attempts to index world in my_tab . Since that key hasn’t been set in  my_tab  (it is nil), Lua calls our  __index  function with  my_tab  and  world as arguments. The function returns the string  cruel world , which is returned to the goodbye print statement. This code will output:

This example is pretty crucial to understand what’s going on behind the scenes and why. A key feature of __index is that you don’t have to set it to a function. You can also set it to another table instead! The behavior is now as follows: if you index something that isn’t in the table, it checks the table in __index instead (like a backup table).

Why is this important? For our objects, we will be creating a table of the functions (methods) that every object of one kind should have. We’ll set the metatable of the objects to equal this table of functions so that we don’t have to copy functions over to every instance of an object when it is created.

However, before we get to that, we have to understand colon syntax for method calling (remember that a method and a function are essentially the same, except that the word method is used in the context of OOP). In Roblox Lua, you are required to call methods like Destroy by using a colon. How is this different from using a period? When you use a colon in a method call, Lua sends the table itself (the left of the colon) as the first argument to the function. For example, if you had a table foo  with a function bar , then calling foo:bar()  is the same as foo.bar(foo) . More info about this behavior can be found in Chapter 16 of Programming in Lua. It’s syntax sugar.

When you use a colon in a method call, Lua sends the table itself (the left of the colon) as the first argument to the function.

Let’s put this all together: we can store our object’s methods (functions) inside a table. We set this table as the __index for the metatable of newly created objects. We call these methods using colon syntax so our functions can access the object we’re talking about. In the next article, we will take all these abstract topics and apply the concepts to concrete examples.

Click here for Part 3 of this tutorial series.

Object Oriented Programming in Lua (Part 1 – Concepts)

Hi everyone! This multi-part tutorial is all about object-oriented programming (OOP for short) in Lua. I’ll be applying this information to Roblox’s flavor of Lua. For this tutorial, you should be fairly comfortable with tables (read this chapter from Programming in Lua if needed) as well as how ModuleScripts work. You’ll learn what metatables are and how they can be used to simulate OOP in Lua. Many of the concepts you’ll see here are applicable to other programming languages, namely Java or C#. If you’re going into computer science later in life, this is good to expose yourself to early.

Let’s first talk about what object-oriented programming means: programming involving the use of objects. Objects are distinctly identifiable entities. For example, a car, a button on-screen, a player in-game, or a tool/weapon. Objects have their own individual identities, states and behaviors:

  • The identity of an object just means that it is different from other objects of its kind.
  • The state of an object, such as the current speed of a car or player’s score, are represented by fields.
  • The behavior of an object is defined through methods which are actions the object can perform. A car can accelerate, a player can earn more points, and a button can be pressed.

This should sound familiar to Roblox scripters because every object with which you’ve worked follows this model! A Part has a BrickColor property (a field representing state); a ParticleEmitter can emit particles (a method representing behavior).

In this tutorial, we’re going to make our own blueprints for objects. These are called classes. These blueprints define all the fields and methods by which our objects’ state/behaviors will be identified.

The next article will talk about metamethods and some Lua syntax subtleties that will help us implement these behaviors.

Click here for Part 2 of this tutorial series.