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.

local Car = {}
Car.__index = 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:

-- Old constructor
function newCar(color)
	local car = {}
	car.color = color
	car.speed = 0
	setmetatable(car, CarMetatable)
	return car

-- Brand-new simplified constructor
function Car.new(color)
	return setmetatable({
		color = color;
		speed = 0;
	}, Car)

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.

-- Such honk, much beep, wow.
function Car:honk(self)
	print("Beep beep!")

-- Vroom vroom, what a clean looking method!
function Car:accelerate()
	self.speed = self.speed + 20

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

return Car

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.

local Car = require(game.ServerScriptService.Car)

local ferrari = Car.new("red")
local bugatti = Car.new("blue")



print("My Ferrari is going " .. ferrari.speed .. " miles per hour")
print("My Bugatti is going " .. bugatti.speed .. " miles per hour")

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.

Author: Ozzypig

Roblox developer and computer scientist. I love all things coding and game design!