Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to execute a part of code once in while loops?

Hi. I have a code and it has a while loop in it. I want code to do something in while loop only once. Here is an example;

while true do
	doOnceThing
		print('Script started.')
	end
	--Some other code
end

How can i do it?

EDIT: I know I can put print() outside loop but it's just an example I can't do it on my own code.

2 comments

0

Use two codes

0

@JakePlays_TV what you meant?

2 answers

✓ Accepted answer

This can be solved with an if statement that is only true if the condition is met. Here is an example

local doOnceThing = 1
	while true do
		if doOnceThing == 1 then
			--insert your code here
			doOnceThing = doOnceThing + 1 --this will make it never run again
	    end
	    --Some other code
	end

This is a bit crude since it will constantly check if doOnceThing is equal to 1, but it will solve your current problem.

7 comments

0

Oh thank you so much I am so dumb

0

How do I mark as working

0

If you mean to say, how do you know it's working for debuggin purposes; then add a print inside the if statement. If you mean to reference that doOnceThing has run, then compare it to the value of 2 since it added 1 to it.

0

fyi the local variable is read as nil in the loop

0

and in line 3 you forgot the word "then"

0

thanks, I fixed the then. and I tabbed the local doOnceThing to show that it is within the same scope as the while loop

0

Notice my answer Senpai ;-;

You can just do that thing before the while loop, like so:

print('Script started.')

while true do
	-- Some other code
end

But if you specifically want the thing to be done in the while loop you can simply add a boolean to the code and then make something like this:

local didOnceThing = false

while true do
	if didOnceThing == false then
		print('Script started.')
		didOnceThing = true
	end
	-- Some other code
end

Though it's better to use the first way.

2 comments

0

I know but read the edit part. Thanks anyways

0

No problem

This discussion is preserved as it was. New answers, comments, and votes are closed.