KonsolScript:Tutorials:Conditional

From GPWiki
Jump to: navigation, search

Conditional

In programming, you can achieve artificial intelligence with the help of Conditionals. We provide a question answerable by yes or no which will be acted-upon by then do this or then do that.

Conditional Operators

In KonsolScript, we have EQ (EQual to), NE (Not Equal to), GT (Greater Than), GE (Greater than or Equal to), LT (Less Than), and LE (Less than or Equal to).

With these conditional operators, we can form a question in KonsolScript that means is 1 equal to 2?

1 EQ 2

If statement

The if statement is the "then do this" of conditionals.

//demonstrating if statement
function main() {
  if (1 EQ 2) {
    Konsol:Log("1 is equal to 2")
  }
}
//Outputs (nothing)...

The sample above won't output anything since 1 is not equal to 2.

Else statement

The else statement is the "then do that" of conditionals.

//demonstrating else statement
function main() {
  if (1 EQ 2) {
    Konsol:Log("1 is equal to 2")
  } else {
    Konsol:Log("1 is NOT equal to 2")
  }
}
//Outputs...
//1 is NOT equal to 2

The sample above would output "1 is NOT equal to 2" since 1, surely, is not equal to 2.

Else-If statement

The else if statement is where we try to make another questioning.

//demonstrating else-if statement
function main() {
  if (1 EQ 2) {
    Konsol:Log("1 is equal to 2")
  } else if (1 LT 2) {
    Konsol:Log("1 is less than 2")
  } else {
    Konsol:Log("1 is NOT equal to 2")
  }
}
//Outputs...
//1 is less than 2

The above sample will print "1 is less than 2" and not "1 is NOT equal to 2" because the second question was answered yes so the no part will not be executed.

Last Words

The else statement can never be written before if statement. The samples below will give you error.

//demonstrating wrong usage of if-else statement
  else {
    Konsol:Log("1 is NOT equal to 2")
  } if (1 EQ 2) {
    Konsol:Log("1 is equal to 2")
  }
//demonstrating wrong usage of if-else statement
  else if (1 LT 2) {
    Konsol:Log("1 is less than 2")
  } if (1 EQ 2) {
    Konsol:Log("1 is equal to 2")
  }

Also, if you're more used to using the conditional operators of C/C++, you can use the == (same with EQ), != (same with NE), > (same with GT), >= (same with GE), < (same with LT), and <= (same with LE). See the sample below.

//demonstrating else-if statement
function main() {
  if (1 == 2) {
    Konsol:Log("1 is equal to 2")
  } else if (1 < 2) {
    Konsol:Log("1 is less than 2")
  } else {
    Konsol:Log("1 is NOT equal to 2")
  }
}
//Outputs...
//1 is less than 2


~creek23~