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;
1 | while true do |
2 | doOnceThing |
3 | print ( 'Script started.' ) |
4 | end |
5 | --Some other code |
6 | 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.
This can be solved with an if statement that is only true if the condition is met. Here is an example
1 | local 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.
You can just do that thing before the while loop, like so:
1 | print ( 'Script started.' ) |
2 |
3 | while true do |
4 | -- Some other code |
5 | 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:
1 | local didOnceThing = false |
2 |
3 | while true do |
4 | if didOnceThing = = false then |
5 | print ( 'Script started.' ) |
6 | didOnceThing = true |
7 | end |
8 | -- Some other code |
9 | end |
Though it's better to use the first way.