Issue with for loop

I have a for loop and a cloning event in the for loop, im trying to get it to be parented and cloned to each folder in the nations folder however it only does it for one folder

for _, nation in ipairs(workspace.Nations:GetChildren()) do
	local Nv = Instance.new("NumberValue")
	local gdp = Nv:Clone()
	gdp.Parent = nation
	gdp.Name = "Money"
	while true do
		wait(1)

		for _, province in ipairs(nation:GetChildren()) do
			if province:IsA("MeshPart") then
				gdp.Value = gdp.Value + 50
			end
		end
	end
end

Another question, instead of a while true do loop what would be better to use? Runservice?

There is only one gdp Value in your script.

This should work:

for _, nation in ipairs(game.Workspace.Nations:GetChildren()) do
	local gdp = Instance.new("NumberValue"):Clone()
	gdp.Parent = nation
	gdp.Name = "Money"
end

while task.wait(5) do
	for _, province in ipairs(game.Workspace.Nations:GetChildren()) do
		for _, obj in pairs(province:GetChildren()) do
			if obj:IsA("NumberValue") and obj.Name == "Money" then
				obj.Value += 50
			end
		end

	end
end

In your original code, it would run like this:

  1. Create “Money” NumberValue for “nation”
  2. Begin infinite loop that increases the money of that previously-created “Money” NumberValue.

Having the infinite loop inside the initial for loop prevented the for loop from creating the next “Money” variable until the infinite loop is completed/broken, which never happens according to what you provided.

One thing I wasn’t sure of was this line:

As a result, I didn’t include it in my code above. Let me know if this is necessary in the code.

Also, I added a 5 second wait in the second loop. That can change to your desires. Whatever you change it to will cause a wait of the specified wait time between each money increase.

Thanks it works, and yeah its just checking if its a province or not so it is necessary but I can include it on my own

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.