本文共 2351 字,大约阅读时间需要 7 分钟。
> t = {"hello", "nihao", nil, "yes"}> for i,v in ipairs(t) do>> print (i,v)>> end1 hello2 nihao使用ipairs遍历t表只输出前两个值
> tbl = {a="nihao", b=nil, c="hello", d="yes"}> for k,v in pairs(tbl) do>> print(k,v)>> enda nihaod yesc hello其实pairs是调用了next(_s, _var)函数, 所以我们知道generic for语法的话, 可以直接使用next来写for循环.
> for k,v in next, tbl do>> print(k,v)>> enda nihaod yesc hello直接调用next的效果
> =next(tbl,nil)a nihao> return next(tbl,"a")d yes> return next(tbl,"d")c hello> return next(tbl,"c")nilpairs原型
function pairs(t) return next, t, nilend3. list指链表.
> a = {"hello", next=nil} -- 链表的头> a = {"nihao", next=a} -- next指向头> a = {"yes", next=a} -- next指向上层> a = {"ok", next=a} -- next指向上层打印链表的值.
> print(a[1])ok> print(a.next[1])yes> print(a.next.next[1])nihao> print(a.next.next.next[1])hello生成一个链表和输出链表的值的例子
> list = nil> for line in io.lines() do>> list = {next=list, value=line}>> endabcde^D> l = list> while l do>> print(l.value)>> l = l.next>> endedcba
> function getnext(list, node)>> if not node then>> return list>> else>> return node.next>> end>> endfactory 函数
> function traverse(list)>> return getnext, list, nil>> end使用io.lines生成链表
> list = nil> for line in io.lines() do>> list = {val = line, next = list}>> endhelloyesdigoalhehe^D使用factory函数循环
> for node in traverse(list) do >> print (node.val)>> endhehedigoalyeshello直接使用stateless iterator函数和state值循环
> for node in getnext,list do print (node.val)endhehedigoalyeshello
table.pack把多个值打包成一个序列表.> a = table.pack("a","b","c","nil")> for i,v in ipairs(a) do>> print (i,v)>> end1 a2 b3 c4 niltable.unpack把序列表解散成多值返回.> x,y,z = table.unpack(a)> print(x,y,z)a b c> x,y,z = table.unpack({a=1,b=2,c=3}) -- unpack不处理非序列表元素.> print(x,y,z)nil nil nil> x,y,z = table.unpack({a=1,b=2,c=3,"h","j","k"}) -- 只解包序列部分> print(x,y,z)h j k
转载地址:http://jymum.baihongyu.com/