1. 程式人生 > >Lua學習筆記函式

Lua學習筆記函式

數字型for 的格式,exp3預設為1
  for var=exp1 , exp2 , exp3  do
  <執行體>
  end
泛型for迭代的型別,標準庫中提供了幾種迭代器:
  io.lines() 用於迭代檔案中每行
  pairs() 迭代table中元素
  ipairs() 迭代 陣列 元素
  string.gmatch() 迭代字串中單詞
  
一,函式
  多重返回值:x , y = foo() 
  foo()返回值就是2個值,並不是table或者其他型別。
  t = { foo() }  這是再封裝 成為一個table。{ “a” , “b” }
  
  變長引數:function add ( ... )
  在函式內部使用這些引數  依然使用 ... 來表示,此時,這個表示式 是一個像多重返回值一樣的序列,不是table。當然,可以再包裝 { ... }。這也是通常函式內遍歷變長引數的方式。
  function fwrite ( fmt , ... )
  return io.write( string.format( fmt, ...) )
  end
  
  具名實參:
  w = Window{ x=0 , y=0 , width=300 , height=200,
  title = “Lua” , background=”blue”,
  border = true }
  Window函式只有一個引數(當函式只有一個引數時,呼叫時可以去掉圓括號),並且,這個引數需要我們用table,就可以實現具名引數了。
  
  深入函式:
  第一類值:函式(這個函式本身,而非其返回值,其實現我們可以理解為類似於C中的函式指標被儲存)可以儲存到變數中,或者table中,可以作為實參傳遞給其他函式,還可以作為作為其他函式的返回值。詞法域:類似於JS中的閉包。
  函式名,一個擁有某函式的變數。函式與所有其他值一樣都是匿名的。
  foo = function( x )  return 2*x  end
  
  table.sort ( onetable , function( a , b ) 
  return (a.name > b.name) 
  end 
  )


對一些函式的訪問,想要建立一個安全的執行環境,比如,限制一個程式訪問檔案:
  do
  local  oldOpen = io.open
  local access_OK = function ( filename , mode )
  <檢查訪問許可權>
  end
  io.open  =  function ( filename , mode )
  if access_OK( filename , mode ) then
  return oldOpen( filename , mode )
  else
  return  nil , “access denied”
  end
  end
  end
  
  正確的尾呼叫:
  function f ( x )  return g( x )  end  ---yes
  function f ( x )   g( x )  end  ---not
  “尾呼叫”不需要消耗任何棧資訊,即,當g返回時,程式執行點將直接返回 呼叫f的地方。可以理解為,在f返回並呼叫g的時候,f 已經被清棧,之後接著呼叫g,g結束後自然棧呼叫資訊直接到了,f的呼叫者的地方。
  “尾呼叫”  return <func> ( <args> )
  非常適合狀態機一類程式。
  擷取一段例子:
  funciton room1 ()
  local move = io.read()
  if  move == “south” then return room3()
  elseif  move == “east” then return room2()
  else
  print( “invalid move” )
  return room1()  --stay in the same room
  end
  end