I am still trying to learn how to use Object-Oriented Programming and I have learned some extreme basics about how it works. My problem is that I struggle to think of how I can practice using it.
Can someone give me some basic ideas that use OOP so I can practice? Thanks.
Just search up OOP examples online, Python examples would translate pretty well to Lua.
But the basic idea is you have your class.
local Class = {}
Class.__index = Class
What __index
does it set it so when you index into a table with it’s metatable set to the class, it will check the class for the index before returning nil
.
Then you have your Constructor.
function Class.new()
-- you don't always need to use setmetatable
local self = setmetatable({}, Class)
-- construct your object
return self
end
And then you have your methods.
function Class.Method()
print("This is a method used by the class!")
end
-- [insert more methods here]
(Use the ‘:’ syntax for functions when you need to use self.)