Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Why is my class instance nil?

OOP HELP... I have created my own class Point and I have 2 simple methods in it Point:print() and Point:getMagnitude(). Here is code:

local Class = require(game.ReplicatedStorage.Class) -- Template (see note at bottom)

local Point = Class:extend()

function Point:new(x,y,z)
    self.X = x or 0
    self.Y = y or 0
    self.Z = z or 0
end

function Point:print()
    print(self.X,self.Y,self.Z)
end

function Point:getMagnitude()
    return math.sqrt(self.X^2+self.Y^2+self.Z^2)
end

return Point

My problem is when I run some server code that tests the class I get this error: ReplicatedStorage.Point:12: attempt to index nil with 'X' I don't see any typos, and I do have a constructor method that should give me self... Help me! :( Server Code:

local Point = require(game.ReplicatedStorage.Point)
local pointA = Point(3,4,5)
pointA.print()
local pointAMag = pointA:getMagnitude()
print(pointAMag)

Summary: self is nil when it should not be...

Line 1 Documentation: https://github.com/rxi/classic

1 answer

ANSWERED: By @TimScript on the discord server

This line: pointA.print()

Needed to be: pointA:print()

This discussion is preserved as it was. New answers, comments, and votes are closed.