此文迎合有点语言基础的人速度浏览Lua特性的需求
function 不定长参数
function getSumMore(...)
local sum=0
for k,v in pairs{...} do
sum =sum +v
end
return sum
end
io.write("Sum",getSumMore(1,2,3,4,5,6,7),"\n")
function is variable
like anonymous function
doubleIT = function(x) return x *2 end
Intersting Closure
function outerFunc()
local i=0
return function()
i=i+1
return i
end
end
getI=outerFunc()
print(getI())
print(getI())
Coroutine
co = coroutine.create(function()
for i=1,10,1 do
print(i)
print(coroutine.status(co))
if i==5 then coroutine.yield() end
end
end)
print(coroutine.status(co))
coroutine.resume(co)
print(coroutine.status(co))
co2 =coroutine.create(function()
for i=101,110,1 do
print(i)
end end)
coroutine.resume(co2)
coroutine.resume(co)
print(coroutine.status(co))
files_IO
--r:Read only(default)
--w: Overwrite or create a new file
--a: Append or create a new file
--r+: Read & write existing file
--w+: Overwrite read or create a file
--a+: Append read or create file
file =io.open("test.lua","w+")
file:write("Random string of text\n")
file:write("Random string of text\n")
file:seek("set",0)
print(file:read("*a"))
file:close()
file =io.open("test.lua","a+")
file:write("Even more text\n")
file:seek("set",0)
print(file:read("*a"))
file:close()
modules
convertModule = require("convert")
print(string.format("%.3f cm",convertModule.ftToCm(12)))
local convert={}
function convert.ftToCm(feet)
return feet +30.48
end
return convert
metaTable 操作符的重载?
aTable={}
for x=1,10 do
aTable[x]=x
end
mt={
__add = function(table1,table2)
sumTable={}
for y=1,#table1 do
if(table1[y]~=nil) and (table2[y]~=nil) then
sumTable[y]=table1[y]+table2[y]
else
sumTable[y]=0
end
end
return sumTable
end,
__eq = function(table1,table2)
return table1.value ==table2.value
end,
__lt = function(table1,table2)
return table1.value <table2.value
end,
__le = function(table1,table2)
return table1.value <=table2.value
end,
}
setmetatable(aTable,mt)
print(aTable==aTable)
addTable={}
addTable =aTable+aTable
for i=1,10 do
print(addTable[i])
end
Fake Class
Animal={height=0,weight=0,name="No name",sound="No Sound"}
function Animal:New(height,weight,name,sound)
setmetatable({},Animal)
self.height=height
self.weight =weight
self.name=name
self.sound=sound
return self
end
function Animal:toString()
animalStr =string.format("%s weight %.1f lbs,is %.1f in tall and says %s",self.name,self.weight,self.height,self.sound)
return animalStr
end
spot = Animal:New(10,15,"Spot","Woof")
print(spot.weight)
print(spot:toString())
Inheirtance
继承上面的~
function Cat:toString()
animalStr =string.format("%s weight %.1f lbs,is %.1f in tall and says %s and loves %s",self.name,self.weight,self.height,self.sound,self.favFood)
return animalStr
end
fluffy = Cat:New(10,15,"Fluffy","Meow","Tuna")
print(fluffy:toString())