Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Lua data type


May 12, 2021 Lua


Table of contents


Lua data type

Lua is a dynamic type language, and variables are not defined by type, but are only assigned values to variables. Values can be stored in variables and passed as arguments or returned as a result.

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

The data type Describe
nil The simplest of these, only the value nil belongs to the class, representing an invalid value (equivalent to false in a conditional expression).
boolean Contains two values: false and true.
number Represents the number of floating points of the double type
string Strings are represented by a pair of double or single quotes
function Functions written by C or Lua
userdata Represents any C-data structure stored in a variable
thread A stand-alone line that represents execution and is used to perform a collaborative program
table The table in Lua is actually an "associate array" that can be indexed by numbers, strings, or table types. In Lua, table is created by "constructing expressions", the simplest of which is 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)

The nil type represents a value that does not have any valid value, and it has only one value -- nil, for example, printing a variable without an assignment, outputs an nil value:

> print(type(a))
nil
>

For global variables and table, nil also has a "delete" effect, assigning a nil value to a global variable or variable in the table table, which is equivalent to deleting them, as you 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

Double quotes should be added when comparing using 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 considers false and nil to be "false" and the others to be "true":

print(type(true))
print(type(false))
print(type(nil))
 
if type(false) or type(nil) then
    print("false and nil are false!")
else
    print("other is true!")
end

The above code executes as follows:

$ lua test.lua 
boolean
boolean
nil
false and nil are false!

number (number)

Lua defaults to only one number type -- double (the default type can modify the definition in luaconf.h), and the following are considered number types:

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 an instance . . .


The above code execution results:

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 represent a "piece" string.

html = [[
<html>
<head></head>
<body>
    <a href="//www.w3cschool.cn/">w3cschoolW3Cschool教程</a>
</body>
</html>
]]
print(html)

The following code executes as follows:

<html>
<head></head>
<body>
    <a href="//www.w3cschool.cn/">w3cschoolW3Cschool教程</a>
</body>
</html>

When performing arithmetic on a numeric string, Lua tries 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" and 1 execute the error, the string connection is using .. Such as:

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

Use the s to calculate the length of the string, placed in front of the string, as follows:

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

table (table)

In Lua, table is created by "constructing expressions", the simplest of which is to create an empty table. You can also add some data to the table to initialize the table directly:

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

The table in Lua is actually an "associate array" that can be indexed as 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 executes as follows:

$ lua table_test.lua 
key : value
10 : 33

Unlike arrays in other languages that use 0 as the initial index of the array, the default initial index of tables in Lua typically 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 executes as follows:

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

Table does not have a fixed length size, the table length increases automatically when new data is added, and no initial 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 executes as follows:

$ lua table_test3.lua 
val
nil

function (function)

In Lua, a function is considered a "First-Class Value" and can exist 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 executes as follows:

$ lua function_test.lua 
120
120

Functions can be passed through parameters in the form of anonymous functions:

-- 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 executes as follows:

$ lua function_test2.lua 
key1 = val1
key2 = val2

thread (thread)

In Lua, the main thread is the coroutine. It's similar to thread, with its own separate stack, local variables, and instruction pointers, and can share global variables and most of other things with other co-programs.

The difference between a thread and a co-program: a thread can run multiple times at the same time, while a co-program can run only one at any one time, and a co-program that is running is suspended only when it is suspended.


userdata (custom type)

Userdata is a user-defined data that represents a type created by an application or C/C?language library that can store data of any data type (usually struct and pointer) from any C/C?to be called in the Lua variable.