lua学习笔记(入门篇·下)
上一篇咱们讲到模块与包来着~话不多说,本篇从元表开始。
1.元表 Metatable
元表可以让我们计算两个table 的相加操作 a+b,代码示例如下:
myMetatable = setmetatable({key1 = "hello"},{
__index = function (myMetatable,key)
if key == "key2" then
return "this is the second value."
else
return nil
end
end
})
print (myMetatable.key2)
测试输出:
嗯,换句话说,就是看哪个表有就调用哪个表咯~
2.协同程序(coroutine)
Lua协同程序 与线程 类似 ,主要区别在于 一个具有多线程的程序可以同时运行几个线程,而协同程序却需要彼此写作运行。任一时刻只有一个协同程序在运行。
基本语法: coroutine.create() 、coroutine.resume() 、coroutine.yield()、 coroutine.status()、coroutine.wrap()、coroutine.running()
上手试一下:
corou = coroutine.create(
function(i)
print (i)
end
)
coroutine.resume(corou,1) --1?
print(coroutine.status(corou))-----dead?
输出结果:
3.文件 I/O
Lua I/O 读取和处理文件 有 简单模式、完全模式两种。
简单模式:
file = io.open("module.lua","r")
io.input(file)
print(io.read())
io.close(file)
file = io.open("module.lua","a+")
io.output(file)
io.input(file)
io.write("----add something")
print(io.read())
io.close(file)
测试结果:
好,然后再看看完全模式~
file = io.open("module.lua","r")
print(file:read())
file:close()
file = io.open("module.lua","a+")
file:write("----------testing")
file:close()
嗯哼,结果是这样的~
4.错误处理
主要有两种,语法错误和运行错误,语法错误就不详述了,根据提示去改就好,咱来看看运行错误的处理方式其中一种 assert :
function add(a,b)
assert(type(a)=="number","a is not a number")
assert(type(b)=="number","b is not a number")
return a+baidu
end
add(9)
输出是这样的:
此外还有 pcall xpcall debug 嗯。。。这些记下来,用到的时候就懂了
5.垃圾回收
Lua采用的是自动内存管理,嗯哼,所以通常情况下不必操心所创建对象的内存的分配和释放。
垃圾回收函数如下:
collectgarbage(“collect”) 、collectgarbage(“count”):、 collectgarbage(“restart”): 、collectgarbage(“setpause”):、collectgarbage(“setstepmul”):、collectgarbage(“step”): 、collectgarbage(“stop”):
嗯哼,挺有意思,老规矩,详细了解的老铁google呗。
6.面向对象
由于对象由属性和方法组成,所以在Lua 中,可以通过 table + function 模拟出 类 来。
举个栗子:
Rectangle = {area = 0 , length = 0 ,breadth = 0}
function Rectangle : new (o , length ,breadth)
O = o or {}
setmetatable(O,self)
self.__index = self
self.length = length or 0
self.breadth = breadth or 0
self.area = length*breadth
return O
end
function Rectangle : printArea()
print("the area is ", self.area )
end
r = Rectangle:new(nil,10,20)
print(r.length)
r : printArea()
输出结果:
嗯哼,入门笔记先到这里~(其实还有数据库,不过在下的小手提没有安装这个,回头再说,哈哈哈)
心得:Lua确实小巧精致,至于性能用到了才会有实际的感受咯。