Lua 中 table 库函数 insert、remove、sort
2015-06-22 11:51
706 查看
Lua 中 table 库函数 insert、remove、sort
一、 insert 插入do --> table.insert 插入函数 tab = {"a", "c", "d", "b"} -- 在 tab 末尾添加 元素 "e" table.insert(tab, "e") -- 在 tab 末尾添加 元素 "f" print(table.insert(tab, "f")) -- 输出结果: 无输出,即 table.insert 函数无返回值 -- 在 tab 第 2 个元素后 添加 "g" table.insert(tab, 2, "g") for i,v in ipairs(tab) do print(i,v) end -- 输出结果: -- 1 a -- 2 g -- 3 c -- 4 d -- 5 b -- 6 e -- 7 f end
二、 remove 移除
do --默认移除表中最后一个元素 --table.remove(t) -- 移除表中第 index 个元素 -- table.remove(t, index) t = {"a", "b", "c", "d"} -- 默认移除 最后一个元素 table.remove(t) -- 移除 表 t 中 第 1 个元素 table.remove(t, 1) for k,v in pairs(t) do print(k,v) end -- 输出结果: -- 1 b -- 2 c end
三、sort 排序
do tab = {"d", "b", "a", "c"} -- 默认按照升序对 表 tab 进行排序 table.sort( tab ) for i,v in ipairs(tab) do print(i,v) end -- 输出结果: -- 1 a -- 2 b -- 3 c -- 4 d tab2 = {"d", "b", "a", "c"} -- 定义一个降序排序的函数 function sortfunction( a, b ) return a > b end -- 将 tab2 按照 sortfunction 函数进行排序 -- tab2 会按照降序进行排序 table.sort( tab2, sortfunction ) for i,v in ipairs(tab2) do print(i,v) end --输出结果: -- 1 d -- 2 c -- 3 b -- 4 a end
相关文章推荐
- Lua 与C/C++ 交互系列:Userdata知识点翻译
- Lua 中 table 库函数 table.concat 连接 函数
- Lua 与C/C++ 交互系列: Lua调用C/C++函数(4-2)
- Ubuntu14.04 lua游戏引擎Love安装
- lua中的成员变量和成员函数及其静态成员函数
- lua文件包含
- Lua 与C/C++ 交互系列: Lua调用C/C++函数(4-1)
- Lua 与C/C++ 交互系列: Lua调用C/C++函数(3)
- Lua 与C/C++ 交互系列: Lua调用C/C++函数(2).
- Lua 与C/C++ 交互系列: Lua调用C/C++函数(1).
- Lua 与C/C++ 交互系列:通过C++调用Lua函数(2)
- Lua cjson模块编译笔记及错误解决方法
- Lua 与C/C++ 交互系列:通过C调用Lua函数(1)
- Lua相关的扩展库
- leetcode--Evaluate Reverse Polish Notation
- LeetCode 之 Evaluate Reverse Polish Notation — C++ 实现
- 编译 lua cjson模块
- lua学习笔记_注释、基本数据类型、if语句
- lua学习1
- lua (一) : mac终端下使用 brew安装lua