lua:table
1.习惯上,Lua的下表从1开始,只有这样,才可以使用标准库的函数
--链表 list=nil list={next=list,value="v"} list={next=list,value=88} local l=list while l do print(l.value) l=l.next end --输出88 v
--队列 List={} function List.new() return {first=0,last=-1} end function List.pushleft(list,value) local first=list.first-1 list.first=first list[first]=value end function List.pushright(list,value) local last=list.last+1 list.last=last list[last]=value end function List.popleft(list) local first=list.first if first>list.last then error("list is empty") end local value=list[first] list[first]=nil --to allow garbage collection list.first=first+1 return value end
--遍历table function set(list) local set={} for _,l in pairs(list) do print(l) end end list={"fun","bored","intre"} set(list)
lines={ lua_set=10, lua_get=24, lua_present=48, } --table.sort是对value进行排序 function pairsByKeys(t,f) local a={} for n in pairs(t) do table.insert(a,n) end table.sort(a,f) local i=0 local iter=function() i=i+1 if a[i]==nil then return nil else return a[i],t[a[i]] end end return iter end for name,line in pairsByKeys(lines) do print(name,line) end