table 是 Lua 中唯一的数据结构,其他语言所提供的其他数据结构比如:arrays、records、lists、queues、sets 等都是通过 table 来实现,
数组:
- a={}
- for i=1,1000 do
- a[i]=0
- end
矩阵和多维数组:N行M列
- N=5
- M=5
- mt={} --创建一个矩阵
- for i=1,N do
- mt[i]={} --创建一行
- for j=1,M do
- mt[i][j]=0
- end
- end
- for i=1,N do
- for j=1,M do
- print(i.." "..j..":"..mt[i][j])
- end
- end
链表:
- list=nil --根节点
- list={next=list,value=v} --链表开头插入一个值V的节点
- local l=list
- while l do --遍历这个链表
- print(l.value)
- l=l.next
- end
队列和双端队列:
- List={}
- function List.new() --创建新的List表
- return{first=0,last=-1} --返回第一个元素和最后一个元素
- end
- function List.pushleft(list,value) --左边插入
- local first=list.first-1
- list.first=first
- list[first]=value
- end
- function List.pushright(list,value) --右边插入
- local last=list.last+1
- list.last=last
- list[last]=value
- end
- function List.popleft(list) --左边删除
- local first=list.first
- if first>list.last then error("list is empty") end
- local value=list[first]
- list[first]=nil
- list.first=first+1
- return value
- end
- function List.popright(list) --右边删除
- local last=list.last
- if list.first>last then error("list is empty") end
- local value=list[last]
- list[last]=nil
- list.last=last-1
- return value
- end
集合和包:
- function Set(list) --构造集合
- local set={}
- for l in ipairs(list) do
- set[l]=true
- end
- return set
- end
- reserved=Set{"while","end","function","local"}
栈:用做字符串缓冲,在栈的底部用来保存已经生成的大的字符串,而小的串从栈定入栈。
- function newStack()
- return {""}
- end
- function addString(stack,s)
- table.insert(stack,s) --入栈
- --table.remove(stack) --出栈
- end
- local s=newStack()
- for line in io.lines("2.txt") do
- addString(s,line .. "\n")
- end
- s=table.concat(s,"\n")
- print(s)