Lua 常用数据结构
来源:互联网 发布:php array remove key 编辑:程序博客网 时间:2024/05/16 07:48
Lua中的table不是一种简单的数据结构,它可以作为其它数据结构的基础。如数组、记录、线性表、队列和集合等,在Lua中都可以通过table来表示。
一、数组
在lua中通过整数下标访问表中的元素即可简单的实现数组。并且数组不必事先指定大小,大小可以随需要动态的增长。
a = {}for i = 1,100 doa[i] = 0endprint("The length of array 'a' is " .. #a)squares = {1, 4, 9, 16, 25}print("The length of array 'a' is " .. #squares)
在Lua中习惯上数组的下表从1开始,Lua的标准库与此习惯保持一致,因此如果你的数组下标也是从1开始你就可以直接使用标准库的函数,否则就无法直接使用。
二、二维数组
Lua中主要有两种表示矩阵的方法,第一种是用数组的数组表示。也就是说一个表的元素是另一个表。
local N = 3local M = 3mt = {}for i = 1,N domt[i] = {}for j = 1,M domt[i][j] = i * jendendmt = {}for i = 1, N dofor j = 1, M domt[(i - 1) * M + j] = i * jendend
三、链表
Lua中用tables很容易实现链表,每一个节点是一个table,指针是这个表的一个域,并且指向另一个节点(table)。例如,要实现一个只有两个域:值和指针的基本链表,代码如下:
list = nilfor i = 1, 10 dolist = { next = list ,value = i}endlocal l = listwhile l do --print(l.value)l = l.nextend
四、队列与双向队列
虽然可以使用Lua的table库提供的insert和remove操作来实现队列,但这种方式实现的队列针对大数据量时效率太低,有效的方式是使用两个索引下标,一个表示第一个元素,另一个表示最后一个元素。
List = {}--创建function List.new()return {first = 0,last = -1}end--队列头插入function List.pushFront(list,value)local first = list.first - 1list.first = firstlist[first] = valueend--队列尾插入function List.popFront(list)local first = list.firstif first > list.last thenerror("List is empty")endlocal value = list[first]list[first] = nillist.first = first + 1return valueendfunction List.popBack(list)local last = list.lastif list.first > last thenerror("List is empty")endlocal value = list[last]list[last] = nillist.last = last - 1 return valueend--测试代码local testList = {first = 0,last = -1}local tableTest = 12List.pushFront(testList,tableTest)print( List.popFront(testList))
五、栈
简单实现堆栈功能,代码如下:
local stackMng = {}stackMng.__index = stackMngfunction stackMng:new()local temp = {}setmetatable(temp,stackMng)return tempendfunction stackMng:init()self.stackList = {}endfunction stackMng:reset()self:init()endfunction stackMng:clear()self.stackList = {}endfunction stackMng:pop()if #self.stackList == 0 thenreturnendif self.stackList[1] thenprint(self.stackList[1])endreturn table.remove(self.stackList,1)endfunction stackMng:push(t)table.insert(self.stackList,t)endfunction stackMng:Count()return #self.stackListend--测试代码object = stackMng:new()object:init()object:push(1)object:pop()
六、集合
在Lua中用table实现集合是非常简单的,见如下代码:
reserved = {["while"] = true, ["end"] = true,["function"] = true, ["local"] = true,}for k,v in pairs(reserved) doprint(k,"->",v)end
1 0
- Lua 常用数据结构
- 细说Lua常用数据结构
- lua中的数据结构-table常用函数库
- Lua数据结构
- lua数据结构
- Lua数据结构
- lua 数据结构
- Lua 数据结构
- Lua数据结构。
- lua数据结构
- Lua 常用
- lua常用
- Lua常用
- lua的数据结构
- Lua的数据结构
- lua的数据结构 -- 数组
- lua的数据结构 -- 链表
- lua的数据结构 -- 队列
- Hibernate入门
- SSH
- gcc编译出现 undefined reference to 的问题
- php static 静态属性 静态方法
- 对Android系统 root的理解
- Lua 常用数据结构
- Excel导出
- 产品类的经验分享
- mysql命令行操作
- hbase shell删除键不听使唤
- nutch的抓取目录解释
- Zero Clipboard js+swf实现的复制功能使用方法
- android 自定义ProgressBar
- *【Wikioi】1983-等式问题