I’m trying to use object oriented programming in my code because it makes it neat and reusable but I have a problem.
Here’s an example of my problem:
local class = {}
class.a = 1
class.print = function() print(class.a) end
class.__index = class
local new = setmetatable({}, class)
new.a = 2
new.print()
So over here, a is the value in the table, and print is a function that prints a.
The problem is, with the second table, I change a to 2, so I want print to print 2 now instead of 1. But it still prints 1, and I’m not sure how to get around this problem.
The advantage of OOP is that you can use self and : notation. I believe this is what you are looking for:
local class = {}
class.a = 1
class.print = function(self) print(self.a) end
class.__index = class
local new = setmetatable({}, class)
new.a = 2
new:print() --prints 2
new.print(new)--also prints 2