unknown_document

We couldn't find that page... Were you looking for one of these?


Lua's Logic Operators
Boolean Values In order to provide a baseline for the examples below, let's start with a quick look at the boolean values of true and false : print ( true ) -- true print ( false ) -- false As we discussed earlier , when a non-boolean value is evaluated in a boolean context that value is coerced to its boolean equivalent. It is common to refer to values that are coerced to true as being truthy , while those that are coerced to false are falsy . not The first and most simple Boolean operator is the not operator, which simply inverts the truthiness of the value it operates on and returns a boolean value: print ( not true ) -- false print ( not false ) -- true print ( not nil ) -- true -- careful! print ( not 0 ) -- false print ( not "" ) -- false print ( not {}) -- false We included a few examples of type coercion to show how it works. If you are familiar with boolean coercion in other programming languages, be careful when evaluating 0 , "" , and {} , as they may provide unexpected results. and The next operator is the and operator, which evaluates to truthy when both inputs are truthy , and otherwise evaluates to falsy : print ( true and true ) -- true print ( true and false ) -- false print ( false and true ) -- false print ( false and false ) -- false The previous examples shows that the and operator evaluates boolean values in the expected way. The following examples demonstrate how it evaluates non-boolean values: print ( false and nil ) -- false print ( true and nil ) -- nil print ( true and 0 and nil ) -- nil print ( true and nil and 0 ) -- nil Note that the and operator returns either the first non- truthy value, or the last truthy value if all values are truthy . This behavior allows the and operator to both provide logical operators and provide a simple control structure . or Complementary to the and operator is the or operator, which evaluates to truthy if either of the inputs are truthy , and evaluates to falsy otherwise. print ( true or true ) -- true print ( true or false ) -- true print ( false or true ) -- true print ( false or false ) -- false As with the and operator, the or operator performs logical operations as expected, and also operates on non-boolean values: print ( nil or false ) -- false print ( nil or true ) -- true print ( nil or 0 or true ) -- 0 print ( 0 or nil or true ) -- 0 The or operator returns either the first truthy value it encounters, or the last falsy value if all values are falsy . Like the and operator, this allows the or operator to both provide logical operators and provide a simple control structure that is often very convenient. Compound Boolean operators can be chained together to create "compound" operations: print ( true and not true ) -- false print ( true or not true ) -- true How this works will become clean in the next section, where we discuss precedence .
Lua's Relational Operators
Relational Lua's relational operators are more or less the same as in most other languages: local x = 2 local y = 3 print ( x > y ) -- false print ( x < y ) -- true print ( x >= y ) -- false print ( x <= y ) -- true print ( x <= x ) -- true print ( x >= x ) -- true The relational operators allow one to determine when values are greater-than or less-than others, and include a variant that also allows the variables to be equal. Equality Lua's equality operator uses two equal signs == , which is differentiated from the variable assignment operator = which uses a single equal sign: local x = 2 local y = 3 print ( x == y ) -- false print ( x == x ) -- true This operator returns true when the two values are equal, otherwise it returns false . Inequality Like equality , it can often be useful to know when two values are not equal. Lua implements this using the ~= operator: local x = 2 local y = 3 print ( x ~= y ) -- true print ( x ~= x ) -- false This operator returns false when the two values are equal, otherwise it returns true .
Lua's Length Operator
Lua includes a length operator # which (in theory) returns the number of items contained in the value to which it is applied. However, it is frankly a bit wonky and can give unexpected results if used outside of a fairly narrow range of applications. Part of the wonkiness is that it behaves differently depending on the type it is acting upon. For this reason, we look at how it behavior with each of the following types: List-like Tables Map-like Tables Set-like Tables Strings
Lua's Arithmetic Operators
Basics Let's first take a look at the basics, addition , subtraction , multiplication , and division . These work as one would expect: local x = 2 local y = 3 print ( x + y ) -- 5 print ( x - y ) -- -1 print ( x * y ) -- 6 print ( x / y ) -- 0.66666666666667 Negation Whereas almost all languages allow a value to be negated by multiplying it by -1 to negative it, Lua additionally allows a value to be negated by simply prefixing it with - . local x = 2 local y = 3 print ( - x ) -- -2 print ( - y ) -- -3 print ( x + - y ) -- -1 Note that negation occurs independently of other operators, as shown in the last case. We will learn more about this in a moment when we discuss precedence . Exponentiation Lua supports exponentiation with the ^ operator: local x = 2 local y = 3 print ( x ^ y ) -- 8.0 print ( y ^ - x ) -- 0.11111111111111 Modulus Like many programming languages modular arithmetic in Lua uses the % operator. While the topic of modular arithmetic is well outside the scope of learning about Lua, this is a useful but often misunderstood function, so let's give it a quick review. To calculate a % b, one first finds the largest integer k such that multiplying k by b is less than a , then the result is the difference or remainder, a - kb . local x = 2 local y = 3 print ( x % y ) -- 2 print ( y % x ) -- 1 In the first example y is greater than x , so the remainder is simply x . In the second example the largest integer k is 1 , so that the remainder is 3-2=1 . Bitwise Lua also supports the basic bitwise operations. While bitwise operations are very important in computing, they are used in a fairly narrow range of applications so we won't spend too much time on them other than to show which operations are supported and a simple example of how they work: local x = 2 local y = 3 print ( x & y ) -- 2 print ( x | y ) -- 3 print ( x ~ y ) -- 1 You can learn more about bitwise operations here .
Lua's Concatenation Operator
Concatenation refers to the common operation of joining of two strings . In Lua, when two strings are concatenated the result is a third string that contains the characters of the first string followed by the characters contained in the second string: local x = "left side" local y = "right side" print ( x .. y ) -- left sideright side -- separating strings with a literal " " print ( x .. " " .. y ) -- left side right side Note that the concatenation is literal: no space is added between two concatenated strings. When concatenating sentences be sure to include a literal space between the two strings. Concatenation also works with numbers , by first coercing each value to its string-equivalent then concatenating those values: local x = 2 local y = 3 print ( x .. y ) -- 23 Note that concatenation won't work with other value fundamentals, such as booleans or nil .
Operator Precedence in Lua
As we all learned in algebra, it is not only important to understand how operators work, but also understand the order in which operators are applied. The order in which operators are applied is governed by their precedence and their association . Lua operators have the following precedence, ordered from highest to lowest priority, and association: Group Operators Association Exponentiation ^ Right Unary Operators not # - ~ Left Arithmetic * / % Left Arithmetic + - Left Concatenation .. Right Bitwise & Left Bitwise ~ Left Bitwise | Left Relational < > <= >= ~= == Left Logical and Left Logical or Left As with algebra, parentheses can be used to override the order of precedence of an expression.
Lua
Lua is a lightweight, cross-platform, high-level programming language that has become increasingly-popular as an embedded scripting language. Lua is often praised as a clean, simple, easy to learn scripting language that is applicable to a wide range of tasks. Today Lua can be found in a wide range of applications ranging from wezterm to xplr and neovim . Let's get started.
Control Structures
Lua implements several of the basic control structures that might be expected in a programming language. Here is a quick summary of the available options, then we will get into the details in the coming sections: Control Type Structure Conditional If-Then Condition-controlled Loop While Condition-controlled Loop Repeat Count-controlled Loop Numeric For Collection-controlled Loop Generic For
Lua's Basic Functions
Lua includes a variety of basic functions that are useful when working with Lua. These functions are always available, and can be accessed by name as shown in the following example: print ( type ( 123 )) -- number The most-commonly used functions are: assert(cond) Raise an error if cond is not truthy with message "assertion failed!" assert(cond, msg) Raise an error if cond is not truthy with message msg dofile() Reads input from stdin and executes it, returning all values. dofile(path) Executes the lua file located at path , returning all values.. getmetatable (o) Return the metatable from object o , of nil if o does not have a metatable. ipairs (list) Returns (index, value) pairs from list . See iterating lists for more information. pairs (map) Returns (key, value) pairs from map . See iterating maps for more information. pcall (f, ) calls function f with optional arguments ... in "protected mode". returns true , followed by an return values when no error occurs, otherwise returns false followed by an error message. print () Prints arguments ... to stdout , passing non- string values to tostring . require (name) Loads module name and returns it. setmetatable (table) Removes table 's metatable (i.e., sets its metatable to nil ) and returns table . setmetatable (table, t) Sets table 's metatable to t and returns table . tonumber (arg) Converts arg to a number and returns it. arg is expected to be a number or a string that represents a number . Otherwise, returns nil . tonumber (arg, base) Converts arg to a number with base base and returns it. arg is expected to be a number or a string that represents a number . Otherwise, returns nil . tostring (arg) Converts arg to a string and returns it. type (arg) Returns a string specifying the type of arg . unpack (list) Returns the elements from list . unpack (list, i) Returns elements from index i through the end of list . unpack (list, i, j) Returns elements from indices i through j of list xpcall (f, callback) calls function f in "protected mode". returns true , followed by an return values when no error occurs, otherwise returns false followed by the return value(s) of callback(error) , where error is the original error.
Lua's Table Library
The table library contains a collection of functions that operate on tables . In most cases these functions expect a specified "kind" of table , most often a list . Whenever possible we try to be explicit about referencing which "kind" of table the function expects. The table library is always available, and its functions can be accessed by name as shown in the following example: local list = { "d" , "c" , "a" , "b" , } table.sort ( list ) print ( list [ 1 ]) -- a print ( list [ 2 ]) -- b print ( list [ 3 ]) -- c print ( list [ 4 ]) -- d The table library contains the following functions: table.concat (list) Returns a string containing the concatenation of each element in list . table.concat (list, sep) Returns a string containing the concatenation of each element in list separated by sep . table.concat (list, sep, i) Returns a string containing the concatenation of each element in list [1:] separated by sep . If i > #list returns an empty string . table.concat (list, sep, i, j) Returns a string containing the concatenation of each element in list [i:j] separated by sep . If i > j returns an empty string . table.insert (list, value) Appends an element to the end of the list , increasing its length by 1. table.insert (list, index, value) Inserts an element into the specified index. Existing elements at positions greater than or equal to index are each shifted to the next higher index, and the length of the list is increased by 1. table.remove (list) Removes the last element from the list and returns it, decreasing the length of the list by 1. table.remove (list, index) Removes the element at the specified index and returns it. Existing element at positions greater than index are each shifted to the next lower index, and the length of the list is decreased by 1. table.sort (table) Sorts list elements in in-place. By default elements are sorted ascending by value. The sort algorithm is "unstable", meaning that elements that evaluate equal may change positions each time table.sort is invoked. table.sort (table, comp) Sorts table elements in a given order, in order specified by comp . comp is a function that receives two elements as arguments, then returns true when the first appear in the list prior to the second and false otherwise.