Where there is a will, there is a way. Some times when you are programming in C# or python, you may think about is there a way to break out of a function block to it’s parent scope?
We learned that in C we could use goto to jump around the codes. That’s a great tool when you need to jump out of deep nested loops. But you can’t jump out of a function with this tricky tool. If you learned about POSIX C, the longjump can meet the need, though it’s intended to easier the complexity in error handling. Requirement like jumping out of a function is really rare when coding. We always can find out a solution. Such as try catch in C++ or C#.
Lua code fragment below, you can’t stop the code from going through all the numbers. The permutation is a system predefined function, and we cannot modify it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function permutation(check) n = 100000 while n > 0 do check(n) n = n - 7 end end permutation(function(n) if n % 1234 == 0 then print("break here: " .. n) return # Just want to print the first number it finds. end end) |
But Ruby can complete the task with Block like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def permutation n = 100000 while n > 0 yield n n = n - 7 end end permutation { |n| if n % 1234 == 0 puts "break here: " + n.to_s break end } |
The differences make the existence of things reasonable.