If

From MiniScript Wiki
Revision as of 15:37, 17 February 2025 by Turtlezero (talk | contribs) (added link to orphaned "end if" page)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

if is the keyword that begins an if block. Use an if…then statement to specify some condition under which the following statements should be executed. Use "end if" to end the if-block. The basic syntax is:

if condition then
end if

When the condition is not true, MiniScript will jump directly to the end if statement.

if x == 42 then
   print "I have found the Ultimate Answer!"
end if

The whole set of lines, from if…then to end if, is known as an if block. Sometimes you want to do something else when the specified condition is not true. You can specify this with an else block before the end if.

if x == 42 then
   print "I have found the Ultimate Answer!"
else
   print "I am still searching."
end if

Finally, you can check for additional conditions by adding else-if blocks as needed. Here's a slightly more practical example that converts a number to words.

if apples == 0 then
   print "You have no apples."
else if apples == 1 then
   print "You have one apple."
else if apples > 10 then
   print "You have a lot of apples!"
else
   print "You have " + apples + " apples."
end if

In this case, the first condition that matches will execute its block of lines. If none of the conditions match, then the else block will run instead.

Note that for all these forms, the if, else if, else, and end if statements must each be on its own line. However, there is also a "short form" if statement that allows you to write an if or if/else on a single line, provided you have only a single statement for the then block, and a single statement for the else block (if you have an else block at all). A shortform if looks like this:

if x == null then x = 1

…while a short-form if/else looks like this:

if x >= 0 then print "positive" else print "negative"

Notice that end if is not used with a short-form if or if/else. Moreover, there is no way to put more than one statement into the then or else block. If you need more than one statement, then use the standard multi-line form.