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.