字段类型
global -- 默认,全局类型
local -- 局部类型
table -- ??
变量初始化与赋值
支持多变量同时赋值 -- i,j = 2,3
if语句
只有false和nil才会做失败判定,即使0也会被判断为成功
函数
格式
optional_function_scope function function_name( argument1, argument2, argument3........, argumentn) function_body return result_params_comma_separated end
optional_function_scope -- local or global(默认)
function_name -- 函数名
argument -- 参数
function_body -- 函数体
result_params_comma_separated -- 返回值,多值的情况以逗号分开
不定参数函数
function average(...)
result = 0
local arg = {...}
for i,v in ipairs(arg) do
result = result + v
end
return result/#arg
end
string类型
三种表示形式,单引号/双引号/[[ ]](无转移字符)
数组
默认的index从1开始,可以人为设定。内部可能是kv结构进行的存储。
comment
使用 "--"
迭代器
对于数组的遍历,可以使用ipairs
array = {"Lua", "Tutorial"}
for key,value in ipairs(array)
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
square后的第一个值作为限制循环次数的参数传入,第二个值表示当前值,该值会递增。只要square函数有返回值,for循环将一直循环执行。
有状态迭代器
通过闭包的方式实现
array = {"Lua", "Tutorial"}
function elementIterator (collection)
local index = 0
local count = #collection
-- The closure function is returned
return function ()
index = index + 1
if index <= count
then
-- return the current element of the iterator
return collection[index]
end
end
end
for element in elementIterator(array)
do
print(element)
end
table
初始化 -- mytable = {}
添加元素 -- mytable[1]= "Lua"
删表 -- mytable = nil(如果还有其他变量指向该表,不会进行垃圾回收。只有所有该表的引用均删除操作,才会触发垃圾回收机制)
遍历 -- for key, value in pairs(tbtest) do
删除元素 -- table.remove,如何删除非数组类型的元素???