GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • 首页
  • HTML
  • JavaScript
  • CSS
  • React
  • Python3
  • Java
  • C
  • C++
  • C#
  • Go
  • SQL
  • Linux
  • VS Code

This view

  • Original page
  • New address

GeezerVison is showing www.runoob.com — Lua table(表) | 菜鸟教程

菜鸟教程 -- 学的不仅是技术,更是梦想!

  • Vue3 教程
  • Vue2 教程
  • Bootstrap3
  • Bootstrap4
  • Bootstrap5
  • 机器学习
  • PyTorch
  • TensorFlow
  • Sklearn
  • NLP
  • AI Agent
  • Ollama
  • Coding Plan
Lua 教程
Lua 教程 Lua 环境安装 Lua 编辑器 Lua 基本语法 Lua 数据类型 Lua 变量 Lua 循环 Lua 流程控制 Lua 函数 Lua 运算符 Lua 字符串 Lua 数组 Lua 迭代器 Lua table(表) Lua 模块与包 Lua 元表(Metatable) Lua 协同程序(coroutine) Lua 文件 I/O Lua 错误处理 Lua 调试(Debug) Lua 垃圾回收 Lua 面向对象 Lua 数据库访问 Lua5.3 参考手册
Lua 迭代器
Lua 模块与包

Lua table(表)

table 是 Lua 的一种数据结构用来帮助我们创建不同的数据类型,如:数组、字典等。

Lua table 使用关联型数组,你可以用任意类型的值来作数组的索引,但这个值不能是 nil。

Lua table 是不固定大小的,你可以根据自己需要进行扩容。

Lua也是通过table来解决模块(module)、包(package)和对象(Object)的。 例如string.format表示使用"format"来索引table string。


table(表)的构造

构造器是创建和初始化表的表达式。表是Lua特有的功能强大的东西。最简单的构造函数是{},用来创建一个空表。可以直接初始化数组:

-- 初始化表
mytable = {}

-- 指定值
mytable[1]= "Lua"

-- 移除引用
mytable = nil
-- lua 垃圾回收会释放内存

当我们为 table a 并设置元素,然后将 a 赋值给 b,则 a 与 b 都指向同一个内存。如果 a 设置为 nil ,则 b 同样能访问 table 的元素。如果没有指定的变量指向a,Lua的垃圾回收机制会清理相对应的内存。

以下实例演示了以上的描述情况:

实例

-- 简单的 table
mytable = {}
print("mytable 的类型是 ",type(mytable))

mytable[1]= "Lua"
mytable["wow"] = "修改前"
print("mytable 索引为 1 的元素是 ", mytable[1])
print("mytable 索引为 wow 的元素是 ", mytable["wow"])

-- alternatetable和mytable的是指同一个 table
alternatetable = mytable

print("alternatetable 索引为 1 的元素是 ", alternatetable[1])
print("alternatetable 索引为 wow 的元素是 ", alternatetable["wow"])

alternatetable["wow"] = "修改后"

print("mytable 索引为 wow 的元素是 ", mytable["wow"])

-- 释放变量
alternatetable = nil
print("alternatetable 是 ", alternatetable)

-- mytable 仍然可以访问
print("mytable 索引为 wow 的元素是 ", mytable["wow"])

mytable = nil
print("mytable 是 ", mytable)

以上代码执行结果为:

mytable 的类型是        table
mytable 索引为 1 的元素是       Lua
mytable 索引为 wow 的元素是     修改前
alternatetable 索引为 1 的元素是        Lua
alternatetable 索引为 wow 的元素是      修改前
mytable 索引为 wow 的元素是     修改后
alternatetable 是       nil
mytable 索引为 wow 的元素是     修改后
mytable 是      nil

Table 操作

以下列出了 Table 操作常用的方法:

序号方法 & 用途
1table.concat (table [, sep [, start [, end]]]):

concat是concatenate(连锁, 连接)的缩写. table.concat()函数列出参数中指定table的数组部分从start位置到end位置的所有元素, 元素间以指定的分隔符(sep)隔开。

2table.insert (table, [pos,] value):

在table的数组部分指定位置(pos)插入值为value的一个元素. pos参数可选, 默认为数组部分末尾.

3table.maxn (table)

指定table中所有正数key值中最大的key值. 如果不存在key值为正数的元素, 则返回0。(Lua5.2之后该方法已经不存在了,本文使用了自定义函数实现)

4table.remove (table [, pos])

返回table数组部分位于pos位置的元素. 其后的元素会被前移. pos参数可选, 默认为table长度, 即从最后一个元素删起。

5table.sort (table [, comp])

对给定的table进行升序排序。

接下来我们来看下这几个方法的实例。

Table 连接

我们可以使用 concat() 输出一个列表中元素连接成的字符串:

实例

fruits = {"banana","orange","apple"}
-- 返回 table 连接后的字符串
print("连接后的字符串 ",table.concat(fruits))

-- 指定连接字符
print("连接后的字符串 ",table.concat(fruits,", "))

-- 指定索引来连接 table
print("连接后的字符串 ",table.concat(fruits,", ", 2,3))

执行以上代码输出结果为:

连接后的字符串     bananaorangeapple
连接后的字符串     banana, orange, apple
连接后的字符串     orange, apple

插入和移除

以下实例演示了 table 的插入和移除操作:

实例

fruits = {"banana","orange","apple"}

-- 在末尾插入
table.insert(fruits,"mango")
print("索引为 4 的元素为 ",fruits[4])

-- 在索引为 2 的键处插入
table.insert(fruits,2,"grapes")
print("索引为 2 的元素为 ",fruits[2])

print("最后一个元素为 ",fruits[5])
table.remove(fruits)
print("移除后最后一个元素为 ",fruits[5])

执行以上代码输出结果为:

索引为 4 的元素为     mango
索引为 2 的元素为     grapes
最后一个元素为     mango
移除后最后一个元素为     nil

Table 排序

以下实例演示了 sort() 方法的使用,用于对 Table 进行排序:

实例

fruits = {"banana","orange","apple","grapes"}
print("排序前")
for k,v in ipairs(fruits) do
        print(k,v)
end

table.sort(fruits)
print("排序后")
for k,v in ipairs(fruits) do
        print(k,v)
end

执行以上代码输出结果为:

排序前
1    banana
2    orange
3    apple
4    grapes
排序后
1    apple
2    banana
3    grapes
4    orange

Table 最大值

table.maxn 在 Lua5.2 之后该方法已经不存在了,我们定义了 table_maxn 方法来实现。

以下实例演示了如何获取 table 中的最大值:

实例

function table_maxn(t)
  local mn=nil;
  for k, v in pairs(t) do
    if(mn==nil) then
      mn=v
    end
    if mn < v then
      mn = v
    end
  end
  return mn
end
tbl = {[1] = 2, [2] = 6, [3] = 34, [26] =5}
print("tbl 最大值:", table_maxn(tbl))
print("tbl 长度 ", #tbl)

执行以上代码输出结果为:

tbl 最大值:    34
tbl 长度     3

注意:

当我们获取 table 的长度的时候无论是使用 # 还是 table.getn 其都会在索引中断的地方停止计数,而导致无法正确取得 table 的长度。

可以使用以下方法来代替:

function table_leng(t)
  local leng=0
  for k, v in pairs(t) do
    leng=leng+1
  end
  return leng;
end
AI 思考中...
Lua 迭代器
Lua 模块与包

7 篇笔记 写笔记

  1. #0

       wb070815

      109***[email protected]

    21

    table 去重

    function table.unique(t, bArray)
        local check = {}
        local n = {}
        local idx = 1
        for k, v in pairs(t) do
            if not check[v] then
                if bArray then
                    n[idx] = v
                    idx = idx + 1
                else
                    n[k] = v
                end
                check[v] = true
            end
        end
        return n
    end
    wb070815

       wb070815

      109***[email protected]

    9年前 (2018-04-03)
  2. #0

       hhh

      cdd***[email protected]

    12

    数组去重

    --数组去重函数
    function removeRepeat(a)
        local b = {}
        for k,v in ipairs(a) do
            if(#b == 0) then
                b[1]=v;
            else
                local index = 0
                for i=1,#b do
                    if(v == b[i]) then
                        break
    
                    end
                    index = index + 1
                end
                if(index == #b) then
                    b[#b + 1] = v;
                end
            end
        end
        return b
    end
    
    --遍历数组输出
    function output(o)
        for k,v in ipairs(o) do
            print(k,v)
        end
    end
    
    --测试
    arr = {1,1,1,2,4,5,3,2,5,3,6}
    narr = removeRepeat(arr)
    table.sort(narr)  --对数组排序
    output(narr)

    结果:

    1    1
    2    2
    3    3
    4    4
    5    5
    6    6
    hhh

       hhh

      cdd***[email protected]

    9年前 (2018-04-11)
  3. #0

       Colin

      amc***[email protected]

    22
    -- table 去重
    table = {1 , 2 , 3 , 4 , 20 , 6 , 7 , 7 , 15 , 28};
    function table_unique(t) 
        local check = {};
        local n = {};
        for key , value in pairs(t) do
            if not check[value] then
                n[key] = value
                check[value] = value
            end
        end
        return n
    end 
    
    for key , value in pairs(table_unique(table)) do
        print('value is ' , value)
    end
    Colin

       Colin

      amc***[email protected]

    9年前 (2018-04-24)
  4. #0

       Elynn

      ely***[email protected]

    22

    排序支持自定义排序规则,比如:

    t =
    {
        [1] = {A = 5, B = 2},
        [2] = {A = 1, B = 3},
        [3] = {A = 3, B = 6},
        [4] = {A = 7, B = 1},
        [5] = {A = 2, B = 9},
    }
    table.sort(t, function(a, b) return a.A > b.A; end)
    Elynn

       Elynn

      ely***[email protected]

    9年前 (2018-06-30)
  5. #0

       wildwolf

      wil***[email protected]

    1

    table 泛型元素去重, 只要元素支持 == 比较。

    要写成完全的泛型,那么 v==a[i] 改成一个比较函数的指针 equal(v,a[i]):

    function removeRepeated(a)
        for k,v in pairs(a) do
            local count=0
            for j in pairs(a)do count=count+1 end
            for i=k+1,count do
                if v==a[i] then
                    table.remove(a,i)
                end
            end
        end
    end
    local a={"a","d","c","g","d","w","c","a","g","s"}
    removeRepeated(a)
    for k,v in pairs(a) do
           print(k,v)
    end
    wildwolf

       wildwolf

      wil***[email protected]

    8年前 (2018-08-18)
  6. #0

       miku

      mik***iku.com

    24

    排序自定义排序规则时,大体规则是传参数 (a,b),当 return true 时,则 a 排在 b 前,否则相反。

    local a={2,3,5,52,6,74,4}
    table.sort(t, function(a, b) return a>b end)
    for k,v in ipairs(a) do print(v) end
    -- 74 52 6 5 4 3 2
    miku

       miku

      mik***iku.com

    8年前 (2018-09-04)
  7. #0

       凯凯本凯

      kai***[email protected]

    23

    大家注意,函数传参类型为table时,是地址传递而不是值传递!

    代码:

    local function f(x)
      x["writable"] ="written"
    end
    local t={
      ["readonly"]="read",
      ["writable"]="write"
    }
    print("before---------")
    for k,v in pairs(t) do
      print(k,v)
    end
    f(t)
    print("after----------")
    for k,v in pairs (t) do
      print(k,v)
    end

    输出:

    before---------
    readonly  read
    writable  write
    after----------
    readonly  read
    writable  writteny

    不要踩坑了(本人已踩坑,无奈重构代码)!

    凯凯本凯

       凯凯本凯

      kai***[email protected]

    5年前 (2022-02-05)

点我分享笔记

取消

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址
分类导航
  • Python / 数据科学
    • Python 教程
    • Python2.x 教程
    • FastAPI 教程
    • Flask 教程
    • Django 教程
    • NumPy 教程
    • Pandas 教程
    • SciPy 教程
    • Matplotlib 教程
    • Dash 教程
    • Jupyter Notebook 教程
    • Pillow 教程
    • 量化交易
    • R 教程
    • Julia 教程
  • AI / 智能开发
    • AI Agent(智能体)
    • AI(人工智能)
    • AI 应用案例
    • Codex 教程
    • Vibe Coding 教程
    • Claude Code
    • OpenCode
    • Skills(技能)
    • Ollama 教程
    • Hermes Agent
    • DeepSeek Harness
    • Pi Agent
    • AI 数学基础
    • TensorFlow 教程
    • PyTorch 教程
    • Scikit-learn 教程
    • 机器 教程
    • LangChain
    • 自然语言处理 NLP
    • OpenCV 教程
    • Selenium 教程
    • Playwright 教程
  • 前端开发
    • HTML 教程
    • HTML5 教程
    • CSS 教程
    • CSS3 教程
    • JavaScript 教程
    • HTML DOM 教程
    • TypeScript 教程
    • AJAX 教程
    • JSON 教程
    • Tailwind CSS 教程
    • Bootstrap4 教程
    • Bootstrap5 教程
    • Bootstrap6 教程
    • Foundation 教程
    • Vue.js 教程
    • Vue3 教程
    • React 教程
    • Next.js 教程
    • Three.js 教程
    • AngularJS 教程
    • Angular 教程
    • jQuery 教程
    • jQuery UI 教程
    • jQuery EasyUI 教程
    • ECharts 教程
    • Chart.js 教程
    • Highcharts 教程
    • Google 地图 教程
    • SVG 教程
    • Font Awesome 教程
  • 后端开发
    • Node.js 教程
    • Electron 教程
    • PHP 教程
    • Java 教程
    • Go 教程
    • Rust 教程
    • C# 教程
    • Unity 教程
    • Servlet 教程
    • JSP 教程
    • ASP 教程
    • AppML 教程
    • VBScript 教程
    • Swagger 教程
    • RESTful API 教程
    • Docker 教程
    • Linux 教程
    • ZooKeeper 教程
  • 数据库
    • SQL 教程
    • MySQL 教程
    • PostgreSQL 教程
    • SQLite 教程
    • MongoDB 教程
    • Redis 教程
    • Memcached 教程
  • 移动开发
    • Android 教程
    • Flutter 教程
    • Ionic 教程
    • jQuery Mobile 教程
    • Swift 教程
    • Kotlin 教程
  • DevOps / 工程化
    • Git 教程
    • SVN 教程
    • CMake 教程
    • Maven 教程
    • VS Code 教程
    • Obsidian 教程
    • PyCharm 教程
    • Eclipse 教程
    • Markdown 教程
    • LaTeX 教程
  • 编程语言
    • C 教程
    • C++ 教程
    • Zig 教程
    • Scala 教程
    • Ruby 教程
    • Perl 教程
    • Lua 教程
    • Dart 教程
    • 汇编语言 教程
    • Verilog 教程
  • 计算机基础
    • 计算机组成原理
    • 数据结构与算法
    • C 语言数据结构与算法
    • 设计模式
    • Python 设计模式
    • 正则表达式
    • HTTP 教程
    • TCP/IP 教程
    • 网络协议
    • W3C 教程
  • XML / Web Service
    • XML 教程
    • DTD 教程
    • XML DOM 教程
    • XSLT 教程
    • XPath 教程
    • XQuery 教程
    • XLink 教程
    • XPointer 教程
    • XML Schema 教程
    • XSL-FO 教程
    • Web Service 教程
    • WSDL 教程
    • SOAP 教程
    • RSS 教程
    • RDF 教程
  • .NET
    • ASP.NET 教程
    • MVC 教程
    • Razor 教程
    • Web Forms 教程
    • Web Pages 教程
    • PowerShell 教程
  • 网站建设
    • 网站建设指南
    • 浏览器信息
    • 网站主机教程
    • 网站品质

字节 Coding Plan 限时 9.9 元起,支持 Deepseek-V4、GLM-5.3、Doubao-Seed-Evolving、Kimi-K3。
百度 Dumate 百度推出的桌面级 AI 智能体。 输入激活码送 4000 积分
使用文档
Trae AI 原生开发环境,让编程更高效。新用户注册赠2500积分,管理项目,也交付成果。
Advertisement
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.