Lua基础:数据结构

        table 是 Lua 中唯一的数据结构,其他语言所提供的其他数据结构比如:arrays、records、lists、queues、sets 等都是通过 table 来实现,

数组:

  1. a={}
  2. for i=1,1000 do
  3.     a[i]=0
  4. end

矩阵和多维数组:N行M列

  1. N=5
  2. M=5
  3.  
  4. mt={}      --创建一个矩阵
  5.  
  6. for i=1,N do
  7.     mt[i]={}    --创建一行
  8.     for j=1,M do
  9.         mt[i][j]=0
  10.     end
  11. end
  12.  
  13. for i=1,N do
  14.     for j=1,M do
  15.         print(i.." "..j..":"..mt[i][j])
  16.     end
  17. end

链表:

  1. list=nil         --根节点
  2. list={next=list,value=v}   --链表开头插入一个值V的节点
  3. local l=list
  4. while l do              --遍历这个链表
  5.     print(l.value)
  6.     l=l.next
  7. end

队列和双端队列:

  1. List={}
  2.  
  3. function List.new()          --创建新的List表
  4.     return{first=0,last=-1}  --返回第一个元素和最后一个元素
  5. end
  6.  
  7. function List.pushleft(list,value)         --左边插入
  8.     local first=list.first-1
  9.     list.first=first
  10.     list[first]=value
  11. end
  12.  
  13. function List.pushright(list,value)   --右边插入
  14.     local last=list.last+1
  15.     list.last=last
  16.     list[last]=value
  17. end
  18.  
  19. function List.popleft(list)       --左边删除
  20.     local first=list.first
  21.     if first>list.last then error("list is empty") end
  22.     local value=list[first]
  23.     list[first]=nil
  24.     list.first=first+1
  25.     return value
  26. end
  27.  
  28. function List.popright(list)  --右边删除
  29.     local last=list.last
  30.     if list.first>last then error("list is empty") end
  31.     local value=list[last]
  32.     list[last]=nil
  33.     list.last=last-1
  34.     return value
  35. end

集合和包:

  1. function Set(list)      --构造集合
  2.     local set={}
  3.     for l in ipairs(list) do
  4.          set[l]=true
  5.     end
  6.     return set
  7. end
  8.  
  9. reserved=Set{"while","end","function","local"}

栈:用做字符串缓冲,在栈的底部用来保存已经生成的大的字符串,而小的串从栈定入栈。

  1. function newStack()
  2.     return {""}
  3. end
  4.  
  5. function addString(stack,s)
  6.     table.insert(stack,s)             --入栈
  7.     --table.remove(stack)            --出栈
  8. end
  9.  
  10. local s=newStack()
  11.  
  12. for line in io.lines("2.txt") do
  13.     addString(s,line .. "\n")
  14. end
  15.  
  16. s=table.concat(s,"\n")
  17. print(s)

猜你喜欢

转载自blog.csdn.net/QQhelphelp/article/details/88075101
今日推荐