SOLUTION BY ScrewDeath:

local Class = {}
Class.__index = Class
Class.new = function(someProp)
	local self = {}
	self.someProp = someProp
	setmetatable(self, Class)
	return self
end

function Class:method()
	print(self.someProp)
end

local x = Class.new(10)
local y = Class.new(100)

x:method()
y:method()

QUESTION:

NOTE: I suck at programming.

Here's a basic class I made (I probably did something wrong and that's probably the cause of it)

local Class = {}
Class.__index = Class
Class.new = function(someProp)
	local self = Class
	self.someProp = someProp
	setmetatable(self, Class)
	return self
end

function Class:method()
	print(self.someProp)
end

local x = Class.new(10)
local y = Class.new(100)

x:method()
y:method()

Now when I run this I get:

100(x2)

And if I do (after I declared them)

print(x)
print(y)

I get the exact same table!

If I remove y that seems to fix the problem but if I do this

local x = Class.new(10)
print(x)
local y = Class.new(100)
print(y)

I also get the exact same table! What is going on!

If I spawn a new thread for when I use them it seems to fix the problem but this feels hacky so I want to know how and why this is going on!

6 comments

1

Problem is Line 4. The reason behind setmetatable is that it will reference "Class" when it cannot find a value. Your Line 4 basically makes every instance refer to Class and not its own distinct object.

0

Okay. I somewhat understand that but what should I change to fix it?

1

Don't work much w/ metatables, but try "local self = {}"

0

Thanks!

0

Oh yeah this is my first game that uses OOP

0

How many times are you gonna attempt to lock this question?