unknown_document

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


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 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 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 .
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 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 .
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.
Lua's Math Library
Lua's math library contains a collection of functions that are basically a subset of C 's math library . The math library is always available, and its functions can be accessed by name as shown in the following example: print ( math.abs ( - 123 )) -- 123 The math library contains the following functions: math.abs (x) Returns the absolute value of x math.acos (x) Returns the arc-cosine of x , in radians. math.asin (x) Returns the arc-sine of x , in radians. math.atan (x) Returns the arc-tangent of x , in radians. math.atan2 (x, y) Returns the arc-tangent of y/x, in radians, based on the signs of both values to determine the correct quadrant. math.ceil (x) Returns the smallest integer value greater than or equal to x . math.cos (x) Returns the cosine of x , where x is specified in radians. math.deg (x) Convert x , specified in radians , to degrees math.exp (x) Returns the value of e raised to the xth power. math.floor (x) Returns the largest integer value less than or equal to x . math.fmod (x, y) Return a value equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y) . math.frexp (x) Returns values (m, e) such that m * 2^e == x . math.ldexp (x, y) Return x * (2**y) , essentially the inverse of function math.frexp . math.log (x) Return the natural log of x math.log10 (x) Return the base-10 logarithm of x math.max (x, ...) Returns the maximum value among its arguments. math.min (x, ...) Returns the minimum value among its arguments. math.modf (x) Spits real number x into it's integer and fractional parts. math.pi The constant pi , approximately equal to 3.14159. math.pow (x, y) Returns x raised to the power of y . math.rad (x) Convert x , specified in degrees , to radians math.sin (x) Returns the sine of x , where x is specified in radians. math.sqrt (x) Returns the square root of x math.tan (x) Returns the tangent of x , where x is specified in radians. math.random () Return a uniformly-distributed pseudo-random number between 0 (inclusive) and 1 math.random (x) Return a uniformly-distributed pseudo-random number between 1 (inclusive) and x math.random (x, y) Return a uniformly-distributed , pseudo-random number between x (inclusive) and y (inclusive). math.randomseed (x) Sets x as the "random seed" for the pseudo-random generator
If Then Control Flow in Lua
Conditional statements control program flow by evaluating an expression then proceeding to one or more different "paths" depending on the result. Lua implements conditional statements with the if-then statement, which supports several variations. If-Then The most simple conditional statement contains a single boolean condition that directs program flow to a branch if that condition evaluates to true . if-then statements in Lua follow the pattern: if [ boolean expression ] then -- execute when boolean expression is true end The following is a simple example of the if-then statement: local x = 2 local y = 3 local result if x > y then result = x + y end print ( result ) -- nil It this example the values of the x and y variables are compared and, because x is not greater than y , the conditional branch is not executed, and result is not assigned a value. If-Then-Else In the previous example we created a block of code that is only executed if a specific condition exists. Sometimes we need a bit more control over program flow, and want program flow to take one of two paths, depending on the conditional. For this, Lua has the if-then-else statement, which follows the pattern: if [ boolean expression ] then -- execute when boolean expression is true else -- execute when boolean expression is false end Let's look at a simple example: local x = 2 local y = 3 local result if x > y then result = x + y else result = 5 end print ( result ) -- 5 If-Then-Elseif-Else if [ boolean expression # 1 ] then -- execute when boolean expression #1 is true elseif [ boolean expression # 2 ] then -- execute when boolean expression #2 is true elseif [ boolean expression # n ] then -- execute when boolean expression #n is true else -- optional -- execute when all boolean expressions are false end The expression can include any number of elseif clauses, allowing program flow to take any number of alternate paths. Note that the else clause is optional. When included this branch will execute only of all other conditionals are false . Let's extend our example to include a second conditional statement: local x = 2 local y = 3 local result if x > y then result = x + y elseif x < y then result = 10 else result = 5 end print ( result ) -- 10 Now that we have seen how if-then statements work, the next section will take a quick look at using the and and or to perform simple conditional statements.
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.