I have a module script that is inside a pet, which gives a extra amount of a stat to a player. Inside this module, I am attempting to set the amount the player is given to the value of a StringValue in the player.
The issue is that I get the message “Attempt to index nil with ‘FindFirstChild’” in the output.
Script:
local plr = game.Players.LocalPlayer
repeat task.wait() until plr:FindFirstChild("StringValue") ~= nil
local E = plr:FindFirstChild("StringValue")
local module = {
Extra = E.Value
}
return module
Make sure this is required by a local script. You can only use the LocalPlayer inside of a local script, which also means the module will only work if required by a local script.
Module doesn’t have to be the first thing- it just has to be not in the loop’s scope, if it is local. The local keyword means that it is only defined in the scope that it’s created in, and once it goes out of scope, that variable gets de-referenced.
In his case, the module variable actually needs to be created after his loop, since his loop is making sure that the string value exists, which I assume he made because it sometimes doesn’t exist yet, by the time this module runs.
I think of a module as a library because it gets included into other scripts/modules. Here’s the layout that I use:
--[[
Some comments about the module.
--]]
local suchAndSuchModule = {}
-- ******** Requirements
-- ******** Local Data
-- ******** Private Functions/Methods
-- ******** Public Functions/Methods
-- ******** Event Handlers
-- ******** Initialization
return suchAndSuchModule
One thing that I do want to point out is that it’s considered an error to have any code after the module’s return statement.
local module = {}
local plr = game.Players.LocalPlayer
module.getExtra = function()
local strValue = plr:WaitForChild("StringValue", 10)
if strValue == nil then
return nil
end
return strValue.Value
end
return module
Although you can use FindFirstChild, I tend to prefer WaitForChild because it resolves certain timing issues that can cause a race condition. It will wait up to 10 seconds before returning with either the requested item or nil. The if/then statement prevents a nil reference error when trying to index the Value of a nil component. So it will return either the value or nil. Or you can return a fixed value instead of nil if you prefer.
To use this, just include your module with the require keyword and call the function.
local someModuleName = require(path/file name of module)
local E = someModuleName.getExtra()
I don’t know what the rest of your code looks like, but you replace your module code with the code that I have written. Then you include the module everywhere you need to and just call the function to get the value. In addition to doing it this way, you can add other functions to the module too using the same format.