Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 6 years ago
Edited 6 years ago

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;

1while true do
2    doOnceThing
3        print('Script started.')
4    end
5    --Some other code
6end

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.

0
Use two codes JakePlays_TV 97 — 6y
0
@JakePlays_TV what you meant? AkinokMiner 17 — 6y

2 answers

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

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

1local doOnceThing = 1
2    while true do
3        if doOnceThing == 1 then
4            --insert your code here
5            doOnceThing = doOnceThing + 1 --this will make it never run again
6        end
7        --Some other code
8    end

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

0
Oh thank you so much I am so dumb AkinokMiner 17 — 6y
0
How do I mark as working AkinokMiner 17 — 6y
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. SteelMettle1 394 — 6y
0
fyi the local variable is read as nil in the loop DeceptiveCaster 3761 — 6y
View all comments (3 more)
0
and in line 3 you forgot the word "then" DeceptiveCaster 3761 — 6y
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 SteelMettle1 394 — 6y
0
Notice my answer Senpai ;-; Tymberlejk 143 — 6y
Ad
Log in to vote
1
Answered by 6 years ago
Edited 6 years ago

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

1print('Script started.')
2 
3while true do
4    -- Some other code
5end

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:

1local didOnceThing = false
2 
3while true do
4    if didOnceThing == false then
5        print('Script started.')
6        didOnceThing = true
7    end
8    -- Some other code
9end

Though it's better to use the first way.

0
I know but read the edit part. Thanks anyways AkinokMiner 17 — 6y
0
No problem Tymberlejk 143 — 6y

Answer this question