OOP allows you to quickly reuse code and modify them. You can duplicate the results of OOP in procedural code, but it will be more inefficient and time consuming.
(Due to the lack of examples in this thread, let me supply you with one )
Let’s say you are making a shooter game with different types of guns that deal different damage, have different reload speed, et cetera. You can use procedural code to write code for each gun. When the player clicks the screen, a bullet fires from the gun:
local reloaded = true
function fireBullet()
if reloaded then
-- player shot takes x damage
reloaded = false
wait(reloadSpeed)
reloaded = true
end
end
Gun.Equipped:Connect(function(mouse)
mouse.Button1Down:Connect(function()
fireBullet()
end)
end)
You can duplicate this code inside all the guns, change its reloadSpeed
and its damage. But come on, who likes copying and pasting for every gun they have in their game? (Especially when you have, like, hundreds of them)
With OOP you can reuse code and easily change the object’s (in this case, the gun) properties. You can change the fireBullet
function just inside the ModuleScript and the change will duplicate across all guns. Or maybe you could add in new functions, properties without having to change all gun scripts.
One handy property of OOP is inheritance. Lets say you want to create a new type of gun that shoot heat-tracking rockets that follow players. You can create a new class that inherits from the main gun class and name it something like rocketGun
, and then just overwrite the fireBullet
function. You won’t have to bind the mouse click event again, since you only overwrote the fireBullet
function, and not the initialize function.
Tbh, I don’t know…
But, quoting @Crazyman32:
Yes, I definitely agree
Well, I recommend watching/reading tutorials on the web. There seems to be very little material on Lua OOP, so if you know another language, you can try to learn OOP in that language (I recommend Python).
After you understand the basics, going through some of the intermediate or advanced tutorials about Lua OOP would be more easy. Also, read some example OOP code and try to understand it. You should also learn about metatables before diving into Lua OOP (it helps).
@Crazyman32 also dug up some interesting material on OOP (nice! ).
And lastly, practice practice practice, as it is the only way to master programming.