colobot-data/help/D/cbot/if.txt

41 lines
1.7 KiB
Plaintext

\b;Instructions \c;if\n; and \c;else\n;
With the instruction \c;if() {}\n; you can execute a set of instructions only if a certain condition is true. Write the condition in brackets \c;()\n;, and the instructions in braces \c;{}\n;.
\b;Basic use
Here is a concrete example: The bot will shoot only if the target is closer than 40 meters:
\c;
\s; item = \l;radar\u cbot\radar;(AlienAnt);
\s; if (\l;distance\u cbot\dist;(position, item.position) < 40)
\s; {
\s; fire(1);
\s; }
\n;
You can also test if an object exists at all. If the instruction \c;\l;radar\u cbot\radar;();\n; does not find the requested object, it returns the value \c;null\n;. So you can test if an object does not exists with the condition \c;(item == null)\n;, or test if it exists with \c;(item != null)\n;. Two equal signs \c;==\n; test equality, an exclamation mark followed by an equal sign \c;!=\n; test inequality. Here is a test that will go to rechage the \l;power cell\u object\power; only if there is a \l;power station\u object\station;:
\c;
\s; item = \l;radar\u cbot\radar;(PowerStation);
\s; if (item != null)
\s; {
\s; \l;goto\u cbot\goto;(item.position);
\s; \l;wait\u cbot\wait;(5);
\s; }
\n;
\b;For specialists
Syntax:
\s;\c;if ( condition )
\s;{
\s; \n;Instructions A ...\c;
\s;}
\s;else
\s;{
\s; \n;Instructions B ...\c;
\s;}
\n;
With this conditional structure you can execute a \l;bloc\u cbot\bloc; A or a \l;bloc\u cbot\bloc; B depending on a \l;condition\u cbot\cond;. If the condition is true, bloc A is executed. If the condition is false, bloc B is executed.
Part \c;else { }\n; is not compulsory.
\t;Attention
Do not put a \l;semicolon\u cbot\term; at the end of the line \c;if ( )\n;.
\t;See also
\l;Programming\u cbot;, \l;types\u cbot\type; and \l;categories\u cbot\category;.