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
endfor 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}
endlocal 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}
endfunction List.pushFront(list,value)
list.first=list.first-1
list[ list.first ]=value
endfunction List.pushBack(list,value)
list.last=list.last+1
list[ list.last ]=value
endfunction 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
endfunction 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
endlp=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
endfunction 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
endlocal s=table.concat(t,"\n") --将table t 中的字符串连接起来
您可能感兴趣的文章:
- Lua中使用table实现的其它5种数据结构
- Lua中使用table实现的其它5种数据结构
- Lua中使用table实现的其它5种数据结构(数组、链表、队列、集合和包、StringBuild)
- lua数据结构之table的内部实现
- lua数据结构之table的内部实现
- 使用js实现对table的动态添加、删除和更新
- 使用单个innodb表,实现锁,防止游戏被刷物品或者其它资源!
- 使用单个innodb表,实现锁,防止游戏被刷物品或者其它资源!
- [Android]使用二维表格实现 TableLayout 跨行(转)
- 使用单个innodb表,实现锁,防止游戏被刷物品或者其它资源!
- 数据结构的应用——使用栈实现字符串括号匹配检查
- 使用jquery为table动态添加行的实现代码
- 数据结构的应用——使用栈实现十进制到其他(2、8、16)进制的转换
- VS2005中TableAdapter中实现动态查询并使用LIKE的方法整理
- 数据结构的应用——使用栈和递归实现Hanoi问题求解
- 使用Vaadin的SQLContainer和table实现批量数据的快速浏览
- 数据结构 链表的lua实现 仿照C++中list 实现
- ASP.NET中使用MultiView和View以及Menu实现Tablecontrol的功能
- 数据结构的应用——使用栈实现任意迷宫的求解
- 在网上看到使用PHP实现常见的数据结构和算法