Lua数组表的应用

–[[ lua表处理 ]]–
alice = {}
alice[ "name" ] = “liuhui”
alice[ "phone" ] = “15157121639″
alice[ "address" ] = “杭州江干”
alice[ "city" ] = “杭州”
print( alice["name"] )
print( alice["city"] )
print( alice.city )
–[[ 采用{} 处理赋值的时候每条语句后面都有, ]]–
mytab =
{
	["name"] = “liuhui”,
	["xingbie"] = “男”,
	["age"] =24,
}
mytab1 =
{
	name = “xiaohui”,
	email = “liuhui331234958@126.com”,
}
print( mytab.name )
print( mytab1.email )
–[[ 把表当作数组使用 ]]–
tab1 =
{
	“abc”,
	“def”,
	“mok”,
	“liuhui”,
}
tab2 =
{
	[1] = “abc”,
	[2] = “def”,
	[3] = “mok”,
}
–[[ lua中数组是从1开始计算 ]]–
–[[ print( tab1[1] ) ]]–
print(“tab1打印..”)
len = #tab1
for i=1, len do
	print( tab1[i] )
	i = i + 1
end
print(“tab2打印..”)
len = #tab2
for i=1, len do
	print( tab2[i] )
	i = i + 1
end
tab1[5] = “hehe”
print( tab1[4] )
print( tab1[5] )
–[[ 更加标准的数组添加元素做法 table.insert 如果不用第二个参数,添加到末尾 ]]–
table.insert( tab1, 6, “nihao” )
print( tab1[6] )
–[[ 从数组中删除元素table.remove,与table.insert很相似 ]]–
print( “删除tab1[1]” )
print( “删除前长度为:”..#tab1..”内容为” )
for i=1, #tab1 do
	print( tab1[i] )
end
table.remove( tab1, 1 )
print( “删除后长度为:”..#tab1 )
–[[ 这里显示的是原数组中的第二个元素 ,默认向前移一位]]–
for i=1, #tab1 do
print( tab1[i] )
end
table.remove( tab1 ) –[[ 不带删除标号的删除默认为最后一个元素删除 ]]–
print( “删除后长度为:”..#tab1 )
for i=1, #tab1 do
	print( tab1[i] )
end
–[[ 数组排序 ]]–
array =
{
	“liuhui”,
	“haha”,
	“abc”,
	“zero”,
}
table.sort( array )
for i=1, #array do
	print( array[i] )
end
–[[ 数组中添加函数名 ]]–
function prtmsg( str )
	local msg = str
	return msg
end
function prttype( str )
	local ret = “”
	if( type(str) == “string” ) then
		ret = “string”
		return ret
	elseif( type(str) == “double” ) then
		ret = “double”
		return ret
	else
		return ret
	end
end
util = {}
util.func = prtmsg
util.type = prttype
mstr = “hello”
print( “message type:”..util.type(mstr) )
print( “message info:”..util.func(“hello”) )

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页