微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

lua学习笔记 4 迭代法遍历 table,当Table中含Table时,递归输出

迭代法遍历 table,当Table中含Table时,递归调用。打印Table中 K,V值
@H_502_6@


@H_502_6@

通过type(arg) 判断当前类型@H_502_6@


@H_502_6@

@H_502_6@

table1 = {
	name = "Android Developer",email = "[email protected]",url = "http://blog.csdn.net/hpccn",quote = [[
	There are 
	10 types of pepole
	who can understand binary.
	]],--多行文字
	embeddedTab = {
		em1 = xx,x =0,{x =1,y =2 } -- 再内嵌table
	}-- 内嵌table 
}

tab = "    "
function print_table(t,i)
	local indent ="" -- i缩进,当前调用缩进
	for j = 0,i do 
		indent = indent .. tab
	end
	for k,v in pairs(t) do 
		if (type(v) == "table") then -- type(v) 当前类型时否table 如果是,则需要递归,
			print(indent .. "< " .. k .. " is a table />")
			print_table(v,i + 1) -- 递归调用
			print(indent .. "/> end table ".. k .. "/>")
		else -- 否则直接输出当前值
				
			print(indent .. "<" .. k .. "=" .. v.."/>")
		end
	end
end


print_contents(table1,0)

@H_502_6@


@H_502_6@

输出结果:@H_502_6@

for k,v in pairs(table) do 这样的遍历顺序并非是table中table的排列顺序,而是根据table中key的hash值排序来遍历的。
@H_502_6@

与Java中 HashMap,C++中的Map相似。@H_502_6@

@H_502_6@

    <name=Android Developer/>
    <quote=	There ar 
	10 types of pepole
	who can understand binary.
	/>
    <url=http://blog.csdn.net/hpccn/>
    < embeddedTab is a table />
        < 1 is a table />
            <y=2/>
            <x=1/>
        /> end table 1/>
        <x=0/>
    /> end table embeddedTab/>
    <[email protected]/>


@H_502_6@


@H_502_6@ 学习重点: 

@H_502_6@

1 数据类型的判断: type()@H_502_6@

lua语言中的数据类型主要有:nil、number、string、function、table、thread、boolean、userdata。@H_502_6@

需要确定一个变量的类型时,可以使用内置函数type获取,如下:
@H_502_6@

type(“hello world”);              ---->string
type(type);                            ---->function
type(3.1415);                       ---->number
type(type(type));                  ---->string


@H_502_6@


@H_502_6@

2 迭代法 @H_502_6@

pairs 迭代全部的项@H_502_6@

ipairs 迭代以数字做键值的项,且从1 开始@H_502_6@

@H_502_6@

for k,v in pairs(t) do 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐