Lua Data Types
Lua is a dynamically typed language. Variables don't need type definitions; you just assign values to variables. Values can be stored in variables, passed as parameters, or returned as results.
Lua has 8 basic types: nil, boolean, number, string, userdata, function, thread, and table.
| Data Type | Description |
|---|---|
| nil | This is the simplest. 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 a real floating-point number of double-precision type. |
| string | Strings are represented by a pair of double quotes or single quotes. |
| function | Functions written in C or Lua. |
| userdata | Represents arbitrary C data structures stored in variables. |
| thread | Represents an independent thread of execution, used to execute coroutines. |
| table | A table in Lua is actually an "associative array". The index of the array can be a number, string, or table type. In Lua, tables are created through "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(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 indicates that there is no valid value. It has only one value -- nil. For example, printing a variable that has not been assigned a value will output a nil value:
> print(type(a)) nil >
For global variables and tables, nil also has a "delete" effect. Assigning a nil value to a global variable or a variable in a table is equivalent to deleting them. Run the following code to know:
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.":
nil
> type(X)==nil
false
> type(X)=="nil"
true
>
type(X)==nilThe result isfalseThe reason is that type(X) actually returns a"nil"string, which is a string type:
type(type(X))==string
boolean (Boolean)
The boolean type has only two optional values: true and false. Lua treats false and nil as false, everything else is true, and the number 0 is also true:
Example
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 result of the above code is as follows:
$ lua test.lua boolean boolean nil false 和 nil 都为 false 数字 0 是 true
number (Number)
Lua has only one number type by default -- double (double precision) type (the default type can be modified in luaconf.h definitions). The following notations are all considered number types:
Example
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 result of the above code:
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 double square brackets "[[]]" to represent a "block" of string.
Example
<html>
<head></head>
<body>
<a href="http://www.example.com/">Example Tutorial</a>
</body>
</html>
]]
print(html)
The execution result of the following code is:
<html>
<head></head>
<body>
<a href="../index.html">Example</a>
</body>
</html>
When performing arithmetic operations on a numeric string, Lua will attempt to convert this numeric string into a number:
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
[C]: 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 in the following example:
Example
> print(#len)
14
> print(#"www.example.com")
14
>
table (Table)
In Lua, tables are created through "constructor expressions". The simplest constructor expression is {}, used to create an empty table. You can also add some data in the table and initialize the table directly:
Example
local tbl1 = {}
-- Directly initialize the table
local tbl2 = {"apple", "pear", "orange", "grape"}
A table in Lua is actually an "associative array". The index of the array can be a number or a string.
Example
a = {}
a["key"] = "value"
key = 10
a[key] = 22
a[key] = a[key] + 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 arrays in other languages that use 0 as the initial index, in Lua the default initial index of a table generally starts at 1.
Example
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 Key 1 Key 2 Key 3 Key 4
A table does not have a fixed length. When new data is added, the table length automatically grows. Tables that are not initialized are nil.
Example
a3 = {}
for i = 1, 10 do
a3[i] = i
end
a3["key"] = "val"
print(a3["key"])
print(a3["none"])
The script execution result is:
$ lua table_test3.lua val nil
function (Function)
In Lua, functions are regarded as "First-Class Values". Functions can be stored in variables:
Example
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 120 120
Functions can be passed as arguments in the form of anonymous functions:
Example
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. It has its own independent stack, local variables, and instruction pointer, and can share global variables and most other things with other coroutines.
The difference between threads and coroutines: multiple threads can run simultaneously, but only one coroutine can run at any time, and a running coroutine will only pause when it is suspended.
userdata (Custom Type)
userdata is a user-defined data type used to represent a type created by the 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 calling.
Other Extensions