--主要是new/pushlast/popfirst List = {} function() return {first=0, last=-1} end functionList.pushfirst(list, value) local first = list.first-1 list.first = first list[first] = value end functionList.pushlast(list, value) local last = list.last+1 list.last = last list[last] = value end functionList.popfirst(list) local first = list.first if first>list.last thenerror('list is empty') end local value = list[first] --允许垃圾收集 list[first] = nil list.first = first+1 return value end functionList.poplast(list) local last = list.last if list.first>last thenerror('list is empty') end local value = list[last] list[last] = nil list.last = last-1 return value end
4 集合、包
将集合元素作为索引放入table中;则对任意值都无需搜索table,直接索引即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
functionSet(list) local set = {} for _, l inipairs(list) do set[l] = trueend return set end
functionBag(list) local bag = {} for _, l inipairs(list) do bag[l] = 1end return bag end functioninsert(bag, element) bag[element] = (bag[element] or0)+1 end functionremove(bag, element) local count = bag[element] --递减其计数器 bag[element] = (count and count>1) and (count-1) ornil end
--读文件的正确姿势 local t = {} for line inio.linesdo t[#t+1] = line end --欺骗concat,在结尾处添加换行 t[#t+1] = '' local s = table.concat(t, 'n')
--“汉诺塔”实现 functionaddString(stack, s) stack[#stack+1] = s for i = #stack-1, 1, -1do if #stack[i] > #stack[i+1] then break end --如果新字符串更大,则连接、压缩栈 stack[i] = stack[i] .. stack[i+1] stack[i+1] = nil end end