While loop not looping

I am making a simple quest dialog system but the loop is not looping.

LocalScript:

local MessagesLeft = #Conversation:GetChildren() -- =2

while MessagesLeft > 0 do
	local MessageInfo = Conversation[MessagesLeft-(#Conversation:GetChildren()-1)]
	SpeakerName.Text = MessageInfo.Speaker.Value
	Text.Text = MessageInfo.Text.Value
	print(1)
	Button.Activated:Wait() -- TextButton
	MessagesLeft-=1
	print(2)
end
print(3)

What it prints:

-- 1
-- 2

It prints 2 after I click the button

But the text does not change (When I click the button) and it doesn’t print anything else


What I need it to do:

Loop until there are no messages left then it ends the loop


Am I missing something?

1 Like

Do you have any errors in your output? Your MessageInfo declaration is probably incorrect. I am not sure what value you want to get out of it but MessagesLeft-(#Conversation:GetChildren()-1) is going to start at 1 and then reduce to 0, which is an invalid index.

Do you want to go up the Conversation array or down it?

1 Like

There are no errors

while MessagesLeft > 0 do (while MessagesLeft is bigger than zero) wont error because it doesn’t go below 1. I don’t think

1 Like

Right MessagesLeft doesn’t go below zero, but the subtraction of #Converstaion:GetChildren() will push it over.

Loop by loop:

MessagesLeft = 2 | #Conversation - 1 = 1 | Total = 1
MessagesLeft = 1 | #Conversation - 1 = 1 | Total = 0

1 Like

I want it to go down the list

1,
2,
3,
--etc

I would flip the entire loop so it’s more logically positive. This will count up instead of trying to count down and converting to up.

local MessagesRead = 0
local TotalMessages = #Conversation:GetChildren()
while MessagesRead < TotalMessages do
    MessagesRead += 1
    local MessageInfo = Conversation[MessagesRead]
    -- etc ...

It works

My final code:

    local MessagesRead = 1
	Button.Visible = true
	while true do -- Changed to true so i can break the loop when i want
		local MessageInfo = Conversation[MessagesRead]
		SpeakerName.Text = MessageInfo.Speaker.Value
		Text.Text = MessageInfo.Text.Value
		print(1)
		if MessagesRead == #Conversation:GetChildren() then break end -- Break the loop
		Button.Activated:Wait()
		MessagesRead+=1
		print(2)
	end
	print(3)

Thanks for helping :smile:


I still don’t know why it would not loop the first time

  1. It did not error
  2. It did not print 3
1 Like

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