初学者,有错误希望指正。
1——————逻辑符
a and b
--[[如果a为false,则返回a,否则返回b]]
a or b
--[[如果a为true,则返回a,否则返回b]]
x=x or v
--[[当x为nil或false时,把v的值赋给x]]
--[[等价于]]
if not x then
x=v
end
--[[C 语言中的 a?b:c在lua中用 (a and b) or c]]
2————————返回比对的第几个值
--[[只想要string.find返回的第二个值,典型的方法是使用哑元(dummy variable,下划线)]]
local _,x=string.find(s,p)
--[[get x]]
--[[另一种是可变参数的一种应用]]
function select(n,...)
return(arg[n])
end
select(n,string.find(s,p))
--[[获取第n个返回值,推荐]]
3————————Lua 具名实参(通过table实现可选参数函数)
--[[检查参数和设置默认参数值的函数]]
function func1(a)
print("this is fakeone")
--[[
if func_os~=nil and func_3~=nil then
func_os(func_3)
end
]]
_func1(a.x,a.func_os or nil,a.func_3 or nil)
end
--[[真正实现功能的函数]]
function _func1(x,func_os,func_3)
print("this is correct one")
if func_os~=nil and func_3~=nil then
func_os(func_3)
end
print(type(func_os),type(func_3))
end
function func2(func_os)
print("this is two")
func_os()
end
function func3(...)
print("this is three")
end
for line in io.lines() do
if "1"==line then
--[[func1({x=line,func_os=func2,func_3=func3})]]
local a={x=line,func_os=func2,func_3=func3}
func1(a)
else
break
end
end
4——————————闭包的小应用,利用闭包特性建立隔离沙箱
--[[创建一个安全的环境。当运行一段不信任的代码时需要的安全环境]]
--[[比如使用闭包重定义io库的open函数来限制程序打开的文件]]
--[[写一个调用io.open]]
function open_change(filename,mode)
local newopen=io.open
--[[可用可不用用local就是chunk内使用,不用local就是全局]]
newopen=function(filename)
if access_OK(filename,mode)then
return io.open(filename,mode)
else
return nil,"access dennied"
--[[尾调用,尾调用不需要使用栈空间,那么尾调用递归的层次可以无限制的,不会导致栈溢出]]
end
--[[修改后newopen只能本地使用,全局的io.open不被修改]]
end
end
--[[修改io.open的返回]]
function open_change(filename,mode)
local oldopen=io.open
io.open=function(filename)
if access_OK(filename,mode)then
return oldopen(filename,mode)
else
return nil,"access dennied"
--尾调用,尾调用不需要使用栈空间,那么尾调用递归的层次可以无限制的,不会导致栈溢出
end
--[[修改后的io.open在本文件内都被修改,如果是作为module被require那么修改后的io.open同样适用于require本文件的新文件]]
end
end