Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

[SOLVED] I have a problem with OOP and I don't know why it's happening!?

Asked by
Griffi0n 315 Moderation Voter
5 years ago
Edited 5 years ago

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!

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. ScrewDeath 153 — 5y
0
Okay. I somewhat understand that but what should I change to fix it? Griffi0n 315 — 5y
1
Don't work much w/ metatables, but try "local self = {}" ScrewDeath 153 — 5y
0
Thanks! Griffi0n 315 — 5y
View all comments (2 more)
0
Oh yeah this is my first game that uses OOP Griffi0n 315 — 5y
0
How many times are you gonna attempt to lock this question? Zafirua 1348 — 5y

Answer this question