Lua中使用table实现的其它5种数据结构

lua中的table不是一种简单的数据结构,它可以作为其他数据结构的基础,如:数组,记录,链表,队列等都可以用它来表示。

1、数组

在lua中,table的索引可以有很多种表示方式。如果用整数来表示table的索引,即可用table来实现数组,在lua中索引通常都会从1开始。


--二维数组

n=10 m=10

arr={}

for i=1,n do

     arr[i]={}

   for j=1,m do

      arr[i][j]=i*j

   end

end

for i=1, n do    for j=1, m do       if(j~=m) then  io.write(arr[i][j].." ")       else print(arr[i][j])       end    end end

2、链表

在lua中,由于table是动态的实体,所以用来表示链表是很方便的,其中每个节点都用table来表示。


list = nil

for i = 1, 10 do

    list = { next = list, value = i}

end

local l = list while l do     print(l.value)     l = l.next end

3、队列与双端队列

在lua中实现队列的简单方法是调用table中insert和remove函数,但是如果数据量较大的话,效率还是很慢的,下面是手动实现,效率快许多。


List={}

function List.new()    return {first=0, last=-1} end

function List.pushFront(list,value)    list.first=list.first-1    list[ list.first ]=value end

function List.pushBack(list,value)    list.last=list.last+1    list[ list.last ]=value end

function List.popFront(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.popBack(list)    local last=list.last    if last<list.first then error("List is empty!")    end    local value =list[last]    list[last]=nil    list.last=last-1    return value end

lp=List.new() List.pushFront(lp,1) List.pushFront(lp,2) List.pushBack(lp,-1) List.pushBack(lp,-2) x=List.popFront(lp) print(x) x=List.popBack(lp) print(x) x=List.popFront(lp) print(x) x=List.popBack(lp) print(x) x=List.popBack(lp) print(x) --输出结果 -- 2 -- -2 -- 1 -- -1 -- lua:... List is empty!

4、集合和包

在Lua中用table实现集合是非常简单的,见如下代码:


    reserved = { ["while"] = true, ["end"] = true, ["function"] = true, }

    if not reserved["while"] then

        --do something

    end

在Lua中我们可以将包(Bag)看成MultiSet,与普通集合不同的是该容器中允许key相同的元素在容器中多次出现。下面的代码通过为table中的元素添加计数器的方式来模拟实现该数据结构,如:


function insert(Bag,element)

    Bag[element]=(Bag[element] or 0)+1

end

function remove(Bag,element)    local count=Bag[element]    if count >0 then Bag[element]=count-1    else Bag[element]=nil    end end

5、StringBuild

如果在lua中将一系列字符串连接成大字符串的话,有下面的方法:

低效率:


local buff=""

for line in io.lines() do

   buff=buff..line.."\n"

end

高效率:


local t={}

for line in io.lines() do    if(line==nil) then break end    t[#t+1]=line end

local s=table.concat(t,"\n")  --将table t 中的字符串连接起来

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。