#(I am learning OOP) Why won't this work?

31 messages · Page 1 of 1 (latest)

misty smelt
#
------------- Module ------------------
local Thing = {}
Thing.__Index = Thing

function Thing.new(name)
    
    local self = setmetatable({}, Thing)

    self.Score = 0
    self.Name = name
    
    return self
end

function Thing:Rename(newName)
    self.Name = newName
end

return Thing

------------- Server Script ------------------
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local module = require(ReplicatedStorage:WaitForChild("ModuleScript"))

local thing = module.new("yes")
print(thing.Name)
thing:Rename("no")
print(thing.Name)

#

I keep getting an error saying " attempt to call missing method 'Rename' of table"

flat nexus
#

make a variable for a table

#
local newTable  = {}
#

add properties to that table

#

then do setmetatable on that table like this ```lua
setmetatable(newTable, Thing)

#

if i were writing it, it would look something like this ```lua
function Thing.new(name)
local newThing = {}
newThing.Score = 0
newThing.Name = name
setmetatable(newThing, Thing)
return newThing
end)

misty smelt
#

When I run it, it still comes out with the same error

#

Now it is printing "yes" but gives "attempt to call a nil value" when I rename it

flat nexus
#

why are you using self as a parameter?

#

this lua function Thing.Rename(self, newName) self.Name = newName end could just be this ```lua
function Thing:Rename(newName)
self.Name = newName
end

#

but it is a rename function?

misty smelt
#

Like this ?


local Thing = {}
Thing.__Index = Thing

function Thing:Rename(newName)
    self.Name = newName
end

function Thing.new(name)
    local self = {}
    self.Score = 0
    self.Name = name
    
    setmetatable(self, Thing)
    return self
end

return Thing
misty smelt
#

It still gives " attempt to call missing method 'Rename' of table"

flat nexus
#

line 2 should be ```lua
Thing.__index = Thing

#

you have a capital i for index

misty smelt
#

oh

#

wow

#

It was that simple

#

lol

flat nexus
#

does it work?

misty smelt
#

yes

flat nexus
#

nice

misty smelt
#

Thank you!

flat nexus
#

thats quite funny

flat nexus
sonic zinc
#

yeah that was literally the only problem

#

also doing this is fine

local self = setmetatable({}, Thing)