-- test 测试lua数据
array = {}
for i = -2,2 do
array[i] = i*2
end
for i=-2,2 do
print(array[i])
end
-- 测试多维数组
print("test for mutiArray")
mutiArray={}
for i=1,3 do
mutiArray[i]={}
for j=1,3 do
mutiArray[i][j]=i*j
end
end
-- 访问多维数组
for i=1,3 do
for j=1,3 do
print(mutiArray[i][j])
end
end
-- 测试迭代器
print("test for iterator")
arrayiter = {"liugao","liugao2"}
for key,value in pairs(arrayiter)
do
print(key,value)
end
-- 测试无状态的迭代器
function square(iteratorMaxCount,currentNumber)
if currentNumber<iteratorMaxCount
then
currentNumber =currentNumber + 1
return currentNumber,currentNumber*currentNumber
end
end
for i,n in square,3,0
do
print(i,n)
end
print("测试无状态迭代器")
mutistatarr = {"liugao","liugao2"}
function elementIterator (collection)
local index=0
local count=#collection
-- 闭包函数
return function()
index = index + 1
if index <= count
then
-- 返回迭代器的元素
return index, collection[index]
end
end
end
for index,element in elementIterator(mutistatarr)
do
print(index,element)
end
-- 测试table
print("测试table")
fruits={"banana","orange","apple"}
-- 返回talbe连接后的字符串
print("连接后的字符",table.concat(fruits))
-- 指定连接字符
print("连接后的字符",table.concat(fruits,": "))
-- 测试插入和移除
print("测试插入和移除")
table.insert(fruits,"mango")
for i,v in pairs(fruits)
do
print(i,v)
end
print("移除最后一个元素")
table.remove(fruits)
for i,v in pairs(fruits)
do
print(i,v)
end
print("排序后")
table.sort(fruits)
for i,v in pairs(fruits)
do
print(i,v)
end
-- 测试元表
mytable = setmetatable({key1 = "value1"}, {
__index = function(mytable, key)
if key == "key2" then
return "metatablevalue"
else
return mytable[key]
end
end
})
print(mytable.key1,mytable.key2)
运行结果如下图: