I’m trying to set the variable minCount to the value of an IntValue called minCount in a part. This is the relevant code:
bases = {}
basesFolder = game.Workspace.bases
for i, v in ipairs(basesFolder:GetChildren()) do
bases[i] = v
end
for v in bases do
minCount = v.minCount.Value
end
Instead of setting the variable to the IntValue, it returns “attempt to index number with ‘minCount’” and the script stops. How do I fix this?
bases = {}
basesFolder = game.Workspace.bases
for i, v in ipairs(basesFolder:GetChildren()) do
bases[i] = v
end
for i, v in pairs(bases) do
if v:FindFirstChild("minCount") and v.minCount:IsA("IntValue") then
minCount = v.minCount.Value
else
warn("Not Found " .. v.Name)
end
end
Yea noticed the for in loops always get 2 variables so on your second loop you only have 1 meaning v = number index instead of the bade object. Changing it to for i’v … fixes it
Depending on the situation I don’t recommend using pairs since the order of operation isn’t guranteed to go in the number order. These days the ipairs and pairs are no longer needed and the syntax of for i, v in list do is completely valid
If you need the mincount to be personalized for each object:
bases = {}
basesFolder = game.Workspace.bases
for i, v in ipairs(basesFolder:GetChildren()) do
bases[i] = v
end
for v in bases do
local minCount = tonumber(math.floor(v.minCount.Value))
end
else:
bases = {}
basesFolder = game.Workspace.bases
for i, v in ipairs(basesFolder:GetChildren()) do
bases[i] = v
end
for v in bases do
minCount = tonumber(math.floor(v.minCount.Value))
end
As mentioned here, the issue comes from the lack of defining a 2nd variable in the second for loop.
-- The "v" is the problem.
for v in bases do
minCount = v.minCount.Value
end
The first variable defined in a for in loop will always be an index which is the number. So if for example v is 0 the code is trying to run 0.minCount.Value which throws the error.
-- This works now
for i, v in bases do
minCount = v.minCount.Value
end
By defining index to be i lets the for in loop define v as the actual base instance which is more valid. To be safe you should introduce some FindFirstChild checks to actually make sure minCount can be found.
for i,v in bases do
local foundMinCount = v:FindFirstChild("minCount")
if foundMinCount and foundMinCount:IsA("IntValue") then
minCount = foundMinCount.Value
end
end
This needs a full explanation on what this is doing and how everything is set up.
Going off what you said was the error: “attempt to index number with minCount”
That sound like you picked the wrong .Value …
Are you sure you manually added that as a number and not a int?
Oh yeah; can’t believe my eyes missed that. I suppose because of the lack of an i before the v, the for loop is simply taking v to be a variable name for i, thus v has become the index. And because indexes are numbers, this results in the error. Nicely spotted