unknown_document

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


Lua Variables
A variable is a named container than stores a value. Defining a variable follows the pattern: [ name ] = [ value ] -- globally scoped local [ name ] = [ value ] -- locally-scoped variable where name is the name of the variable, and value is the value assigned to that variable. Note It can sometimes be helpful to additionally think of this a bit more technically: Each value is stored somewhere in a small piece of computer memory, and the name is used to reference the value that is stored there. The second example above begins with the local keyword, which declares that this variable is defined in the "local" scope . We will learn more about scope in the next section, but for now just know that it is good practice to precede variable declarations with the local keyword, so that is what we will do in our examples. Some examples of variable definitions are: local name = "John" local age = 23 local height = 182.3 local x -- nil These examples show how to define variables that contains strings , integers , and floats , respectively. Note in each case that the name of the variable is on the left, while the value assigned to it is on the right. In the last example the variable x was defined, but no value was assigned to it. In this case x is assigned the default value nil , which we will learn about shortly. Lua does not require that the variable type be declared, the type is inferred from the value assigned to the variable. After a variable has been created, the name of the variable represents the value assigned to it in subsequent operations. For example, one can perform arithmetic on variables: print ( age + 3 ) -- 26 Reassignment After a variable has been created, new values can be assigned to that variable: local x = 123 print ( x ) -- 123 x = 456 print ( x ) -- 456 Note that because we had already declared the x variable in the local scope, although the local keyword in not used when we assign 456 to that variable it remains in the local scope. Multiple-Assignment Lua also supports "multiple" assignment, meaning that multiple values can be assigned on the same line. The example above could be re-written: local name , age , height = "John" , 23 , 182.3 When multiple-assignment is used, each of the values on the right side of the = are evaluated, then they are assigned to the variables on the left side in-order. There are a few cases to be aware of: More Variables Than Values When there are more variables than there are values, missing values are treated as nil . local name , age , height = "John" , 23 print ( name ) -- John print ( age ) -- 23 print ( height ) -- nil Fewer Variables Than Values When there are fewer variables than there are values, only the left-most values are assigned: local name , age , height = "John" , 23 , 182.3 , "blue" , "brown" print ( name ) -- John print ( age ) -- 23 print ( height ) -- 182.3 -- "blue" and "brown" were ignored When to use Multiple-Assignment In most cases, multiple assignment makes code more difficult to read, and more difficult to comment , so it should generally be avoided. However, there is one case where it can be helpful: Suppose we want to swap values assigned to two variables: local x0 = 3 local x1 = 2 if x0 > x1 then x0 , x1 = x1 , x0 -- swap values assigned to variables end print ( x0 ) -- 2 print ( x1 ) -- 3 This is one of the few times where it makes sense to use multiple-assignment directly. However, as we will see in coming chapters, multiple assignment is very common when returning values from functions , so it is important to understand the basic mechanics of how it works.
Lua's Reserved Words
Lua defines a number of reserved words , which are words that have special meaning to Lua and therefore cannot be used as identifiers such as variable or function names. It is an error to use any of the following: and break do else elseif end false for function if in local nil not or repeat return then true until while
Variable Scope in Lua
We learned in the previous section that variables consist of both a name and a value , and that after a variable has been declared, it is possible to "re-assign" values to the name . The important detail here is that each variable requires a unique name . Let's now take a look at an important aspect of variables, scope . Global Scope In the early days of programming, all variables were what we now call global variables , or variables that have (or exist in the) "global scope" . The global scope can be thought of as a single bucket of uniquely-named variables, that are accessible from anywhere. Programmers quickly discovered that this created a variety of problems, ranging from simple annoyances such as the need to define (and keep track of) many similarly-named variables to avoid "name collisions", to accidentally-created and difficult-to-find bugs related to different parts of the code operating on the same variables. Although global variables are generally discouraged today, they are supported by most languages, including Lua. In fact, variables created in Lua are global by default. While global variables might seem convenient, they lead to code that can be difficult to understand, debug, and maintain, which led the concept of scope and local scopes. Local Scope While we have described the global scope as a big bucket of variables, local variables can be thought of as smaller buckets of variables that are placed into that big global bucket. Local variables have their scope limited by the "location" in which they are defined: local variables defined in a file have their scope limited to that file. This allows the same variable names to be used in different files without risk of collision. local variables defined within a function are local to that function, which allows functions to be easily used across different files. Within a file or function, local variables defined within a block (such as a control structure are local to that block. Let's take a look at a few examples: local x = "file scope" print ( x ) -- file scope -- start an "if-then" block if true then -- this block has its own scope local x = "block scope" print ( x ) -- block scope end -- back in the file scope print ( x ) -- file scope local fn = function () -- this function has its own scope local x = "function scope" return x end -- although we are back in the file scope -- this prints the function's return value print ( fn ()) -- function scope -- this prints x from the file scope print ( x ) -- file scope
Lua Comments
Before we get into Lua itself, let's first talk about comments . Comments are text annotations in code that are ignored when the script is executed, but help people reading the code understand it. We use comments throughout our examples to explain what is happening a different points in the code, as well as to show the values of variables and other important information. Because comments are used to help document this behavior, let's start with explain what they are and how to read them. There are two types of comments in Lua: Line Comments Line comments are delimited with two dashes, as in -- . When Lua encounters this delimiter, it ignores any content to the right of the delimiter. For example: -- This entire line is a comment print ( 123 ) --- The print statement executes, then this is ignored We will often use comments in examples to either: Explain the operations performed on a line, or Show the output or value of a variable on a line Block Comments Block comments are similar to line comments, except they apply to entire blocks of code. When there is an entire block of code to comment out, there are two choices. First, every line in the block case be commented with a line comment: -- local a = 123 -- -- print(a) -- -- a = 456 -- -- print(a) which is perfectly valid, though often less convenient than using a block comment: --[[ local a = 123 print(a) a = 456 print(a) ]] In the second example, the block comment starts with the -- , which is followed by double-square brackets [[ which define the start of the block comment. Everything between the start of the block and the end of the block, defined by the closing double-square brackets ]] , is considered a comment and ignored.
Lua's Userdata Type
Userdata is a type in Lua that basically represents a "black box" of data that is used in the code, but can't be printed or otherwise inspected. Using userdata is an advanced topic that generally involves integrating C code with Lua. In most cases anyone other than advanced users who are integrating Lua and C will only see userdata when debugging a script and printing values, and the only reason we bring it up is so that reader have some idea what they are looking at when they see it.
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 Table Type
Lua implements a single data structure type, which is implemented as a general-purpose collection that encompasses functionality that is usually implemented by several different data structures in other programming languages. This makes tables powerful, but can also make it a bit challenging to work with, and can lead to surprising results if one is not careful. For example, while tables can act as both lists and mappings , most table functions generally make an assumption about how the table is being used. When a table function is used in the wrong context it won't generate an error, it will just return an unexpected result. We will learn much more about tables in the Tables chapter.
Lua Types
Lua is a dynamically-typed language, similar to Python . This means that there are no type definitions, and no need to declare the types of variables. Instead, the type is inferred from the value. This can be an advantage or a disadvantage, depending upon the context, but it is part of what allows Lua to have such a simple grammar. Let's now take a look at Lua's types:
Lua's nil Type
Whereas most types convey a value, many programming languages include a type that specifies that there is no value. This concept varies slightly between languages, but is conveyed by None in python and NULL in C and SQL , in Lua this value is nil . We saw earlier that when a variable is defined without a value it is assigned the value of nil , which provides a good example of what nil is - it represents the condition when there is no value. This might sound a bit abstract, but this is one of those topics that is difficult to comprehend by simply reading about it, but will become clear after "seeing it in action" in the coming sections.
Lua's Boolean Type
Boolean values represent the logical values of true and false. Some languages represent these values as the integers 1 and 0, respectively, while others represent them with the words True and False . In Lua, these values are represented by (the lowercase) true and false . Truthiness & Falsiness In addition to the strictly boolean values, Lua also supports coercing non- boolean values into their boolean equivalents so that they can be used in boolean contexts. This is such a common occurrence that it often makes sense to refer to non- boolean values as their boolean -equivalents; values that are coerced to true are considered truthy , while those that are coerced to false are regarded as falsy . Value coercion in Lua is simple: Lua regards nil to be falsy , and all other values are truthy . This can lead to some surprising results result for those that are familiar with coercion in other languages, where 0 , empty strings "" , and empty collections {} are usually regarded as being falsy .