YouTip LogoYouTip

Lua Variables

# Lua Variables Variables need to be declared in the code before use, i.e., creating the variable. Before the compiler executes the code, it needs to know how to allocate storage space for statement variables to store their values. Lua variables have three types: global variables, local variables, and fields in a table. All variables in Lua are global variables, even within statement blocks or functions, unless explicitly declared as local using `local`. The scope of a local variable starts from the declaration position to the end of the statement block it is in. The default value for all variables is `nil`. ## Example -- test.lua file script a =5-- global variable local b =5-- local variable function joke() c =5-- global variable local d =6-- local variable end joke() print(c,d)--> 5 nil do local a =6-- local variable b =6-- reassign to local variable print(a,b);--> 6 6 end print(a,b)--> 5 6 The output of the above example is: $ lua test.lua 5nil6656 * * * ## Assignment Statement Assignment is the most fundamental way to change the value of a variable and the fields of a table. a = "hello" .. "world" t.n = t.n + 1 Lua can assign values to multiple variables simultaneously. The elements in the variable list and value list are separated by commas. The values on the right side of the assignment statement are assigned to the variables on the left in order. a, b = 10, 2*x a=10; b=2*x When encountering an assignment statement, Lua first evaluates all values on the right side before performing the assignment. Therefore, we can swap variable values like this: x, y = y, x -- swap 'x' for 'y' a, a = a, a -- swap 'a' for 'a' When the number of variables and values does not match, Lua adopts the following strategy based on the number of variables: a. Number of variables > Number of values: Fill with `nil` according to the number of variables. b. Number of variables 0 1 nil a, b = a+1, b+1, b+2-- value of b+2 is ignored print(a,b)--> 1 2 a, b, c =0 print(a,b,c)--> 0 nil nil The last example above is a common error situation. Note: If you want to assign values to multiple variables, you must assign a value to each variable in sequence. a, b, c = 0, 0, 0print(a,b,c) --> 0 0 0 Multiple value assignments are often used to swap variables or assign function return values to variables: a, b = f() `f()` returns two values, the first is assigned to `a`, the second to `b`. You should use local variables as much as possible, which has two benefits: * 1. Avoid naming conflicts. * 2. Accessing local variables is faster than global variables. * * * ## Indexing Indexing of a table uses square brackets `[]`. Lua also provides the `.` operator. t t.i -- a shorthand when the index is a string type gettable_event(t,i) -- indexing access is essentially a function call similar to this ## Example > site ={} > site="www..com" >print(site) www..com >print(site.key) www..com
← Met Document GetelementsbyclasMet Html Focus β†’