LDMud logo: an emblem with three snakes, on the left behind that emblem a cogwheel. In front of both is a sword.

LDMud

Home of LDMud

View the Project on GitHub ldmud/ldmud

Control Flow

LPC has the same control flow statements as C (and one addition foreach):

if
    if(expression)
{
// Evaluate this, when 'expression' yields a non-zero value.
}
else
{
// Evaluate this, when 'expression' yields zero.
}
while
    while(expression)
{
// Evaluate this repeatedly,
// as long 'expression' yields a non-zero value.
}
There's also the do-while loop where the loop body is at least executed once and the condition is evaluated first after the first loop.
    do
{
// Evaluate this repeatedly,
// as long 'expression' yields a non-zero value.
// But evaluate this at least once.
}
while(expression);
for
for loops contain three expressions and a loop body. The first expression is executed at the beginning of the loop. The second expression is evaluated each time before the loop body is executed. If this expression yields zero then the loop will end. The third expression is executed at the end of each loop.
    for(int i = 0; i < 10; i++)
{
// Evaluate this repeatedly, with i going from 0 to 9.
}
foreach
foreach iterates over a range, which can be an array, mapping, struct (iterating over each member variable), string (iterating over each character of the string), or an integer range.
    foreach(string elem: textarray)
{
printf("%s\n", elem);
}

foreach(string key, mixed val: somemapping)
{
printf("%s: %Q\n", key, val);
}

foreach(int nr: 10..100)
{
printf("%d\n", nr);
}
switch
switch executes code blocks depending on a value.
    switch(value)
{
case 0:
// Evaluate this, if value == 0.
break;

case 1:
// Evaluate this, if value == 1.
break;

default:
// Evaluate this, when no case label matched.
break;
}
When there is no break statement at the end of a case block then the following block is executed as well.
break
break exits the innermost while, for, foreach loop, or switch block.
continue
continue will continue the execution from the beginning of the innermost while, for, or foreach loop. In a for loop the third expression (loop end) and second expression (loop condition) are evaluated. If the loop condition yields zero, the loop ends. Similarly the loop condition of while is evaluated. In foreach loops the loop starts with the next value.
return
return exits the current function and optionally returns a value.
    int query_number()
{
return 42;
}