Simulate goto continue in Lua (simulate C++ C#'s continue
introduce
You should have seen continue in C# or C++. Its usage is actually to interrupt the current loop and directly enter the next loop. The code is as follows:
for (int i = 0; i < 10; i++)
{
if (i == 2) continue;
Debug.Log(i);
}
The above prints as follows:
0
1
3
4
5
6
7
8
9
Well, there is actually no continue syntax in Lua, but there is goto continue in Lua, which can be executed to a certain line to continue execution, which is equivalent to specifying the order of execution and the statements to be executed. In addition to this method, you can also use while to simulate it in Lua. The following of the continue statement is the specific implementation method of these two methods.
specific method
goto continue
This can specify the execution order and execution statements of Lua code. It has one more function than continue, which can jump to a certain line for execution. Let’s look at the code below to see how to implement it.
for i = 1, 10 do
if i == 2 then
--这里goto 直接跳到for 的结尾 不会触发print(i)
goto continue
end
logError(i)
::continue::
end
Print as follows:
1
3
4
5
6
7
8
9
10
while simulates continue method
while neutralbreakbreakwhile Method
breakalso breakforcirculation
for i = 1, 10 do
while true do
if(i == 2) then break end
logError(i)
break
end
end
Print as follows:
1
3
4
5
6
7
8
9
10
Summarize
The above two methods are the two that I commonly use. Of course, if you want to make the judgment in for, while or repeat until, it is also possible. There are many ways to achieve it. If there is a better method, you can leave a message. , thank you all for your support, I hope to give you some free care and attention, thank you.