Lua编程示例(三):稀疏表、双端队列、格式化输出、表和循环表的格式化输出
a={} fori=1,10do a[i]={} forj=0,10do if(i%2==0)then a[i][j]=0 end end end print(a[9][10]) print(a[10][10]) print() --双端队列 List={} functionList.new() return{first=0,last=-1} end functionList.pushleft(list,value) localfirst=list.first-1 list[first]=value list.first=first end functionList.pushright(list,value) locallast=list.last+1 list[last]=value list.last=last end functionList.popleft(list) localfirst=list.first if(first>list.last)then error("listisempty") end localres=list[first] list[first]=nil list.first=list.first+1 returnres end functionList.popright(list) locallast=list.last iflast<firstthen error("thelistisempty") end localres=list[last] list[last]=nil list.last=list.last-1 returnres end functionList.display(list) if(list.first>list.last)then error("thelistisempty",2) end fori=list.first,list.lastdo print(list[i]) end end mylist=List.new() List.pushleft(mylist,12) List.pushleft(mylist,"00") List.pushright(mylist,34) List.pushright(mylist,56) List.display(mylist) print() functionnewStack() return{""} end functionserialize(o) iftype(o)=="number"then io.write(o) elseiftype(o)=="string"then --不要手动加入引号,否则会有边际效应 io.write(string.format("%q",o)) elseiftype(o)=="table"then io.write("{\n") fori,vinpairs(o)do io.write(""..i.."=") serialize(v) io.write(",\n") end io.write("}\n") end end serialize(123) print() serialize("112233") print() tab={a=11,haha="www",c=333} serialize(tab) functionbasicSerialize(o) iftype(o)=="number"then returntostring(o) else returnstring.format("%q",o) end end functionsave(name,value,saved) saved=savedor{}--参数未传入的初始化 io.write(name,"=") iftype(value)=="number"ortype(value)=="string"then io.write(basicSerialize(value),"\n") elseiftype(value)=="table"then ifsaved[value]then io.write(saved[value],"\tcircle\n") else saved[value]=name io.write("{}\n") fork,vinpairs(value)do localfieldname=string.format("%s[%s]",name, basicSerialize(k)) save(fieldname,v,saved) end end else error("cannotsavea"..type(value)) end end a={x=1,y=2;{3,4,5}} a[2]=a--循环表 a.z=a[1]--共享子表 save('a',a)
运行结果:
nil 0 00 12 34 56 123 "112233" { a=11, c=333, haha="www", } a={} a[1]={} a[1][1]=3 a[1][2]=4 a[1][3]=5 a[2]=acircle a["y"]=2 a["x"]=1 a["z"]=a[1]circle