|
<< Click To Display Table Of Contents >> You Are Here: MADRIX Script (Introduction) > Basics > Statements > 'If' And 'Else If' Statements |
if(condition)
statement
else
statement
The first statement is executed if the given condition is true or unequal to 0. Otherwise the second statement, stated after else, is executed.
Statement may include a single statement or a block of statements and the else-part is optional. Here are some examples for the if-statement:
if(x % 2 == 0)
{
col.r = 0;
SetPixel(col, x, y);
}
else
{
col.r = 255;
SetPixel(col, x, y);
}
if(testPixel(x, y) != 0)
{
SetPixel(WHITE, x, y);
}
if(x + 2 > y)
y++;
It is important to consider that an else always refers to the last if-statement. However, blocks may be used to make the intention clear. To give you a demonstration, please consider the following example. It may be interpreted wrong since i will be incremented if the j > i-condition fails and not if the i > 3-condition fails, as is implied by the given else.
if(i > 3)
if(j > i)
j = i;
else
i++;
To let the compiler create the correct code, use blocks:
if(i > 3)
{
if(j > i)
j = i;
}
else
i++;
Else if is an additional structure to implement decisions. It may be used like this:
if(condition)
statement
else if (condition)
statement
Like described above, else is always followed by a statement. And if is such a statement. Then, it is logical that an else can be directly followed by an if. The else if structure is very useful to make code with a lot of decisions more readable. It enables you to check for different conditions, which shall only be checked if the previous condition was passed successfully. Here is an example which selects another color for different days. Simply copy and paste it in the function RenderEffect.
date t = GetDate();
color c;
if(t.day < 11)
c.r = 255;
else if(t.day <= 21)
c.g = 255;
else if(t.day <= 31)
c.b = 255;
else
c = WHITE;
Clear(c);
The following example for the MAS Script Effect renders a blinking cross onto the matrix. Instead of using random colors, predefined colors will be used. During each call of RenderEffect, the color will be chosen.
color colCross = {0, 255, 255, 255};
int g_iCol;
void InitEffect()
{
g_iCol = 0;
SetAsync(true);
SetBpm(300);
}
void RenderEffect()
{
int x, y;
if(g_iCol == 0)
{
colCross.r = 255;
g_iCol = 1;
}
else if(g_iCol == 1)
{
colCross.r = 155;
g_iCol = 2;
}
else
{
colCross.r = 0;
g_iCol = 0;
}
for(int x = 0; x < GetMatrixWidth(); x++)
for(int y = 0; y < GetMatrixHeight(); y++)
{
if(x == y)
SetPixel(colCross, x, y);
else if(GetMatrixWidth() - x - 1 == y)
SetPixel(colCross, x, y);
else
SetPixel(BLACK, x, y);
}//for[each line]
}
| MADRIX 3.23. |
| [Ctrl & +/-] = Zoom In/Out | [Ctrl & 0] = 100% |
|
Previous Next
|
|
Enable Automatic Translation | Activer La Traduction Automatique | 启用自动翻译 |