Object Oriented Programming in Lua (Part 1 – Concepts)

Hi everyone! This multi-part tutorial is all about object-oriented programming (OOP) in Lua. In later parts, I’ll apply this information to Roblox Lua. For this tutorial, you should be fairly comfortable with Lua tables. If you’re new or rusty, read this chapter from Programming in Lua. 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. But what’s an object, really? For the purposes of OOP, it is something that represents a real thing, and it has these three distinct qualities:

Identity

The object is distinctly identifiable or different from similar objects.

Examples
  • Cars are different even if they’re the same make, model and color.
  • Players are different even if they share a score or chat the same messages.

State

The object describes its present qualities represented using fields.

Examples
  • A car’s make, model or speed
  • A player’s name or score
  • A button’s text and if it is disabled

Behavior

The object describes what actions it can perform using methods.

Examples
  • A car can turn on its engine, accelerate and honk its horn
  • A player can connect to a game, earn points, and chat
  • A button does something when it is clicked

To Roblox scripters, all this should really familiar! Every object that you’ve used follows this model:

The words “Part” and “ParticleEmitter” are the names of classes, which can be described as a blueprint, template or contract for what an object is. These blueprints define the fields and methods by which objects’ state and behaviors are identified.

For now, that’s all the theory you need to understand! In the next article will talk about metamethods and some Lua syntax subtleties that will help us implement classes.

Click here for Part 2 of this tutorial series.

Author: Ozzypig

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