Accessing OOP constructor when a method is called

Hi, I’m unsure on how to access my constructor’s self variables from a method of the class. (Object Oriented Programming).

-- My module script in replicated storage.
local class = {}

function class.new()
    local self = {}
    self.message = "Example Value"

    return setmetatable(self, class)
end

function class:Setup()
    print(self.message) --> nil
    --Trying to access the variables I defined in class.new
    --Is there someway I can accompish this without declaring
    --class.new() somewhere?
    --Do I use getmetatable() somewhere??
end

If you add class.__index = class under the class variable at the top of your script it should fix your issue.

-- My module script in replicated storage.
local class = {}
class.__index = class -- Added this line here

function class.new()
	local self = {}
	self.message = "Example Value"

	return setmetatable(self, class)
end

function class:Setup()
	print(self.message) --> nil
	--Trying to access the variables I defined in class.new
	--Is there someway I can accompish this without declaring
	--class.new() somewhere?
	--Do I use getmetatable() somewhere??
end

return class

I’m not sure if I fully understand. To be able to access the variables defined in class.new() you must first call it.

However, if you call a function using : you can access the self table. self is a table that is passed as the first argument when you call a function using : so you can do something like this.

local module = {}
module.someVariable = "something"

function module:test()
	print(self.someVariable) -- "something"
	
	self.anotherVariable = "some string" -- Defines a variable called anotherVariable in the self table
	print(self.anotherVariable) -- "some varible"
end

return module

This is a good explanation of what self is: What is self and how can I use it? - #2 by WallsAreForClimbing

2 Likes