基本数据类型 #

一、类型概述 #

Lua 是动态类型语言,变量没有类型,值才有类型。Lua 有 8 种基本数据类型:

类型 描述 示例
nil 空值 nil
boolean 布尔值 true, false
number 数字 1, 3.14, 0xff
string 字符串 “hello”, [[多行]]
function 函数 function() end
table {},
thread 协程 coroutine.create()
userdata 用户数据 C 数据结构

1.1 type 函数 #

使用 type() 函数获取值的类型:

lua
print(type(nil))       -- nil
print(type(true))      -- boolean
print(type(42))        -- number
print(type("hello"))   -- string
print(type(print))     -- function
print(type({}))        -- table
print(type(coroutine.create(function() end)))  -- thread

二、nil 类型 #

2.1 nil 的含义 #

nil 表示"没有值"或"无效值":

lua
-- 未初始化的变量
local x
print(x)  -- nil

-- 删除变量
local y = 10
y = nil   -- y 现在是 nil

-- 表中不存在的键
local t = {name = "Lua"}
print(t.age)  -- nil

2.2 nil 的用途 #

lua
-- 1. 表示缺失值
local function greet(name)
    name = name or "World"  -- 默认值
    print("Hello, " .. name)
end
greet()        -- Hello, World
greet("Lua")   -- Hello, Lua

-- 2. 删除表字段
local t = {a = 1, b = 2}
t.a = nil
print(t.a)  -- nil

-- 3. 条件判断
local value = get_value()
if value == nil then
    print("没有获取到值")
end

2.3 nil 与 false 的区别 #

lua
-- nil 和 false 在条件判断中都是假
local a = nil
local b = false

if not a then print("a 是假") end  -- a 是假
if not b then print("b 是假") end  -- b 是假

-- 但它们不相等
print(a == b)  -- false
print(type(a)) -- nil
print(type(b)) -- boolean

三、boolean 类型 #

3.1 布尔值 #

lua
local is_true = true
local is_false = false

print(type(is_true))   -- boolean
print(type(is_false))  -- boolean

3.2 真值与假值 #

Lua 中只有 falsenil 是假值,其他都是真值:

lua
-- 假值
if nil then print("不会执行") end
if false then print("不会执行") end

-- 真值
if true then print("执行") end
if 0 then print("执行") end        -- 0 是真值!
if "" then print("执行") end       -- 空字符串是真值!
if {} then print("执行") end       -- 空表是真值!

3.3 逻辑运算 #

lua
-- and 运算
print(true and true)    -- true
print(true and false)   -- false
print(false and true)   -- false
print(nil and true)     -- nil(短路求值)

-- or 运算
print(true or false)    -- true
print(false or true)    -- true
print(false or false)   -- false
print(nil or "default") -- default(短路求值)

-- not 运算
print(not true)         -- false
print(not false)        -- true
print(not nil)          -- true
print(not 0)            -- false

3.4 实用技巧 #

lua
-- 默认值
local name = arg[1] or "World"

-- 三元运算模拟
local max = a > b and a or b

-- 安全访问
local value = obj and obj.field or "default"

-- 布尔转换
local function toboolean(v)
    return v and true or false
end

四、number 类型 #

4.1 数字类型 #

Lua 5.3+ 有两种数字表示:

lua
-- 整数(64位整数)
local int = 42
print(type(int))  -- number

-- 浮点数(64位双精度)
local float = 3.14
print(type(float))  -- number

-- 检查是否为整数
print(math.type(42))    -- integer
print(math.type(3.14))  -- float
print(math.type(42.0))  -- integer(Lua 5.4)

4.2 数字表示 #

lua
-- 十进制
local a = 42
local b = 3.14
local c = 0.5
local d = .5      -- 等同于 0.5

-- 科学计数法
local e = 1.5e10  -- 1.5 × 10^10
local f = 5e-3    -- 0.005

-- 十六进制
local g = 0xff    -- 255
local h = 0xFF    -- 255
local i = 0x1.8p1 -- 3.0(十六进制浮点数)

4.3 算术运算 #

lua
local a, b = 10, 3

print(a + b)   -- 加法:13
print(a - b)   -- 减法:7
print(a * b)   -- 乘法:30
print(a / b)   -- 除法:3.333...
print(a // b)  -- 整除:3
print(a % b)   -- 取余:1
print(a ^ b)   -- 幂运算:1000.0
print(-a)      -- 负号:-10

4.4 数学函数 #

lua
-- 常用数学函数
print(math.abs(-10))      -- 绝对值:10
print(math.ceil(3.2))     -- 向上取整:4
print(math.floor(3.8))    -- 向下取整:3
print(math.max(1, 5, 3))  -- 最大值:5
print(math.min(1, 5, 3))  -- 最小值:1
print(math.sqrt(16))      -- 平方根:4.0
print(math.random())      -- 随机数 [0, 1)
print(math.random(10))    -- 随机整数 [1, 10]

-- 三角函数
print(math.sin(math.pi/2))  -- 1.0
print(math.cos(0))          -- 1.0
print(math.tan(0))          -- 0.0

-- 常量
print(math.pi)    -- 3.1415926535898
print(math.huge)  -- 正无穷

4.5 数字转换 #

lua
-- 字符串转数字
local n1 = tonumber("42")      -- 42
local n2 = tonumber("3.14")    -- 3.14
local n3 = tonumber("0xff", 16) -- 255
local n4 = tonumber("hello")   -- nil

-- 数字转字符串
local s1 = tostring(42)    -- "42"
local s2 = tostring(3.14)  -- "3.14"

-- 格式化
local s3 = string.format("%d", 42)      -- "42"
local s4 = string.format("%.2f", 3.14159) -- "3.14"

4.6 数字精度 #

lua
-- 浮点数精度问题
local a = 0.1 + 0.2
print(a == 0.3)  -- false

-- 正确的比较方式
local function almost_equal(x, y, epsilon)
    epsilon = epsilon or 1e-10
    return math.abs(x - y) < epsilon
end
print(almost_equal(0.1 + 0.2, 0.3))  -- true

-- 整数运算精确
local b = 10000000000000000 + 1
print(b)  -- 10000000000000001(精确)

五、string 类型 #

5.1 字符串创建 #

lua
-- 单引号
local s1 = 'Hello'

-- 双引号
local s2 = "World"

-- 长字符串(可换行)
local s3 = [[
这是一段
多行字符串
]]

-- 带缩进的长字符串
local s4 = [=[
    保持缩进
    的字符串
]=]

5.2 转义字符 #

lua
print("换行:\n第二行")
print("制表符:\t缩进")
print("引号:\"引号\"")
print("反斜杠:\\")
print("回车:\r")

5.3 字符串操作 #

lua
local s = "Hello, Lua!"

-- 长度
print(#s)              -- 12
print(string.len(s))   -- 12

-- 大小写
print(string.upper(s)) -- HELLO, LUA!
print(string.lower(s)) -- hello, lua!

-- 子串
print(string.sub(s, 1, 5))  -- Hello
print(string.sub(s, -4))    -- Lua!

-- 查找
print(string.find(s, "Lua"))  -- 8    10

-- 替换
print(string.gsub(s, "Lua", "World"))  -- Hello, World!    1

-- 分割
print(string.match(s, "(%w+), (%w+)"))  -- Hello    Lua

5.4 字符串连接 #

lua
-- 使用 .. 连接
local s1 = "Hello" .. " " .. "World"

-- 使用 table.concat(高效)
local parts = {"Hello", "World", "Lua"}
local s2 = table.concat(parts, " ")

-- 使用 string.format
local name = "Lua"
local version = 5.4
local s3 = string.format("%s %.1f", name, version)

六、function 类型 #

6.1 函数是值 #

lua
-- 函数是第一类值
local f = function(x)
    return x * 2
end

print(f(5))  -- 10

-- 函数作为参数
local function apply(func, value)
    return func(value)
end
print(apply(f, 10))  -- 20

-- 函数作为返回值
local function get_multiplier(n)
    return function(x)
        return x * n
    end
end

local double = get_multiplier(2)
print(double(5))  -- 10

6.2 函数定义语法 #

lua
-- 函数定义方式
function foo1() end
local foo2 = function() end
local function foo3() end

-- 方法定义
local obj = {}
function obj:method()
    print(self)
end

七、table 类型 #

7.1 表的基本使用 #

lua
-- 创建表
local t = {}

-- 数组风格
local arr = {1, 2, 3, 4, 5}

-- 字典风格
local dict = {name = "Lua", version = 5.4}

-- 访问
print(arr[1])        -- 1(Lua 索引从 1 开始)
print(dict.name)     -- Lua
print(dict["name"])  -- Lua

-- 修改
arr[1] = 10
dict.version = 5.3

-- 添加
dict.author = "PUC-Rio"

-- 删除
dict.author = nil

7.2 表的遍历 #

lua
local t = {a = 1, b = 2, c = 3}

-- 遍历键值对
for k, v in pairs(t) do
    print(k, v)
end

-- 遍历数组部分
local arr = {10, 20, 30}
for i, v in ipairs(arr) do
    print(i, v)
end

-- 数值索引遍历
for i = 1, #arr do
    print(i, arr[i])
end

八、thread 类型 #

8.1 协程 #

lua
-- 创建协程
local co = coroutine.create(function()
    for i = 1, 3 do
        print("协程:" .. i)
        coroutine.yield()
    end
end)

print(type(co))  -- thread

-- 运行协程
coroutine.resume(co)  -- 协程:1
coroutine.resume(co)  -- 协程:2
coroutine.resume(co)  -- 协程:3

九、userdata 类型 #

9.1 用户数据 #

userdata 用于表示 C 语言创建的数据结构:

lua
-- 文件句柄是 userdata
local file = io.open("test.txt", "w")
print(type(file))  -- userdata
file:close()

-- Lua 代码通常不直接创建 userdata
-- 它们由 C 库提供

十、类型转换 #

10.1 显式转换 #

lua
-- 数字转字符串
local s = tostring(42)      -- "42"
local s2 = string.format("%d", 42)  -- "42"

-- 字符串转数字
local n = tonumber("42")    -- 42
local n2 = tonumber("3.14") -- 3.14
local n3 = tonumber("hi")   -- nil

-- 布尔转字符串
local b = tostring(true)    -- "true"

10.2 自动转换 #

lua
-- 字符串连接时自动转换
local s = "数字:" .. 42  -- "数字:42"

-- 算术运算时尝试转换
local n = "10" + 5  -- 15(字符串转数字)
-- local err = "a" + 1  -- 错误!

-- 比较运算时自动转换
print("10" == 10)  -- false(类型不同)
print(10 == 10.0)  -- true(数字比较)

十一、类型检查 #

11.1 type 函数 #

lua
local function check_type(value)
    local t = type(value)
    if t == "nil" then
        print("空值")
    elseif t == "boolean" then
        print("布尔值:" .. tostring(value))
    elseif t == "number" then
        print("数字:" .. value)
    elseif t == "string" then
        print("字符串:" .. value)
    elseif t == "table" then
        print("表")
    elseif t == "function" then
        print("函数")
    elseif t == "thread" then
        print("协程")
    elseif t == "userdata" then
        print("用户数据")
    end
end

11.2 类型断言 #

lua
local function assert_type(value, expected_type, name)
    name = name or "参数"
    if type(value) ~= expected_type then
        error(string.format("%s 应该是 %s,实际是 %s",
            name, expected_type, type(value)), 2)
    end
end

local function process(data)
    assert_type(data, "table", "data")
    -- 处理数据
end

十二、总结 #

本章介绍了 Lua 的 8 种基本数据类型:

  1. nil:空值,表示缺失
  2. boolean:true 和 false
  3. number:整数和浮点数
  4. string:字符串,不可变
  5. function:函数,第一类值
  6. table:表,唯一的数据结构
  7. thread:协程
  8. userdata:C 数据

掌握这些数据类型是 Lua 编程的基础。下一章,我们将深入学习字符串操作。

最后更新:2026-03-27