Lua丨table、boolean、字符串组合

版权声明:欢迎转载,转载请注明出处 https://blog.csdn.net/weixin_38239050/article/details/82428373

table

table除了菜鸟教程上的示例,还可当作字典来使用。下面展示了当做字典、数组的方法,和如何遍历table、增删修改table

table出了如下功能,在引用上需要注意:

tableA={“1”,“2”,“3”}

tableB=tablea

此时tableA=nil   只是tableA这个表销毁了,但其中存储的数据还没有被销毁,访问tableB仍可访问该内存。只有当引用该内存的变量都被销毁,该内存才会被回收

--table当做字典使用
mytable={Key1=100,Key2="value2"}
print(mytable.Key1)
mytable.Key1=nil
mytable=nil

--table当做数组使用   Lua中索引从1开始,C#中从零开始
mytable2={"a","b","c"}
print(mytable2[1])

--遍历table,key和val也可写为K,V
for key,val in pairs(mytable2) do
	print(key..":"..val)
end

--table表的添加
mytable3={}
mytable3.key1="10"
print(mytable3.key1)
mytable3[2]="20"
print(mytable3[2])

--table表的修改
mytable3[2]="30"

--table表的移除:移除2之后,并不意味着3会移到2位置,此时table序号就不连续了,3还在3的位置
mytable3[100]="apple"
mytable3[2]=nil
mytable3=nil




>lua -e "io.stdout:setvbuf 'no'" "table.lua" 
100
a
1:a
2:b
3:c
10
20
>Exit code: 0

table如何除了菜鸟教程上讲解的插入,还有如下方法

mytable={}
mytable[#mytable+1]="Lua"
print(mytable[#mytable])

table移除

--移除mytable的最后一位
table.remove(mytable)

--移除指定位的键值对,后面的键值对会前移
table.remove(mytable,2)

boolean

boolean 类型只有两个可选值:true(真) 和 false(假),Lua 把 false 和 nil 看作是"假",其他的都为"真":

“其他都为真”意味着即使if10,也可输出a

mytable={Key1="value1",Key2="value2"}
print(mytable.Key1)
mytable.Key1=nil
mytable=nil

if 10 then
print("a")
end

字符串组合

Lua中用 .. 两个点将两个字符串组合成一个,数字是不可以组拼的

str1="2"
str2="8"
print(str1..str2)
print(str1+str2)


>lua -e "io.stdout:setvbuf 'no'" "table.lua" 
28
10
>Exit code: 0

猜你喜欢

转载自blog.csdn.net/weixin_38239050/article/details/82428373