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)
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)
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.