How do I update this loop?

I need to know how I update this loop. Each time a child is added in the box, the maxNum changes. However, the loop doesn’t update.

    local minNum = 3
    local maxNum = 5 
	workspace.Box1.ChildAdded:Connect(function()
		maxNum += 1
	end)

	for i=minNum, maxNum do
       print(i)
	end

I know why it doesn’t update, but is there anyway to update it so the dev console would be like this:

3
4
5
--child gets added in the box
6
--stop
--child gets  added in the box oncemore
7

I’m stumped.

For that i should be a global variable.

    local minNum = 3
    local maxNum = 5
    local i = minNum
    workspace.Box1.ChildAdded:Connect(function()
        i += 1
       print(i)
    end)
    for _ = minNum, maxNum do
        print(i)
        i += 1
    end
1 Like
    local minNum = 3
    local maxNum = 5 

	for i=minNum, maxNum do
       print(i)
	end

	workspace.Box1.ChildAdded:Connect(function()
		maxNum += 1
        print(maxNum)
	end)

If you just want to print the added number why go through the print loop again after the maxNum is increased? Just print it inside the ChildAdded function.

1 Like

Since I want the loop to run it

but ChildAdded will run everytime a child is added and will work exactly as you want it to.
i don’t understand why you need a loop to do that

2 Likes

To achieve the desired behavior, you need to modify your loop structure. Currently, the loop is executed only once, and it uses the initial values of minNum and maxNum. However, you want the loop to dynamically update each time a child is added to Box1 in the workspace. Here’s an updated version of your code that should work as intended:

local minNum = 3
local maxNum = 5

local function printNumbers()
	for i = minNum, maxNum do
		print(i)
	end
end

workspace.Box1.ChildAdded:Connect(function()
	maxNum = maxNum + 1
	printNumbers()
end)

printNumbers() -- Initial execution of the loop

In this updated code, I’ve extracted the loop into a separate function called printNumbers(). This function will be called both initially and each time a child is added to Box1. After updating maxNum, the printNumbers() function is called to print the updated sequence of numbers.

Note that the initial execution of the loop is done outside of the event connection to ensure the initial values are printed as well.

that’s an overcomplication, plus every time a child is added it will print everything from 3 again so doesn’t work properly

local function printNumbers()
	for i = minNum, maxNum do
		print(i)
	end
    minNum = maxNum + 1
end

you can change the function to this to make it work but still complicated for no reason

This was my original solution, however it behaved like how Fimutsu said

You’re correct. Sorry about that!