Modulated OOP

This tutorial teaches you how to create a module using OOP!

by uhTeddy

Author Avatar

Hey, today we're going to learn how to use OOP in our every day modules!

Before we start lets define OOP.

OOP is a way to create custom instances / classes with metatables

How do we template the module?

local OOP = {}
OOP.__index = OOP


return OOP

This is how you start off the OOP module!

Now lets create a function that creates the class

local OOP = {}
OOP.__index = OOP

function OOP.new(first, last) -- Must use the period to fit syntax
    local self = setmetatable(OOP, {})
    self.first = first -- Sets the dictionary key of first to the argument first
    self.last = last -- does the same as first did with last
    return self -- returns the object
end

return OOP

Now that we've created the object with the arguments of first and last lets create a function that will use those properties and make something

local OOP = {}
OOP.__index = OOP

function OOP.new(first, last) -- Must use the period to fit syntax
    local self = setmetatable({}, OOP)
    self.first = first -- Sets the dictionary key of first to the argument first
    self.last = last -- does the same as first did with last
    return self -- returns the object
end

function OOP:returnName() -- Must use the : for the correct syntax
    return self.first .. " " .. self.last
end

return OOP

That will return a string value of the first and last name that was set with the OOP.

Now, how do we use this well, we need to create a serverscript!

local OOP = require(PATHTOMODULE)

local Person = OOP.new("Bob", "Rosey")

print(Person:returnName()) --// Output: Bob Rosey

That's all I have to say! I hope this helped and I hope this makes your scripting experience even better!

View in-game to comment, award, and more!