Lua 表有几种形式用得比较多,
一种是sequence, 一种是table, 还有一种是list.
1. sequence指没有气泡的一些元素. 例如{"hello", "nihao","yes"}是一个sequence, 索引为1开始的自增数字.
但是{"hello", "nihao", nil, "yes"} 不算序列. 因为中间有个nil气泡.
> t = {"hello", "nihao", nil, "yes"}
> for i,v in ipairs(t) do
>> print (i,v)
>> end
1 hello
2 nihao
使用ipairs遍历t表只输出前两个值
2. table指key, value形式存储的表.
例如tbl = {a="nihao", b=nil, c="hello", d="yes"}
使用pairs可以遍历这个表, 会忽略value=nil的元素.
> tbl = {a="nihao", b=nil, c="hello", d="yes"}
> for k,v in pairs(tbl) do
>> print(k,v)
>> end
a nihao
d yes
c hello
其实pairs是调用了next(_s, _var)函数, 所以我们知道generic for语法的话, 可以直接使用next来写for循环.
> for k,v in next, tbl do
>> print(k,v)
>> end
a nihao
d yes
c hello
直接调用next的效果
> =next(tbl,nil)
a nihao
> return next(tbl,"a")
d yes
> return next(tbl,"d")
c hello
> return next(tbl,"c")
nil
pairs原型
function pairs(t)
return next, t, nil
end
3. 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}
>> end
a
b
c
d
e
^D
> l = list
> while l do
>> print(l.value)
>> l = l.next
>> end
e
d
c
b
a
链表的generic for循环函数用法 .
iterator函数, 函数中不保存state值. 所以也称为stateless iterator
> function getnext(list, node)
>> if not node then
>> return list
>> else
>> return node.next
>> end
>> end
factory 函数
> function traverse(list)
>> return getnext, list, nil
>> end
使用io.lines生成链表
> list = nil
> for line in io.lines() do
>> list = {val = line, next = list}
>> end
hello
yes
digoal
hehe
^D
使用factory函数循环
> for node in traverse(list) do
>> print (node.val)
>> end
hehe
digoal
yes
hello
直接使用stateless iterator函数和state值循环
> for node in getnext,list do
print (node.val)
end
hehe
digoal
yes
hello
4.
table.pack 和table.unpack
table.pack把多个值打包成一个序列表.
> a = table.pack("a","b","c","nil")
> for i,v in ipairs(a) do
>> print (i,v)
>> end
1 a
2 b
3 c
4 nil
table.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
时间: 2024-09-16 02:00:35