Lua Data Types
Lua is a dynamically typed language. Variables do not require type definitions; you only need to assign a value to a variable. Values can be stored in variables, passed as parameters, or returned as results.
There are 8 basic data types in Lua: nil, boolean, number, string, userdata, function, thread, and table.
| Data Type | Description |
| --- | --- |
| nil | This is the simplest type. Only the value nil belongs to this type, representing an invalid value (equivalent to false in conditional expressions). |
| boolean | Contains two values: false and true. |
| number | Represents double-precision floating-point numbers. |
| string | Strings are represented by a pair of double quotes or single quotes. |
| function | Functions written in C or Lua. |
| userdata | Represents any C data structure stored in a variable. |
| thread | Represents an independent line of execution, used for executing coroutines. |
| table | The table in Lua is actually an "associative array," where the array index can be a number, string, or table type. In Lua, tables are created using "constructor expressions." The simplest constructor expression is {}, used to create an empty table. |
We can use the type function to test the type of a given variable or value:
## Example
print(type("Hello world"))--> string
print(type(10.4*3))--> number
print(type(print))--> function
print(type(type))--> function
print(type(true))--> boolean
print(type(nil))--> nil
print(type(type(X)))--> string
* * *
## nil (Empty)
The nil type represents a value with no valid value. It has only one value -- nil. For example, printing an unassigned variable will output a nil value:
> print(type(a))nil>
For global variables and tables, nil also has a "deletion" effect. Assigning a nil value to a global variable or a variable inside a table is equivalent to deleting it. Execute the following code to see:
tab1 ={ key1 ="val1", key2 ="val2","val3"}
for k, v in pairs(tab1)do
print(k .." - ".. v)
end
tab1.key1 =nil
for k, v in pairs(tab1)do
print(k .." - ".. v)
end
### When comparing nil, you should add double quotes "":
>type(X)
nil
>type(X)==nil
false
>type(X)=="nil"
true
>
type(X)==nil results in **false** because type(X) actually returns the string "nil", which is a string type:
type(type(X))==string
* * *
## boolean (Boolean)
The boolean type has only two optional values: true (true) and false (false). Lua treats false and nil as false, and everything else as true. The number 0 is also true:
## Example
print(type(true))
print(type(false))
print(type(nil))
if false or nil then
print("At least one is true")
else
print("Both false and nil are false")
end
if 0 then
print("Number 0 is true")
else
print("Number 0 is false")
end
The execution results of the above code are as follows:
$ lua test.lua booleanbooleannilBoth false and nil are falseNumber 0 is true
* * *
## number (Number)
Lua has only one number type by default -- double (double-precision) type (the default type can be modified in luaconf.h). The following notations are all considered number types:
## Example
print(type(2))
print(type(2.2))
print(type(0.2))
print(type(2e+1))
print(type(0.2e-1))
print(type(7.8263692594256e-06))
[Run Example Β»](#)
The execution results of the above code are:
number number number number number number
* * *
## string (String)
Strings are represented by a pair of double quotes or single quotes.
string1 = "this is string1" string2 = 'this is string2'
You can also use two square brackets "[[]]" to represent a "block" of string.
## Example
html =[[
]]
print(html)
The execution result of the following code is:
When performing arithmetic operations on a numeric string, Lua will try to convert the numeric string to a number:
>print("2"+6)
8.0
>print("2"+"6")
8.0
>print("2 + 6")
2+6
>print("-2e2"*"6")
-1200.0
>print("error"+1)
stdin:1: attempt to perform arithmetic on a string value
stack traceback:
stdin:1:in main chunk
:in ?
>
In the above code, "error" + 1 causes an error. String concatenation uses .., for example:
> print("a" .. 'b') ab > print(157 .. 428)157428>
Use # to calculate the length of a string, placed before the string, as shown in the following example:
## Example
> len ="www..com"
>print(#len)
14
>print(#"www..com")
14
>
* * *
## table (Table)
In Lua, tables are created using "constructor expressions." The simplest constructor expression is {}, used to create an empty table. You can also add some data directly to initialize the table:
## Example
-- Create an empty table
local tbl1 ={}
-- Directly initialize the table
local tbl2 ={"apple","pear","orange","grape"}
The table in Lua is actually an "associative array," where the array index can be a number or a string.
## Example
-- table_test.lua script file
a ={}
a="value"
key =10
a=22
a= a+11
for k, v in pairs(a)do
print(k .." : ".. v)
end
The script execution result is:
$ lua table_test.lua key : value 10 : 33
Unlike other languages where arrays start with 0 as the initial index, in Lua, the default initial index of a table generally starts with 1.
## Example
-- table_test2.lua script file
local tbl ={"apple","pear","orange","grape"}
for key, val in pairs(tbl)do
print("Key", key)
end
The script execution result is:
$ lua table_test2.lua Key1Key2Key3Key4
The table does not have a fixed length. When new data is added, the table length will automatically increase. An uninitialized table is all nil.
## Example
-- table_test3.lua script file
a3 ={}
for i =1,10 do
a3= i
end
a3="val"
print(a3)
print(a3)
The script execution result is:
$ lua table_test3.lua val nil
* * *
## function (Function)
In Lua, functions are considered "First-Class Values." Functions can be stored in variables:
## Example
-- function_test.lua script file
function factorial1(n)
if n ==0 then
return 1
else
return n * factorial1(n -1)
end
end
print(factorial1(5))
factorial2 = factorial1
print(factorial2(5))
The script execution result is:
$ lua function_test.lua 120120
Functions can be passed as parameters in the form of anonymous functions:
## Example
-- function_test2.lua script file
function testFun(tab,fun)
for k ,v in pairs(tab)do
print(fun(k,v));
end
end
tab={key1="val1",key2="val2"};
testFun(tab,
function(key,val)-- Anonymous function
return key.."="..val;
end
);
The script execution result is:
$ lua function_test2.lua key1=val1 key2=val2
* * *
## thread (Thread)
In Lua, the main thread is the coroutine. It is similar to a thread, with its own independent stack, local variables, and instruction pointer, and can share global variables and most other things with other coroutines.
The difference between a thread and a coroutine is that multiple threads can run simultaneously, while a coroutine can only run one at a time, and a running coroutine will only pause when it is suspended.
* * *
## userdata (Userdata)
Userdata is a user-defined data type used to represent a type created by an application or a C/C++ language library. It can store data of any C/C++ data type (usually structs and pointers) into Lua variables for use.
YouTip