while

X3 programming language, the "while" keyword is used to create a loop that continues to execute a block of code as long as a specified condition is true. Here's how you would use the "while" keyword in your X3 language:

Basic Usage:

var count = 0

# Using 'while' loop to execute code while a condition is true
while count < 5 then
    show(count)
    count = count + 1
end

Explanation:

  • In this example, the "while" loop continues to execute the code block as long as the condition count < 5 is true.

  • The loop variable count starts at 0 and increments by 1 in each iteration until it reaches 5.

Infinite Loop:

# Using 'while' loop to create an infinite loop
var i = 0
while true then
    show(i)
    i = i + 1
    if i >= 5 then
        break
    end
end

Explanation:

  • Here, the "while" loop condition is always true, creating an infinite loop.

  • Inside the loop, i is incremented by 1 in each iteration, and the loop stops when i reaches 5 using the "break" keyword.

Using with Input:

# Using 'while' loop with user input
var userInput = 0
while userInput != 5 then
    userInput = input("Enter a number (5 to exit): ")
    show("You entered: {userInput}")
end

Explanation:

  • This example demonstrates using a "while" loop with user input.

  • The loop continues to prompt the user to enter a number until they enter 5, at which point the loop exits.

Nested Loops:

# Nested 'while' loops
var i = 0
while i < 3 then
    var j = 0
    while j < 2 then
        show("({i}, {j})")
        j = j + 1
    end
    i = i + 1
end

Explanation:

  • In this example, a nested "while" loop is used to create a grid-like structure.

  • The outer loop iterates over the values of i, and for each iteration of i, the inner loop iterates over the values of j.

By incorporating the "while" keyword in your X3 language, you provide users with the ability to execute code repeatedly based on a specified condition, allowing for flexible and dynamic looping behavior in their programs.

Last updated