Lua data types


Lua is a dynamically typed language. Variables do not need to be typed, only variables need to be assigned values. Values ​​can be stored in variables, passed as arguments or returned as results.

There are 8 basic types in Lua: nil, boolean, number, string, userdata, function, thread and table.

Data typeDescription
nilThis is the simplest, only the value nil Belongs to this class and represents an invalid value (equivalent to false in conditional expressions).
boolean Contains two values: false and true.
numberRepresents a real floating-point number of double precision type
stringThe string consists of one Use double quotes or single quotes to represent
functionFunction written in C or Lua
userdata Represents any C data structure stored in a variable
threadRepresents an independent line of execution for executing coroutines
tableA table in Lua is actually an "associative array", and the index of the array can be a number or a string. In Lua, table creation is accomplished through "constructive expressions". The simplest constructed expression is {}, which is used to create an empty table.

We can use the type function to test the type of a given variable or value:

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)

nil type represents a type that does not have any valid values, it has only one Value - nil, for example, printing a variable without an assigned value will output a nil value:

> print(type(a))
nil
>

For global variables and tables, nil also has a "delete" function, which is used for global variables or tables. Assigning a nil value to variables is equivalent to deleting them. You will know by executing the following code:

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

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 is "true":

print(type(true))
print(type(false))
print(type(nil))
 
if false or nil then
    print("至少有一个是 true")
else
    print("false 和 nil 都为 false!")
end

The execution result of the above code is as follows:

$ lua test.lua 
boolean
boolean
nil
false 和 nil 都为 false!

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 writing methods are regarded as number types :

Instance

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 instance»

Click the "Run instance" button to view the online instance

The above code execution result:

number
number
number
number
number
number

string (string)

The string is represented by a pair of double quotes or single quotes.

string1 = "this is string1"
string2 = 'this is string2'

You can also use 2 square brackets "[[]]" to represent a "piece" of string.

html = [[
<html>
<head></head>
<body>
    <a href="http://www.w3cschool.cc/">w3cschoolphp中文网</a>
</body>
</html>
]]
print(html)

The execution result of the following code is:

<html>
<head></head>
<body>
    <a href="http://www.w3cschool.cc/">w3cschoolphp中文网</a>
</body>
</html>

When performing arithmetic operations on a numeric string, Lua will try to convert the numeric string into 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
	[C]: in ?
>

In the above code, "error" + 1 is reported as an error. The string connection uses .., such as:

> print("a" .. 'b')
ab
> print(157 .. 428)
157428
>

Use # to calculate the length of the string and place it in front of the string, as shown in the following example:

> len = "www.w3cschool.cc"
> print(#len)
16
> print(#"www.w3cschool.cc")
16
>

table (table)

In Lua, the creation of table is completed through "construction expression". The simplest construction expression is {}, which is used to create a Empty table. You can also add some data to the table and initialize the table directly:

-- 创建一个空的 table
local tbl1 = {}
 
-- 直接初始表
local tbl2 = {"apple", "pear", "orange", "grape"}

The table in Lua is actually an "associative array" (associative array), and the index of the array can be a number or a string.

-- table_test.lua 脚本文件
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, which use 0 as the initial index of the array, the default initial index of the table in Lua generally starts with 1.

-- table_test2.lua 脚本文件
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

The table will not have a fixed length. When new data is added, the length of the table will automatically grow. Tables that are not initialized will be nil.

-- table_test3.lua 脚本文件
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, a function is regarded as a "first-type value (First- Class Value)", the function can be stored in a variable:

-- function_test.lua 脚本文件
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

function can be passed through parameters in the form of an anonymous function:

-- function_test2.lua 脚本文件
function anonymous(tab, fun)
    for k, v in pairs(tab) do
        print(fun(k, v))
    end
end
tab = { key1 = "val1", key2 = "val2" }
anonymous(tab, function(key, val)
    return key .. " = " .. val
end)

The script execution result is:

$ lua function_test2.lua 
key1 = val1
key2 = val2

thread (thread)

In Lua, the most important thread is the coroutine. It is similar to a thread and has its own independent stack, local variables and instruction pointer. It can share global variables and most other things with other coroutines.

The difference between threads and coroutines: threads can run multiple times at the same time, but coroutines can only run one at any time, and a running coroutine will only be suspended when it is suspended.


userdata (custom type)

userdata is a type of user-defined data used to represent a type created by an application or C/C++ language library. Store any data of any C/C++ data type (usually struct and pointer) into a Lua variable and call it.