I’m trying to get a live update of the part count of a model, but the issue is, the script that I’m trying to do it in keeps getting this error, how do I fix this?
ServerScriptService.Ganme:17: attempt to get length of a nil valueServerScriptService.Ganme:17: attempt to get length of a nil value
local RemoteEvents = game:GetService("ReplicatedStorage"):WaitForChild("RemoteEvents")
local partCounterRemote = RemoteEvents:WaitForChild("PartCounterChange")
local PartCount = {}
function checkPartCount(map)
for index, _ in pairs(map:GetDescendants()) do
if _:IsA("Part") then
table.insert(PartCount, _)
end
end
end
while task.wait() do
PartCount = checkPartCount(workspace.Building)
print(#PartCount)
end
There’s some shenanigans in this script. You are trying to take the length of the value returned by checkPartCount, which does not return anything (so it will always return nil). You’ve also overwritten whatever PartCount was before with nil, in the line after your while loop starts. Preferably, checkPartCount would just return a number.
Unrelatedly: the variable name “_” should only be used for variables that must be captured but you will not be using. That is, it should be used like this:
for _, value in pairs(map:GetDescendants()) do
if value:IsA("Part") then
table.insert(PartCount, value)
end
-- _ is never used
end
function getPartCount(map)
local countableParts = {}
for _, value in pairs(map:GetDescendants()) do
if value:IsA("Part") then
table.insert(countableParts, value)
end
end
return #countableParts
end
while task.wait() do
print("Number of parts: " ..getPartCount(workspace.Building))
end
You must use the return keyword to give a value back to the calling expression. If 5 parts were counted, the following happens in the print line:
Function call: print("Number of parts: " ..getPartCount(workspace.Building))
becomes → print("Number of parts: " ..5)
string concatenation (… operator) → print("Number of parts: 5")
print is also a function call but whatever it returns (possibly nil) is unused.
(note: return with no following expression will return nil, if a function reaches its end without a return keyword, it also returns nil)
I have moved the # (count) operator to inside the getPartCount function to make its purpose clearer.
I have also switched the variable names in the for loop so that the _ variable is the unused one. If both are used, the conventional names for them are: for index, value in pairs(mytable) do
or just for i, v in pairs(mytable) do
This is not a language rule, just a naming convention.
getPartCount now starts with a local table which holds the parts that should actually be counted. Since this table is local, it is discarded once the function returns. It is also preferable to have functions which do not change values outside their body, instead communicating purely via arguments and return values, the reason is complicated, but it will help keep your code easy to troubleshoot.