Lua - 数据类型



Lua 是一种动态类型语言,因此变量没有类型,只有值有类型。值可以存储在变量中,作为参数传递,并作为结果返回。

在 Lua 中,虽然我们没有变量数据类型,但我们有值类型。下面列出了值的各种数据类型。

序号 值类型 & 描述
1

nil

用于区分值是否有数据或无(nil)数据。

2

boolean

包含 true 和 false 作为值。通常用于条件检查。

3

number

表示实数(双精度浮点数)。

4

string

表示字符数组。

5

function

表示用 C 或 Lua 编写的函数。

6

userdata

表示任意的 C 数据。

7

thread

表示独立的执行线程,用于实现协程。

8

table

表示普通数组、符号表、集合、记录、图形、树等,并实现关联数组。它可以保存任何值(除了 nil)。

示例 - type 函数

在 Lua 中,有一个名为 'type' 的函数,它使我们能够知道变量的类型。以下代码给出了一些示例。

print(type("What is my type"))   --> string
t = 10

print(type(5.8*t))               --> number
print(type(true))                --> boolean
print(type(print))               --> function
print(type(nil))                 --> nil
print(type(type(ABC)))           --> string

构建并执行上述程序时,它在 Linux 上会产生以下结果:

string
number
boolean
function
nil
string

示例 - type 函数

我们也可以定义变量的类型,并且 type 函数在这种情况下也能完美工作。

print(type("What is my type"))   --> string
t = 10

print(type(5.8*t))               --> number
print(type(true))                --> boolean
print(type(print))               --> function
print(type(nil))                 --> nil
print(type(type(ABC)))           --> string

构建并执行上述程序时,它在 Linux 上会产生以下结果:

string
number
boolean
function
nil
string

我们也可以获取函数的类型,如下所示:

function max(num1, num2)

   if (num1 > num2) then
      result = num1;
   else
      result = num2;
   end

   return result;
end

-- get the type of a function
print("The type of the function ",type(max))

-- get the type of result of function
print("The type of the function ",type(max(3,4)))

-- get the result of function
print("The Max Value: ",max(3,4))

构建并执行上述程序时,它在 Linux 上会产生以下结果:

The type of the function 	function
The type of the function 	number
The Max Value: 	4

默认情况下,所有变量在被赋值或初始化之前都指向 nil。在 Lua 中,零和空字符串在条件检查中被视为真。因此,在使用布尔运算时需要小心。我们将在接下来的章节中进一步了解这些类型的用法。

广告

© . All rights reserved.