Lua learning (3)--Lua data types

Lua is a dynamically typed language . Variables do not need to be typed, just assign values ​​to variables. 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.

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

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

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 means that there is no valid value, it has only one value - nil, for example printing a variable without a value will output a nil value:

> print(type(a))
nil
>

For global variables and tables, nil also has a "delete" function. Assigning a nil value to a global variable or a variable in the table table is equivalent to deleting them. Execute the following code to know:

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

Double quotes should be used when comparing nil ":

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

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 result of executing the above code is as follows:

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

number

Lua has only one number type by default - double (double precision) type (the default type can be modified in the definition in luaconf.h), the following types of writing are regarded as number type:

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 result of executing the above code:

number
number
number
number
number
number

string (string)

Strings are represented by a pair of double or single quotes.

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

You can also use 2 square brackets "[[]]" to denote a "block" of string.

html = [[
<html>
<head></head>
<body>
    <a href="http://www.runoob.com/">菜鸟教程</a>
</body>
</html>
]]
print(html)

The result of executing the following code is:

<html>
<head></head>
<body>
    <a href="http://www.runoob.com/">菜鸟教程</a>
</body>
</html>

When performing arithmetic operations on a number string, Lua will try to convert the number string into a number:
here "+" can only be used to add numbers

> 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 executed and an error is reported. String concatenation uses .. , such as:

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

Use # to calculate the length of the string and put it before the string, as in the following example:

> len = "www.runoob.com"
> print(#len)
14
> print(#"www.runoob.com")
14
> 

table

In Lua, table creation is done through "construction expressions". The simplest construction expression is {}, which is used to create an 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"}

A table in Lua is actually an "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 a 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 does not have a fixed size. When new data is added, the length of the table will automatically increase . The original table is 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

In Lua, functions are seen as "First-Class Values", and functions can be stored in variables:

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

A function can be passed as an anonymous function parameter:

-- 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)--匿名函数
    return key.."="..val;
end
);

The script execution result is:

$ lua function_test2.lua 
key1 = val1
key2 = val2

thread

In Lua, the main thread is the coroutine (coroutine). It is similar to a thread, with its own independent stack, local variables and instruction pointers, and can share global variables and most other things with other coroutines.
The difference between a thread and a coroutine: a thread can run multiple times at the same time, while a coroutine 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 user-defined data used to represent a type created by an application or a C/C++ language library, which can store any C/C++ data of any data type (usually structs and pointers) into Lua variable called.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325588374&siteId=291194637