Is this scripting in OOP?

Hello,

I’ve been trying to get a better grasp of scripting using Object-Oriented Programming (OOP) in Roblox, but I find it quite challenging.

I came up with the following example to understand it better:

local module = {}

module._Value = 10

function module:changeValue()
    self._Value = 10
end

return module

is this right?

It’s close, but this is not exactly what OOP represents.

OOP, or object-oriented programming, is a paradigm in which a class exists (e.g: Person) and objects are created upon using that class.

Lua does not support classes natively. However, with the use of metatables you can simulate a class-based implementation.

Here is a basic implementation of a Person class in Lua using metatables:

local Person = {}
Person.__index = Person --//__index is a metamethod. Basically what this does is refer back to the Person table (and any defined functions within it) if a nil field is indexed in the table object that has this metamethod assigned to it.

function Person.new(name, age) 
--//This is a constructor. It creates new objects of the Person class, taking in two arguments: the name and the age, and assigns these as fields belonging to the new object instance.
local self = setmetatable({}, Person)
--//Disregard the syntax highlighting on 'self'. It's just a new object created from the Person class. 
--//We call setmetatable on the new table object so it can reference the defined
--//functions from the Person object.

--//Add fields specific to this new object of Person
self.name = name
self.age = age

return self
end

function Person:WhoAmI() --//Every object created from the Person class can call this function.
print(`My name is {self.name}, and I am {self.age} years old!`)
end


--//Create a new instance of the Person class
local Bob = Person.new("Bob", 23)
Bob:WhoAmI()

I’d also recommend checking out some basic tutorials on OOP from other languages to help you grasp the general concepts better. Then, this example should make a lot more sense.

Hopefully this steers you in the right direction. Cheers.

Thank you, this is very helpful.

1 Like