How could I make placeholder variables at module scripts?

Hello!I am currently revamping my weapon framework using oop, however, everytime I try to call a variable created by the constructor function, it comes out as nil(expected).

How can I make a placeholder variable for module scripts which will be given their actual values when a module script function is called on a server script?

for example, a module doesn’t know which tool is the function for until it is called on a server script.

Here is an example code taken from my module script:

local Gun = {}
Gun.__index = Gun
function Gun.New(Tool1)
	local GunSettings = {}
	setmetatable(GunSettings, Gun)
	GunSettings.Tool1 = Tool1
	return GunSettings
end

print(Gun.GunSettings.Tool1) --results in an index nil error, I don't know why...
return Gun

It also gives me a “Requested module experienced an error while loading”, which I assume it’s from the variable created by the constructor(I hope)

I would really appreciate an answer :slight_smile:

You can access the object GunSettings by calling methods on it and accessing the hidden self parameter inside those methods.

For example:

local Gun = {}
Gun.__index = Gun
function Gun.New(Tool1)
	local GunSettings = {}
	setmetatable(GunSettings, Gun)
	GunSettings.Tool1 = Tool1
	return GunSettings
end

function Gun:PrintTool()
  print("self.Tool1:", self.Tool1)
end

return Gun

Usage:

local Gun = require(script.Gun)

local mygun = Gun.New(someTool)

-- can call methods which will use mygun as ‘self’
mygun:PrintTool()

-- also can just access properties directly
print("direct access:", mygun.Tool1)
1 Like

Oh, I have never known about that self parameter!

Just a question, how does self work exactly? is it a way to call the constructor function in the script or it’s something else? (I’m new to ooc)

Also why is a string and another value given, wouldn’t a string be enough?

sorry for late reply

Programming in Lua : 16 should walk you through what the self parameter is and Programming in Lua : 16.1 should talk about how metatables fit in.

Basically though

function Gun:PrintTool()

is exactly the same as

function Gun.PrintTool(self)

And you can call either version with either mygun:PrintTool() or mygun.PrintTool(mygun), interchangeably (notice the colon in the first one). The language just makes the syntax nice for you.

Sure, I was just adding the string so you could differentiate the two lines in the output.

1 Like