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)
相關文章
相關標籤/搜索