User:OrenBochman/Lua for beginners

From Meta, a Wikimedia project coordination wiki


Two equals operators[edit]

The two most important oprators are:

  • the equality operator ==
  • the assignment operator =

The assignment operator is used to store a value inside a variable, or to change the stored value.

a=b

it can also be used for multiple asignment

a, b = c, d
a, b = foo()


The equality operator is used to test the value of a typicaly in the context of some program logic. It does not change the value of the variables. The expression containing an equality operator is evaluated by Lua and is used to returns a TRUE or FALSE value for the test.

Conditionals[edit]

Conditional statements alow execution to branch at a certain point in the program. The conditionals show below have a certain pattern - first an expression is evaluated in this case using an equality operator. This is then followed by an assignment.

The most basic Lua conditional logic is an if statement:

if colour == 'black' then
    cssColour = '#000'
end
return p

Lua also support if/else type conditional logic which allow you to to add to the if statement an option covering the else branch which

if colour == 'black' then
    cssColour = '#000'
else
    cssColour = colour
end
return p

It is also possible to represent more complex conditional logic using nested if statements. THese have a different syntax which look like:

if colour == 'black' then
    cssColour = '#000'
    elseif colour == 'white' --This is the nested condition
        cssColour = '#fff'
else
    cssColour = colour
end
return p


More operators[edit]

Operators are the symbols used for mathematical and logical operations in Lua expressions.

  • logical operators in expression return either True or False
    • and - litraly if both A and B are true
    • or - litraly if one of A or B is true
    • not - logical negation
    • == - equals
    • ~= - not equals
    • > - greater than
    • < - less than
    • >= - greater than or equals to
    • <= - less than or equals to
  • mathematical operators in expressions return a number
    • + - adds two numbers
    • - - subtract two numbers
    • * - multiply two numbers
    • / - devide two numbers
    • % - find the reminder of deviding a number by another number
    • ^ - raise a number to the power of another number