--二维数组
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
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
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 lastlist.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!
在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
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 中的字符串连接起来