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;

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.

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

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.

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:

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.

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

Answer this question