一、Lua數據結構
Lua中table不是一種簡單地數據結構,它可以作爲其它數據結構的基礎。其它語言提供的數據結構,如數組、線性表、隊列和集合等。
這些在lua都可以通過table來實現出來
1、數組
local a = {}
for i=1,10 do
a[i] = i
end
注意: lua中數組的key必須從1開始,如下:
local a = {}
for i=-3,5 do
print(i)
a[i] = i
end
for k,v in ipairs(a) do
print(k,'=',v)
end
2、棧
local List = {}
function List.new()
return {first=0,last=-1}
end
function List.pf(list,value)
local first = list.first - 1
list.first = first
list[first] = value
end
function List.popf(list)
local first = list.first
if first > list.last then error("empty") end
local value = list[first]
list[first] = nil
list.first = list.first + 1
return value
end
local list
list = List.new()
List.pf(list,'a')
List.pf(list,'b')
List.pf(list,'c')
print(List.popf(list))
print(List.popf(list))
print(List.popf(list))
for k,v in pairs(list) do
print(k,v)
end
3、隊列
local Queue = {}
function Queue.new()
return {first=0,last=1}
end
function Queue.insertQueue(q,v)
local f = q.first + 1
q.first = f
q[f] = v
end
function Queue.outQueue(q)
local l = q.last
if l>q.first then error("empty") end
local v = q[l]
q[l] = nil
q.last = q.last + 1
return v
end
local Queue = {}
function Queue.new()
return {index=1}
end
function Queue.insertQueue(q,v)
local i = #q
if q.index > 1 and i==0 then
q.index = 1
end
i = i + 1
q[i] = v
end
function Queue.outQueue(q)
local index = q.index
local i = #q
if i < index then error("empty") end
local v = q[index]
q[index] = nil
q.index = q.index + 1
return v
end
local q = {}
q = Queue.new()
Queue.insertQueue(q,'a')
Queue.insertQueue(q,'b')
print(Queue.outQueue(q))
print(Queue.outQueue(q))
4、集合
function set(l)
local set = {}
for k,v in pairs(l) do
set[v] = true
end
return set
end
local s = {'a','b','c','d'}
local set = set(s)
for k,v in pairs(set) do
print(k,'=',v)
end
local i = 'a3'
print(set[i])