English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

类型数据 Lua

Lua 是动态类型语言,变量不要类型定义,只需要为变量赋值。 值可以存储在变量中,作为参数传递或结果返回。

Lua 中有 8 个基本类型分别为:nil、boolean、number、string、userdata、function、thread 和 table。

数据类型描述
nil这个最简单,只有值nil属于该类,表示一个无效值(在条件表达式中相当于false)。
booleano包含两个值:false和true。
number表示双精度类型的实浮点数
string字符串由一对双引号或单引号来表示
function由 C 或 Lua 编写的函数
userdata表示任意存储在变量中的C数据结构
thread表示执行的独立线路,用于执行协同程序
tableLua 中的表(table)其实是一个"关联数组"(associative arrays),数组的索引可以是数字、字符串或表类型。在 Lua 里,table 的创建是通过"构造表达式"来完成,最简单构造表达式是{},用来创建一个空表。

我们可以使用 type 函数测试给定变量或者值的类型:

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 (vuoto)

Il tipo nil rappresenta un tipo di valore senza valore effettivo, ha solo un valore -- nil, ad esempio, stampare una variabile non assegnata genererà un valore nil:

> print(type(a))
nil
>

Per le variabili globali e le tabelle, nil ha anche un'azione di "eliminazione", assegnare un valore nil a una variabile globale o a una variabile nella tabella equivalente a eliminarle, eseguire il seguente codice per vedere:

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

Quando si fa una comparazione con nil, si dovrebbe aggiungere le virgolette doppi "":

> type(X)
nil
> type(X)==nil
false
> type(X)=="nil"
true
>

type(X)==nil risultati in false La ragione è che type(X) restituisce effettivamente la stringa "nil", che è un tipo stringa:

type(type(X))==string

booleano (布尔)

Il tipo booleano ha solo due valori selezionabili: true (vero) e false (falso), Lua considera false e nil come false, tutto il resto è true, anche il numero 0 è true:

print(type(true))
print(type(false))
print(type(nil))
 
if false or nil then
    print("Almeno uno è true")
else
    print("false e nil sono entrambi false")
end
if 0 then
    print("Il numero 0 è true")
else
    print("Il numero 0 è false")
end

Il risultato dell'esecuzione del codice sopra è il seguente:

$ lua test.lua 
booleano
booleano
nil
false e nil sono entrambi false
Il numero 0 è true

numero (number)

Lua predefinisce solo un tipo di numero -- il tipo double (precisione doppia) (il tipo predefinito può essere modificato nella definizione di luaconf.h), tutte le seguenti scritture vengono considerate come tipo numero:

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))

The execution result of the above code is:

number
number
number
number
number
number

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 2 square brackets "[[]]" to represent a "block" of string.

Online example

html = [[
<html>
<head></head>
<body>
    <a href="http://it.oldtoolbag.com/">基础教程网</a>
</body>
</html>
]]
print(html)
The execution result of the following code is:
<html>
<head></head>
<body>
    <a href="http://it.oldtoolbag.com/">基础教程网</a>
</body>
</html>

When performing arithmetic operations on a numeric string, Lua will try to convert this 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 executes an error, string concatenation uses .., as follows:

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

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

> len = "it.oldtoolbag.com"
> print(#len)
14
> print(#"it.oldtoolbag.com")
14
>

table(表)

In Lua, the creation of a table is done through a "construction expression", the simplest construction expression is {}, which is used to create an empty table. It is also possible to add some data to the table and initialize it directly:

-- Create an empty table
local tbl1 = {}
 
-- Directly initialize the table
local tbl2 = {'apple', 'pear', 'orange', 'grape'}

In Lua, tables (table) are actually 'associative arrays', the index of the array can be a number or a string.

-- table_test.lua script file
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

Risultato dell'esecuzione dello script:

$ 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 tables usually starts with 1.

-- table_test2.lua script file
local tbl = {'apple', 'pear', 'orange', 'grape'}
for key, val in pairs(tbl) do
    print('Key', key)
end

Risultato dell'esecuzione dello script:

$ lua table_test2.lua 
Key 1
Key 2
Key 3
Key 4

The table does not have a fixed length, its size will automatically increase when new data is added, and all initial tables are nil.

-- table_test3.lua script file
a3 = {}
for i = 1, 10 do
    a3[i] = i
end
a3['key'] = 'val'
print(a3['key'])
print(a3['none'])

Risultato dell'esecuzione dello script:

$ lua table_test3.lua 
val
nil

function (function)

In Lua, functions are considered as 'first-class values', functions can exist in variables:

-- 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))

Risultato dell'esecuzione dello script:

$ lua function_test.lua 
120
120

La funzione può essere passata come funzione anonima (anonymous function) tramite parametro:

--file di script function_test2.lua
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)--funzione anonima
        return key.."="..val;
end
);

Risultato dell'esecuzione dello script:

$ lua function_test2.lua 
key1 = val1
key2 = val2

thread(线程)

In Lua, la principale coroutine è la coroutine. È quasi uguale a un thread, possiede un proprio stack, variabili locali e puntatore di istruzione, può condividere variabili globali e altre cose con altre coroutine.

La differenza tra thread e coroutine: i thread possono eseguire contemporaneamente, mentre una coroutine può eseguire solo una in qualsiasi momento e una coroutine in esecuzione viene sospesa solo quando viene sospesa(suspend).

userdata(tipo personalizzato)

userdata è un tipo di dati utente definito dall'utente, utilizzato per rappresentare un tipo creato da un'applicazione o una libreria del linguaggio C/C++, che può memorizzare i dati di qualsiasi tipo di dati C/C++ (tipicamente struct e puntatori) in un variabile Lua per essere chiamati.