Lua中的表(table)
两个表之间赋值,相当于引用,修改一个表中的值,另一个表也对应修改。如果将其中一个表赋值为nil,另一个表中信息不受影响,真的想要释放地址,必须将所有引用表赋值为nil
mytable={} --Defined a table
mytable[1] = "Lua"
mytable["name"] = "Keith"
--~ Asign the mytable value to the newtable
--~ The mytable and newtable point to the same address
newtable = mytable
--~ The output result is the same
print(newtable[1])
print(mytable[1])
--~ Change one , the other one will change
newtable[1] = "c#"
print(newtable[1])
print(mytable[1])
--~ clear one value does not affect other
mytable = nil
print(newtbale.name)
Table的连接
我们可以使用concat() 输出一个列表中元素连接成的字符串
fruits = {"banana", "orange", "pear", "apple"}
-- Returns the string after the table is joined
print("The string is connected",table.concat(fruits))
--Specifiy connecting string
print("The string is connected",table.concat(fruits,","))
--Specify the index to join table
print("The string is connected",table.concat(fruits,",",2,3))
Table的插入和移除
fruits = {"banana", "orang", "apple"}
--insert at the end
table.insert (fruits, "mango")
print("Elements with an index of 4 are", fruits[4])
--insert at the index of 2
table.insert ( fruits, 2, "grapes")
print("Elements with an index of 2 are", fruits[2])
print("The last element is ", fruits[5])
table.remove(fruits)
print("remove the last one element", fruits[5])
Table排序
fruits = { "banana", "orange", "apple", "grapes" }
print("Before ordering")
for k,v in ipairs(fruits) do
print(k,v)
end
table.sort(fruits)
print("After ordering")
for k,v in ipairs(fruits) do
print(k,v)
end
Lua中的元表(metatable)
借用 菜鸟教程里面的话来讲,元表的作用就是用来将两个表关联,对两个表进行操作。
有两个很重要的函数来处理元素:
- setmetatable(table,metatable):对指定table设置元表(metatable),如果元表中存在__metatable(两个"_")键值,setmetatable会失败
- getmetatable(table):返回对象的元表(metatable)
Example:
mytable = {} --ordinary table
mymetatable = {} --metatable
setmetatable(mytable,mymetatable) --把mymetatable设为mytable的元表
--simple method
mytable=setmetatable({},{})
__index 元方法
当你通过键来访问table的时候,如果这个键没有值,那么Lua就会寻找该table的metatable(假定有metatable)中的__index键。通俗来讲就是定义一个常量表,通过引用的方式来调用其中的值。
other = { name = "Keith" }
tab1 = setmetatable{ {}, { __index = other })
print(tab1.foo) --output Keith