微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

lua 笔记

lua基本类型:
nil、boolean、string、userdata、function、thread、table
函数type返回类型

Lua 保留字:
and     break    do     else   elseif
end     false    for     function   if 
in     local    nil     not     or 
repeat   return   then   true   until  
while 


运算符:
< > <= >= == ~=

逻辑运算符:
and or not

连接运算符:
..

运算符优先级:
^ 
not  - (unary) 
*   / 
+   - 
.. 
<  >  <=  >=  ~=  == 
and 
or

table构造:
tab = {1,2,3}
tab[1]		访问容器从下标1开始

lua table构造list:
list = nil  
for  line in io.lines() do 
  list = {next=list,value=line} 
end

l = list 
while  l  do 
 print(l.value) 
  l = l.next 
end

赋值语句:
a,b = 10,2*x 
x,y = y,x

使用local 创建一个局部变量

if conditions then  
	then-part 
elseif conditions then 
	elseif-part 
..--->多个elseif 
else 
	else-part 
end;


while  condition do 
 statements; 
end ;

repeat 
 statements; 
until  conditions; 

for  var=exp1,exp2,exp3  do 
 loop-part 
end

for  i=10,1,-1 do 
 print(i) 
end

加载文件:
dofile	require	loadlib(加载库)	

pcall 在保护模式下调用他的第一个参数并运行,因此可以捕获所有的异常和错误。
如果没有异常和错误,pcall 返回true 和调用返回的任何值;否则返回nil加错误信息。 

local  status,err = pcall(function  () error( "my error" ) end ) 
print(err)


可以在任何时候调用debug.traceback 获取当前运行的 traceback 信息

多线程:
co = coroutine.create(function  ()
	for  i=1,10  do
		print("co",i)
		coroutine.yield()
	end
	end )

coroutine.resume(co)

print(coroutine.status(co))

coroutine.resume(co)
coroutine.resume(co)
coroutine.resume(co)

完整实例
function  receive (prod)
	local  status,value = coroutine.resume(prod)
	return value
end

function  send (x)
	coroutine.yield(x)
end

function  producer ()
	return coroutine.create( function  ()
		while  true do
			local  x = io.read()    -- produce new value
			send(x)
		end
	end )
end

function  filter (prod)
	return coroutine.create( function  ()
	local  line = 1
		while  true do
			local  x = receive(prod)  -- get new value
			x = string.format("%5d %s",line,x)
			send(x)  -- send it to consumer
			line = line + 1
		end
	end )
end

function  consumer (prod)
	while  true do
		local  x = receive(prod)  -- get new value
		io.write(x,"\n")    -- consume new value
	end
end

p = producer()

f = filter(p)
consumer(f)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐