I have a question. Lets say I have a module script and I do this
local module = {}
local car
function module.setcar()
for i,v in pairs()do
if v.BrickColor = BrickColor.new("Really red") then
car = v
end
end
function module.destroyCar()
--Will I be able to access car and change its properties in this function, for example
if car.Parent ~= something then
print(something)
end
end
return module
I am doing something similar to this and appeartly it says that I attempted to do nil with Parent. What I am asking is how do I get variables outside of functions
I suggest using self here so the car is apart of the module. To use self, just use : instead of . when declaring the function.
local module = {}
module.car = nil
function module:setCar(t)
for i,v in pairs(t) do
if v.BrickColor == BrickColor.new("Really red") then
self.car = v
end
end
end
function module:destroyCar(something)
if self.car.Parent ~= something then
print(something)
end
end
return module
local tool = {}
local chosen_spawner
local tool
local foundtool = false
function tool.TrackTool()
for _,spawner in pairs(game.Workspace.Spawners:GetChildren()) do
if string.match(spawner.Name,"ToolSpawner") then
if spawner:FindFirstChildWhichIsA("Tool") then
chosen_spawner = spawner
tool = chosen_spawner:FindFirstChildWhichIsA("Tool")
if tool.Parent == chosen_spawner then
print(tool)
print(chosen_spawner)
print("Tool found")
foundtool = true
end
end
end
end
end
function tool.OnToolSpawn()
if tool.Parent ~= chosen_spawner and not foundtool then --"tool" is nil
print("Tool has not spawned yet")
elseif foundtool and chosen_spawner ~= nil and tool.Parent == chosen_spawner then
print(chosen_spawner)
end
end
return tool
Why are you know posting a different script? Can you please take some time to write a few sentences on your issue since now I’m just lost is what the issue is. This is starting to become an XY problem.
Well the issue here is you are redeclaring the tool variable, so you end up returning nothing when requiring the module. To fix this, just name the module and tool variable differently. Next, use self like I mentioned in my last reply to define the tool inside the scope.
local foundtool = false
local module = {}
module.tool = nil
module.chosen_spawner = nil
function module:TrackTool()
--for loop, if statements
self.chosen_spawner = spawner
self.tool = chosen_spawner:FindFirstChildWhichIsA("Tool")
end
function module:OnToolSpawn()
local tool = self.tool
end
return module
Self just refers to the module the function is inside. When you add a function to a module using function module:TrackTool(), self would refer to the module and it’s contents, including tool and chosen_spawner.