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.