Latest web development tutorials

Lua data types

Lua is a dynamically typed language, variables, type definitions do not need only assign values ​​to variables. Values ​​can be stored in variables, passed as a parameter or return the results.

Lua has eight basic types are: nil, boolean, number, string, userdata, function, thread and table.

type of data description
nil The most simple, only the value nil belong to this class represents an invalid value (equivalent to false in conditional expressions).
boolean It contains two values: false and true.
number It represents the type of double-precision floating-point real
string String by a pair of double or single quotes to represent
function Or by the C function written in Lua
userdata C represents any data structure stored in a variable
thread That the implementation of a separate line for the implementation of cooperative programs
table Lua tables (table) is actually a "associative array" (associative arrays), the index of the array can be a number or a string. In Lua, the table is created by the "expression construct" to complete the simplest expression construct {} 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 does not have any type indicates a valid value, it is only one value - nil, such as printing a variable assignment does not, it will output a nil value:

> print(type(a))
nil
>

For global variables and table, nil and a "delete" action, to the global variable table or table variable assigned a nil value, equivalent to delete 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

boolean (Boolean)

boolean type has only two possible values: true (true) and false (false), Lua to false and nil as "false", the other "true":

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

The above code is executed as follows:

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

number (Digital)

Lua default is only one number type - double (double precision) Type (the default type can be modified in luaconf.h definition), the following wording is seen to be 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))

Running instance »

Results of the above code:

number
number
number
number
number
number

string (string)

String by a pair of double or single quotes to represent.

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

You can also use two brackets "[[]]" to mean "one" string.

html = [[
<html>
<head></head>
<body>
    <a href="http://www.w3cschool.cc/">w3cschool本教程</a>
</body>
</html>
]]
print(html)

The following code execution results:

<html>
<head></head>
<body>
    <a href="http://www.w3cschool.cc/">w3cschool本教程</a>
</body>
</html>

When a numeric string to perform arithmetic operations, Lua will try to turn that number into a string of 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 ?
> 

The above code "error" + 1 execution error, the string concatenation using .., such as:

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

Use # to calculate the length of the string, the string on the front, following examples:

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

table (Table)

In Lua, the table is created by the "expression construct" to complete the simplest expression construct {} is used to create an empty table. You can also add some data in the table, direct initialization table:

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

Lua tables (table) is actually a "associative array" (associative arrays), 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

Script execution results:

$ lua table_test.lua 
key : value
10 : 33

Unlike other languages ​​of the array as an array of initial index 0, the default initial index in the table in Lua generally 1.

-- table_test2.lua 脚本文件
local tbl = {"apple", "pear", "orange", "grape"}
for key, val in pairs(tbl) do
    print("Key", key)
end

Script execution results:

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

table size is not fixed length, there is an automatic increase in the length of the table to add new data, the original table is not nil.

-- table_test3.lua 脚本文件
a3 = {}
for i = 1, 10 do
    a3[i] = i
end
a3["key"] = "val"
print(a3["key"])
print(a3["none"])

Script execution results:

$ lua table_test3.lua 
val
nil

function (Function)

In Lua, the function is considered "first class values ​​(First-Class Value)", there may be variable function:

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

Script execution results:

$ lua function_test.lua 
120
120

function can be anonymous function (anonymous function) by way of parameter passing:

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

Script execution results:

$ lua function_test2.lua 
key1 = val1
key2 = val2

thread (thread)

In Lua, the main thread is a collaborative program (coroutine). It is with thread (thread) almost has its own independent stack, local variables and instruction pointer, you can share global variables and most of the other stuff with other collaborative programs.

Thread difference with coroutines: multiple threads can run simultaneously, and coroutine can only run one at any time, and running coroutine only hang (suspend) only when paused.


userdata (custom type)

userdata is a user-defined data type used by the application indicates a or C / C ++ language library created can be any C / C ++ data of any data type (usually a struct and pointers) stored in Lua call variable.