## Assignment and Expressions

## Contents

In Lua, like in most programming languages, you can assign a value to a variable. In Lua, the **=** operator indicates an assignment:

`myvar = 98.6`

Here, the value **98.6** is assigned to the variable **myvar**.

In Lua, any value can be assigned to any variable, as variables are not restricted to containing a specific type of value. For example, all of the following are legal:

myvar = 98.6 myvar = nil myvar = "Dr. John Smith" myvar = {98.6, "Dr. John Smith", "Radiology"} myvar = true

You can also assign to multiple variables at once:

`myvar = myvar2 = 98.6`

Here, both **myvar** and **myvar2** are assigned the value **98.6**. You can also assign multiple values to multiple variables:

`myvar, myvar2 = 98.6, "Dr. John Smith"`

This assigns **98.6** to **myvar** and **“Dr. John Smith”** to **myvar2**. You can use this to swap the values of two variables. For example, the following statement assigns the value of **myvar** to **myvar2** and the (old) value of **myvar2** to **myvar**:

`myvar, myvar2 = myvar2, myvar`

In Lua, you can also use **expressions** to perform arithmetic and compare one value to another. The following tables list the operations that can be performed in Lua expressions.

**Arithmetic operations**

Operation | Description | Example |
---|---|---|

+ |
Addition | myvar2 = myvar + 1 |

– |
Subtraction | myvar2 = myvar – 1 |

– |
Negation | myvar2 = -myvar |

* |
Multiplication | myvar2 = myvar * 10 |

/ |
Division | myvar2 = myvar / 10 |

% |
Modulo (remainder from division) | myvar2 = 47 % 10(this assigns 7 to myvar2) |

^ |
Exponentiation | myvar2 = 2^5(this is 2 to the power 5, or 32) |

**Comparison operations**

Operation | Description | Example |
---|---|---|

== |
Equal to | myvar1 == myvar2(this is true if myvar1 is equal to myvar2) |

~= |
Not equal to | myvar1 ~= myvar2(this is false if myvar1 is equal to myvar2) |

< |
Less than | myvar1 < myvar2(this is true if myvar1 is less than myvar2) |

> |
Greater than | myvar1 > myvar2(this is true if myvar1 is greater than myvar2) |

<= |
Less than or equal to | myvar1 <= myvar2(this is true if myvar1 is less than or equal to myvar2) |

>= |
Greater than or equal to | myvar1 >= myvar2(this is true if myvar1 is greater than or equal to myvar2) |

**Logical operations**

Operation | Description | Example |
---|---|---|

not |
Logical not | !myvar1(This is true if myvar1 contains nil or false, and is false otherwise) |

and |
Logical and | myvar1 and myvar2(This is true if both myvar1 and myvar2 are true) |

or |
Logical or | myvar1 or myvar2(This is true if either of myvar1 or myvar2 is true) |

For more about * assignment *see: assignments in the online programming book, the Lua Tutorial wiki, or search for “assignment” in the online reference manual

For more about * expressions *see: expressions in the online programming book, the online reference manual or the Lua Tutorial wiki.