by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celeshtml
雲風 譯 www.codingnow.comnode
Copyright © 2006 Lua.org, PUC-Rio. All rights reserved.git
Lua 是一個擴展式程序設計語言,它被設計成支持通用的過程式編程,並有相關數據描述的設施。 Lua 也能對面向對象編程,函數式編程,數據驅動式編程提供很好的支持。 它能夠做爲一個強大、輕量的腳本語言,供任何須要的程序使用。 Lua 以一個用 clean C 寫成的庫形式提供。(所謂 Clean C ,指的 ANSI C 和 C++ 中共通的一個子集)程序員
做爲一個擴展式語言,Lua 沒有 "main" 程序的概念:它只能 嵌入 一個宿主程序中工做,這個宿主程序被稱做 embedding program 或簡稱爲 host 。 宿主程序能夠經過調用函數執行一小段 Lua 代碼,能夠讀寫 Lua 變量,能夠注入 C 函數讓 Lua 代碼調用。 這些擴展的 C 函數,能夠大大的擴展了 Lua 能夠處理事務的領域,這樣就能夠訂製出各類語言, 而它們共享一個統一的句法格式的框架。 Lua 的官方發佈版就包含了一個叫作 lua
的簡單的宿主程序,它用 Lua 庫提供了一個保證獨立的 Lua 解釋器。web
Lua 是一個自由軟件,它的使用許可決定了對它的使用過程通常沒有任何保證。 這份手冊中描述的東西的實現,能夠在 Lua 的官方網站 www.lua.org
找到,shell
跟其它的許多參考手冊同樣,這份文檔有些地方比較枯燥。 關於 Lua 的設計想法的探討,能夠看看 Lua 網站上提供的技術論文。 有關用 Lua 編程的細節介紹,能夠讀一下 Roberto 的書,Programming in Lua (Second Edition) 。數據庫
這一節從詞法、語法、句法上描述 Lua 。 換句話說,這一節描述了哪些 token (符記)是有效的,它們如何被組合起來,這些組合方式有什麼含義。express
關於語言的構成概念將用常見的擴展 BNF 表達式寫出。也就是這個樣子: {a} 意思是 0 或多個 a , [a] 意思是一個可選的 a 。 非最終的符號會保留原來的樣子,關鍵字則看起來像這樣 kword , 其它最終的符號則寫成 `=´ 。 完整的 Lua 語法能夠在本手冊最後找到。編程
Lua 中用到的 名字(也稱做 標識符)能夠是任何非數字開頭的字母、數字、下劃線組成的字符串。 這符合幾乎全部編程語言中關於名字的定義。 (字母的定義依賴於當前環境:系統環境中定義的字母表中的字母均可以被用於標識符。) 標識符用來命名變量,或做爲表的域名。api
下面的關鍵字是保留的,不能用做名字:
and break do else elseif end false for function if in local nil not or repeat return then true until while
Lua 是一個大小寫敏感的語言: and
是一個保留字,可是 And
和 AND
則是兩個不一樣的合法的名字。 通常約定,如下劃線開頭鏈接一串大寫字母的名字(好比_VERSION
)被保留用於 Lua 內部全局變量。
下面這些是其它的 token :
+ - * / % ^ # == ~= <= >= < > = ( ) { } [ ] ; : , . .. ...
字符串既能夠用一對單引號引發,也能夠是雙引號,裏面還能夠包含相似 C 的轉義符: '\a
' (響鈴), '\b
' (退格), '\f
' (表單), '\n
' (換行), '\r
' (回車), '\t
' (橫向製表), '\v
' (縱向製表), '\\
' (反斜槓), '\"
' (雙引號), 以及 '\'
' (單引號)。 並且,若是在一個反斜槓後跟了一個真正的換行符,其結果就是在字符串中產生一個換行符。 咱們還能夠用反斜槓加數字的形式 \ddd
來描述一個字符。這裏, ddd 是一串最多三位的十進制數字。(注意,若是須要在這種描述方法後接一個是數字的字符, 那麼反斜槓後必須寫滿三個數字。)Lua 中的字符串能夠包含任何 8 位的值。包括用 '\0
' 表示的零。
只有在你須要把不一樣的引號、換行、反斜槓、或是零結束符這些字符置入字符串時, 你才必須使用轉義符。別的任何字符均可以直接寫在文本里。(一些控制符能夠會影響文件系統形成某些問題, 可是不會引發 Lua 的任何問題。)
字符串還能夠用一種長括號括起來的方式定義。 咱們把兩個正的方括號間插入 n 個等號定義爲第 n 級正長括號。 就是說,0 級正的長括號寫做 [[
, 一級正的長括號寫做 [=[
,如此等等。 反的長擴展也做相似定義; 舉個例子,4 級反的長括號寫做 ]====]
。 一個長字符串能夠由任何一級的正的長括號開始,而由第一個碰到的同級反的長括號結束。 整個詞法分析過程將不受分行限制,不處理任何轉意符,而且忽略掉任何不一樣級別的長括號。 這種方式描述的字符串能夠包含任何東西,固然特定級別的反長括號除外。
另外一個約定是,當正的長括號後面當即跟了一個換行符, 這個換行符就不包含在這個字符串內。 舉個例子,假設一個系統使用 ASCII 碼 (這時,'a
' 編碼爲 97 ,換行符編碼爲 10 ,'1
' 編碼爲 49 ), 下面五種方式描述了徹底相同的字符串:
a = 'alo\n123"' a = "alo\n123\"" a = '\97lo\10\04923"' a = [[alo 123"]] a = [==[ alo 123"]==]
數字常量能夠分兩部分寫,十進制底數部分和十進制的指數部分。指數部分是可選的。 Lua 也支持十六進制整數常量,只須要在前面加上前綴 0x
。 下面是一些合法的數字常量的例子:
3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56
註釋能夠在除字符串內的任何地方是以兩橫 (--
) 開始。 若是跟在兩橫後面的不是一個長括號,這就是一個短註釋,它的做用範圍直到行末; 不然就是一個長註釋,其做用範圍直到遇到反的長括號。 長註釋一般被用來臨時屏蔽代碼塊。
Lua 是一種 動態類型語言。 這意味着變量沒有類型,只有值纔有類型。 語言中不存在類型定義。而全部的值自己攜帶它們本身的類型信息。
Lua 中的全部值都是一致 (first-class) 的。 這意味着全部的值均可以被放在變量裏,看成參數傳遞到另外一個函數中,並被函數做爲結果返回。
Lua 中有八種基本類型: nil, boolean, number, string, function, userdata, thread, and table. Nil 類型只有一種值 nil ,它的主要用途用於標表識和別的任何值的差別; 一般,當須要描述一個無心義的值時會用到它。 Boolean 類型只有兩種值:false 和 true。 nil 和 false 都能致使條件爲假;而另外全部的值都被看成真。 Number 表示實數(雙精度浮點數)。 (編譯一個其它內部數字類型的 Lua 解釋器是件很容易的事;好比把內部數字類型改做 單精度浮點數或長整型。參見文件 luaconf.h
。) String 表示一串字符的數組。 Lua 是 8-bit clean 的: 字符串能夠包含任何 8 位字符, 包括零結束符 ('\0
') (參見 §2.1)。
Lua 能夠調用(和處理)用 Lua 寫的函數以及用 C 寫的函數(參見 §2.5.8).
userdata 類型用來將任意 C 數據保存在 Lua 變量中。 這個類型至關於一塊原生的內存,除了賦值和相同性判斷,Lua 沒有爲之預約義任何操做。 然而,經過使用metatable (元表) ,程序員能夠爲 userdata 自定義一組操做 (參見 §2.8)。 userdata 不能在 Lua 中建立出來,也不能在 Lua 中修改。這樣的操做只能經過 C API。 這一點保證了宿主程序徹底掌管其中的數據。
thread 類型用來區別獨立的執行線程,它被用來實現 coroutine (協同例程)(參見 §2.11)。 不要把 Lua 線程跟操做系統的線程搞混。 Lua 能夠在全部的系統上提供對 coroutine 的支持,即便系統並不支持線程。
table 類型實現了一個關聯數組。也就是說, 數組能夠用任何東西(除了nil)作索引,而不限於數字。 table 能夠以不一樣類型的值構成;它能夠包含全部的類型的值(除 nil 外)。 table 是 lua 中惟一的一種數據結構;它能夠用來描述原始的數組、符號表、集合、 記錄、圖、樹、等等。 用於表述記錄時,lua 使用域名做爲索引。 語言自己採用一種語法糖,支持以 a.name
的形式表示 a["name"]
。 有不少形式用於在 lua 中建立一個 table (參見 §2.5.7)。
跟索引同樣, table 每一個域中的值也能夠是任何類型(除 nil外)。 特別的,由於函數自己也是值,因此 table 的域中也能夠放函數。 這樣 table 中就能夠有一些 methods 了 (參見see §2.5.9)。
table, function ,thread ,和 (full) userdata 這些類型的值是所謂的對象: 變量自己並不會真正的存放它們的值,而只是放了一個對對象的引用。 賦值,參數傳遞,函數返回,都是對這些對象的引用進行操做; 這些操做不會作暗地裏作任何性質的拷貝。
庫函數 type
能夠返回一個描述給定值的類型的字符串。
Lua 提供運行時字符串到數字的自動轉換。 任何對字符串的數學運算操做都會嘗試用通常的轉換規則把這個字符串轉換成一個數字。 相反,不管什麼時候,一個數字須要做爲字符串來使用時,數字都會以合理的格式轉換爲字符串。 須要徹底控制數字怎樣轉換爲字符串,可使用字符串庫中的 format
函數 (參見 string.format
)。
寫上變量的地方意味着當以其保存的值來替代之。 Lua 中有三類變量:全局變量,局部變量,還有 table 的域。
一個單一的名字能夠表示一個全局變量,也能夠表示一個局部變量 (或者是一個函數的參數,這是一種特殊形式的局部變量):
var ::= Name
Name 就是 §2.1 中所定義的標識符。
任何變量都被假定爲全局變量,除非顯式的以 local 修飾定義 (參見 §2.4.7)。 局部變量有其做用範圍: 局部變量能夠被定義在它做用範圍中的函數自由使用 (參見 §2.6)。
在變量的首次賦值以前,變量的值均爲 nil。
方括號被用來對 table 做索引:
var ::= prefixexp `[´ exp `]´
對全局變量以及 table 域之訪問的含義能夠經過 metatable 來改變。 以取一個變量下標指向的量 t[i]
等價於調用 gettable_event(t,i)
。 (參見 §2.8 ,有一份完整的關於 gettable_event
函數的說明。 這個函數並無在 lua 中定義出來,也不能在 lua 中調用。 這裏咱們把它列出來只是方便說明。)
var.Name
這種語法只是一個語法糖,用來表示 var["Name"]
:
var ::= prefixexp `.´ Name
全部的全局變量都是放在一個特定 lua table 的諸個域中,這個特定的 table 叫做 environment (環境)table 或者簡稱爲 環境 (參見 §2.9)。 每一個函數都有對一個環境的引用, 因此一個函數中可見的全部全局變量都放在這個函數所引用的環境表(environment table)中。 當一個函數被建立出來,它會從建立它的函數中繼承其環境,你能夠調用 getfenv
取得其環境。 若是想改變環境,能夠調用 setfenv
。 (對於 C 函數,你只能經過 debug 庫來改變其環境; 參見 §5.9)。
對一個全局變量 x
的訪問 等價於 _env.x
,而這又能夠等價於
gettable_event(_env, "x")
這裏,_env
是當前運行的函數的環境。 (函數 gettable_event
的完整說明參見 §2.8。 這個函數並無在 lua 中定義出來,也不能調用。 固然,_env
這個變量也一樣沒有在 Lua 中定義出來。 咱們在這裏使用它們,僅僅只是方便解釋而已。)
Lua 支持慣例形式的語句段,它和 Pascal 或是 C 很相象。 這個集合包括賦值,控制結構,函數調用,還有變量聲明。
Lua 的一個執行單元被稱做 chunk。 一個 chunk 就是一串語句段,它們會被循序的執行。 每一個語句段能夠以一個分號結束:
chunk ::= {stat [`;´]}
這兒不容許有空的語句段,因此 ';;
' 是非法的。
lua 把一個 chunk 看成一個擁有不定參數的匿名函數 (參見 §2.5.9)處理。 正是這樣,chunk 內能夠定義局部變量,接收參數,而且返回值。
chunk 能夠被保存在一個文件中,也能夠保存在宿主程序的一個字符串中。 當一個 chunk 被執行,首先它會被預編譯成虛擬機中的指令序列, 而後被虛擬機解釋運行這些指令。
chunk 也能夠被預編譯成二進制形式;細節參考程序 luac
。 用源碼形式提供的程序和被編譯過的二進制形式的程序是能夠相互替換的; Lua 會自動識別文件類型並作正確的處理。
語句塊是一列語句段;從語法上來講,一個語句塊跟一個 chunk 相同:
block ::= chunk
一個語句塊能夠被顯式的寫成一個單獨的語句段:
stat ::= do block end
顯式的語句塊對於控制變量的做用範圍頗有用。 有時候,顯式的語句塊被用來在另外一個語句塊中插入 return 或是 break (參見 §2.4.4)。
Lua 容許多重賦值。 所以,賦值的語法定義是等號左邊放一系列變量, 而等號右邊放一系列的表達式。 兩邊的元素都用逗號間開:
stat ::= varlist1 `=´ explist1 varlist1 ::= var {`,´ var} explist1 ::= exp {`,´ exp}
表達式放在 §2.5 裏討論。
在做賦值操做以前, 那一系列的右值會被對齊到左邊變量須要的個數。 若是右值比須要的更多的話,多餘的值就被扔掉。 若是右值的數量不夠需求, 將會按所需擴展若干個 nil。 若是表達式列表以一個函數調用結束, 這個函數所返回的全部值都會在對齊操做以前被置入右值序列中。 (除非這個函數調用被用括號括了起來;參見 §2.5)。
賦值段首先會作運算完全部的表達式,而後僅僅作賦值操做。 所以,下面這段代碼
i = 3 i, a[i] = i+1, 20
會把 a[3]
設置爲 20,而不會影響到 a[4]
。 這是由於 a[i]
中的 i
在被賦值爲 4 以前就被拿出來了(那時是 3 )。 簡單說 ,這樣一行
x, y = y, x
能夠用來交換 x
和 y
中的值。
對全局變量以及 table 中的域的賦值操做的含義能夠經過 metatable 來改變。 對變量下標指向的賦值,即 t[i] = val
等價於 settable_event(t,i,val)
。 (關於函數settable_event
的詳細說明,參見 §2.8。 這個函數並無在 Lua 中定義出來,也不能夠被調用。 這裏咱們列出來,僅僅出於方便解釋的目的)
對於全局變量的賦值 x = val
等價於 _env.x = val
,這個又能夠等價於
settable_event(_env, "x", val)
這裏,_env
指的是正在運行中的函數的環境。 (變量 _env
並無在 Lua 中定義出來。 咱們僅僅出於解釋的目的在這裏寫出來。)
if、 while、以及 repeat 這些控制結構符合一般的意義,並且也有相似的語法:
stat ::= while exp do block end stat ::= repeat block until exp stat ::= if exp then block {elseif exp then block} [else block] end
Lua 也有一個 for 語句,它有兩種形式(參見 §2.4.5)。
控制結構中的條件表達式能夠返回任何值。 false 和 nil 二者都被認爲是假條件。 全部不一樣於 nil 和 false 的其它值都被認爲是真 (特別須要注意的是,數字 0 和空字符串也被認爲是真)。
在 repeat–until 循環中, 內部語句塊的結束點不是在 until 這個關鍵字處, 它還包括了其後的條件表達式。 所以,條件表達式中可使用循環內部語句塊中的定義的局部變量。
return 被用於從函數或是 chunk(其實它就是一個函數)中 返回值。 函數和 chunk 能夠返回不僅一個值, 因此 return 的語法爲
stat ::= return [explist1]
break 被用來結束 while、 repeat、或 for 循環, 它將忽略掉循環中下面的語句段的運行:
stat ::= break
break 跳出最內層的循環。
return 和 break 只能被寫在一個語句塊的最後一句。 若是你真的須要從語句塊的中間 return 或是 break , 你可使用顯式的聲名一個內部語句塊。 通常寫做do return end
或是 do break end
, 能夠這樣寫是由於如今 return 或 break 都成了一個語句塊的最後一句了。
for 有兩種形式:一種是數字形式,另外一種是通常形式。
數字形式的 for 循環,經過一個數學運算不斷的運行內部的代碼塊。 下面是它的語法:
stat ::= for Name `=´ exp `,´ exp [`,´ exp] do block end
block 將把 name 做循環變量。從第一個 exp 開始起,直到第二個 exp 的值爲止,其步長爲 第三個 exp 。 更確切的說,一個 for 循環看起來是這個樣子
for v = e1, e2, e3 do block end
這等價於代碼:
do local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3) if not (var and limit and step) then error() end while (step > 0 and var <= limit) or (step <= 0 and var >= limit) do local v = var block var = var + step end end
注意下面這幾點:
var
、limit
、以及 step
都是一些不可見的變量。 這裏給它們起的名字都僅僅用於解釋方便。v
是一個循環內部的局部變量; 當 for 循環結束後,你就不能在使用它。 若是你須要這個值,在退出循環前把它賦給另外一個變量。通常形式的 for 經過一個叫做迭代器(iterators)的函數工做。 每次迭代,迭代器函數都會被調用以產生一個新的值, 當這個值爲 nil 時,循環中止。 通常形式的 for 循環的語法以下:
stat ::= for namelist in explist1 do block end namelist ::= Name {`,´ Name}
for 語句好似這樣
for var_1, ···, var_n in explist do block end
它等價於這樣一段代碼:
do local f, s, var = explist while true do local var_1, ···, var_n = f(s, var) var = var_1 if var == nil then break end block end end
注意如下幾點:
explist
只會被計算一次。 它返回三個值, 一個迭代器函數,一個狀態,一個迭代器的初始值。f
、 s
、 以及 var
都是不可見的變量。 這裏給它們起的名字都只是爲了解說方便。var_i
對於循環來講是一個局部變量; 你不能夠在 for 循環結束後繼續使用。 若是你須要保留這些值,那麼就在循環結束前賦值到別的變量裏去。爲了容許使用可能的反作用, 函數調用能夠被做爲一個語句段執行:
stat ::= functioncall
在這種狀況下,全部的返回值都被捨棄。 函數調用在 §2.5.8 中解釋。
局部變量能夠在語句塊中任何地方聲名。 聲名能夠包含一個初始化賦值操做:
stat ::= local namelist [`=´ explist1]
若是有的話,初始化賦值操做的行爲等同於賦值操做(參見 §2.4.3)。 不然,全部的變量將被初始化爲 nil。
一個 chunk 同時也是一個語句塊(參見 §2.4.1), 因此局部變量能夠放在 chunk 中那些顯式註明的語句塊以外。 這些局部變量的做用範圍從聲明起一直延伸到 chunk 末尾。
局部變量的可見規則在 §2.6 中解釋。
Lua 中有這些基本表達式:
exp ::= prefixexp exp ::= nil | false | true exp ::= Number exp ::= String exp ::= function exp ::= tableconstructor exp ::= `...´ exp ::= exp binop exp exp ::= unop exp prefixexp ::= var | functioncall | `(´ exp `)´
數字和字符串在 §2.1 中解釋; 變量在 §2.3 中解釋; 函數定義在 §2.5.9 中解釋; 函數調用在 §2.5.8 中解釋; table 的構造在 §2.5.7 中解釋; 可變參數的表達式寫做三個點 ('...
') ,它只能被用在有可變參數的函數中; 這些在 §2.5.9 中解釋。
二元操做符包含有數學運算操做符(參見 §2.5.1), 比較操做符(參見 §2.5.2),邏輯操做符(參見 §2.5.3), 以及鏈接操做符(參見 §2.5.4)。 一元操做符包括負號(參見see §2.5.1), 取反 not(參見 §2.5.3), 和取長度操做符(參見 §2.5.5)。
函數調用和可變參數表達式均可以放在多重返回值中。 若是表達式做爲一個獨立語句段出現(參見 §2.4.6) (這隻能是一個函數調用), 它們的返回列表將被對齊到零個元素,也就是忽略全部返回值。 若是表達式用於表達式列表的最後(或者是惟一)的元素, 就不會有任何的對齊操做(除非函數調用用括號括起來)。 在任何其它的狀況下,Lua 將把表達式結果當作單一元素, 忽略除第一個以外的任何值。
這裏有一些例子:
f() -- 調整到 0 個結果 g(f(), x) -- f() 被調整到一個結果 g(x, f()) -- g 被傳入 x 加上全部 f() 的返回值 a,b,c = f(), x -- f() 被調整到一個結果 ( c 在這裏被賦爲 nil ) a,b = ... -- a 被賦值爲可變參數中的第一個, -- b 被賦值爲第二個 (若是可變參數中並無對應的值, -- 這裏 a 和 b 都有可能被賦爲 nil) a,b,c = x, f() -- f() 被調整爲兩個結果 a,b,c = f() -- f() 被調整爲三個結果 return f() -- 返回 f() 返回的全部結果 return ... -- 返回全部從可變參數中接收來的值 return x,y,f() -- 返回 x, y, 以及全部 f() 的返回值 {f()} -- 用 f() 的全部返回值建立一個列表 {...} -- 用可變參數中的全部值建立一個列表 {f(), nil} -- f() 被調整爲一個結果
被括號括起來的表達式永遠被看成一個值。因此, (f(x,y,z))
即便 f
返回多個值,這個表達式永遠是一個單一值。 ((f(x,y,z))
的值是 f
返回的第一個值。若是 f
不返回值的話,那麼它的值就是 nil 。)
Lua 支持常見的數學運算操做符: 二元操做 +
(加法), -
(減法),*
(乘法), /
(除法), %
(取模),以及 ^
(冪); 和一元操做 -
(取負)。 若是對數字操做,或是能夠轉換爲數字的字符串(參見 §2.2.1), 全部這些操做都依賴它一般的含義。 冪操做能夠對任何冪值都正常工做。好比, x^(-0.5)
將計算出 x
平方根的倒數。 取模操做被定義爲
a % b == a - math.floor(a/b)*b
這就是說,其結果是商相對負無窮圓整後的餘數。(譯註:負數對正數取模的結果爲正數)
Lua 中的比較操做符有
== ~= < > <= >=
這些操做的結果不是 false 就是 true。
等於操做 (==
) 首先比較操做數的類型。 若是類型不一樣,結果就是 false。 不然,繼續比較值。 數字和字符串都用常規的方式比較。 對象 (table ,userdata ,thread ,以及函數)以引用的形式比較: 兩個對象只有在它們指向同一個東西時才認爲相等。 每次你建立一個新對象(一個 table 或是 userdata ,thread 函數), 它們都各不相同,即不一樣於上次建立的東西。
你能夠改變 Lua 比較 table 和 userdata 的方式,這須要使用 "eq" 這個原方法 (參見 §2.8)。
§2.2.1 中說起的轉換規則並不做用於比較操做。 因此, "0"==0
等於 false, 並且 t[0]
和 t["0"]
描述的是 table 中不一樣的域。
操做符 ~=
徹底等價於 (==
) 操做的反值。
大小比較操做以如下方式進行。 若是參數都是數字,那麼就直接作數字比較。 不然,若是參數都是字符串,就用字符串比較的方式進行。 再則,Lua 就試着調用 "lt" 或是 "le" 元方法 (參見 §2.8)。
Lua 中的邏輯操做符有 and, or, 以及 not。 和控制結構(參見 §2.4.4)同樣, 全部的邏輯操做符把 false 和 nil 都做爲假, 而其它的一切都看成真。
取反操做 not 老是返回 false 或 true 中的一個。 與操做符 and 在第一個參數爲 false 或 nil 時 返回這第一個參數; 不然,and 返回第二個參數。 或操做符or 在第一個參數不爲 nil 也不爲 false 時, 返回這第一個參數,不然返回第二個參數。 and 和 or 都遵循短路規則; 也就是說,第二個操做數只在須要的時候去求值。 這裏有一些例子:
10 or 20 --> 10 10 or error() --> 10 nil or "a" --> "a" nil and 10 --> nil false and error() --> false false and nil --> false false or nil --> nil 10 and 20 --> 20
(在這本手冊中, --> 指前面表達式的結果。)
Lua 中字符串的鏈接操做符寫做兩個點 ('..
')。 若是兩個操做數都是字符串或都是數字,鏈接操做將以 §2.2.1 中提到的規則把其轉換爲字符串。 不然,會取調用元方法 "concat" (參見 §2.8)。
取長度操做符寫做一元操做 #
。 字符串的長度是它的字節數(就是以一個字符一個字節計算的字符串長度)。
table t
的長度被定義成一個整數下標 n
。 它知足 t[n]
不是 nil 而 t[n+1]
爲 nil; 此外,若是 t[1]
爲 nil ,n
就多是零。 對於常規的數組,裏面從 1 到 n
放着一些非空的值的時候, 它的長度就精確的爲 n
,即最後一個值的下標。 若是數組有一個「空洞」 (就是說,nil 值被夾在非空值之間), 那麼 #t
多是指向任何一個是 nil 值的前一個位置的下標 (就是說,任何一個 nil 值都有可能被當成數組的結束)。
Lua 中操做符的優先級寫在下表中,從低到高優先級排序:
or and < > <= >= ~= == .. + - * / % not # - (unary) ^
一般,你能夠用括號來改變運算次序。 鏈接操做符 ('..
') 和冪操做 ('^
') 是從右至左的。 其它全部的操做都是從左至右。
table 構造子是一個構造 table 的表達式。 每次構造子被執行,都會構造出一個新的 table 。 構造子能夠被用來構造一個空的 table, 也能夠用來構造一個 table 並初始化其中的一些域。 通常的構造子的語法以下
tableconstructor ::= `{´ [fieldlist] `}´ fieldlist ::= field {fieldsep field} [fieldsep] field ::= `[´ exp `]´ `=´ exp | Name `=´ exp | exp fieldsep ::= `,´ | `;´
每一個形如 [exp1] = exp2
的域向 table 中增長新的一項, 其鍵值爲 exp1
而值爲 exp2
。 形如 name = exp
的域等價於 ["name"] = exp
。 最後,形如 exp
的域等價於 [i] = exp
, 這裏的 i
是一個從 1 開始不斷增加的數字。 這這個格式中的其它域不會破壞其記數。 舉個例子:
a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
等價於
do local t = {} t[f(1)] = g t[1] = "x" -- 1st exp t[2] = "y" -- 2nd exp t.x = 1 -- t["x"] = 1 t[3] = f(x) -- 3rd exp t[30] = 23 t[4] = 45 -- 4th exp a = t end
若是表單中最後一個域的形式是 exp
, 並且其表達式是一個函數調用或者是一個可變參數, 那麼這個表達式全部的返回值將連續的進入列表 (參見 §2.5.8)。 爲了不這一點,你能夠用括號把函數調用(或是可變參數)括起來 (參見 §2.5)。
初始化域表能夠在最後多一個分割符, 這樣設計能夠方便由機器生成代碼。
Lua 中的函數調用的語法以下:
functioncall ::= prefixexp args
函數調用時,第一步,prefixexp 和 args 先被求值。 若是 prefixexp 的值的類型是 function, 那麼這個函數就被用給出的參數調用。 不然 prefixexp 的元方法 "call" 就被調用, 第一個參數就是 prefixexp 的值,跟下來的是原來的調用參數 (參見 §2.8)。
這樣的形式
functioncall ::= prefixexp `:´ Name args
能夠用來調用 "方法"。 這是 Lua 支持的一種語法糖。像 v:name(args)
這個樣子,被解釋成 v.name(v,args)
, 這裏 v
只會被求值一次。
參數的語法以下:
args ::= `(´ [explist1] `)´ args ::= tableconstructor args ::= String
全部參數的表達式求值都在函數調用以前。 這樣的調用形式 f{fields}
是一種語法糖用於表示 f({fields})
; 這裏指參數列表是一個單一的新建立出來的列表。 而這樣的形式 f'string'
(或是 f"string"
亦或是 f[[string]]
) 也是一種語法糖,用於表示 f('string')
; 這裏指參數列表是一個單獨的字符串。
由於表達式語法在 Lua 中比較自由, 因此你不能在函數調用的 '(
' 前換行。 這個限制能夠避免語言中的一些歧義。 好比你這樣寫
a = f (g).x(a)
Lua 將把它看成一個單一語句段, a = f(g).x(a)
。 所以,若是你真的想做爲成兩個語句段,你必須在它們之間寫上一個分號。 若是你真的想調用 f
, 你必須從 (g)
前移去換行。
這樣一種調用形式:return
functioncall 將觸發一個尾調用。 Lua 實現了適當的尾部調用(或是適當的尾遞歸): 在尾調用中, 被調用的函數重用調用它的函數的堆棧項。 所以,對於程序執行的嵌套尾調用的層數是沒有限制的。 然而,尾調用將刪除調用它的函數的任何調試信息。 注意,尾調用只發生在特定的語法下, 這時, return 只有單一函數調用做爲參數; 這種語法使得調用函數的結果能夠精確返回。 所以,下面這些例子都不是尾調用:
return (f(x)) -- 返回值被調整爲一個 return 2 * f(x) return x, f(x) -- 最加若干返回值 f(x); return -- 無返回值 return x or f(x) -- 返回值被調整爲一個
函數定義的語法以下:
function ::= function funcbody funcbody ::= `(´ [parlist1] `)´ block end
另外定義了一些語法糖簡化函數定義的寫法:
stat ::= function funcname funcbody stat ::= local function Name funcbody funcname ::= Name {`.´ Name} [`:´ Name]
這樣的寫法:
function f () body end
被轉換成
f = function () body end
這樣的寫法:
function t.a.b.c.f () body end
被轉換成
t.a.b.c.f = function () body end
這樣的寫法:
local function f () body end
被轉換成
local f; f = function () body end
注意,並非轉換成
local f = function () body end
(這個差異只在函數體內須要引用 f
時纔有。)
一個函數定義是一個可執行的表達式, 執行結果是一個類型爲 function 的值。 當 Lua 預編譯一個 chunk 的時候, chunk 做爲一個函數,整個函數體也就被預編譯了。 那麼,不管什麼時候 Lua 執行了函數定義, 這個函數自己就被實例化了(或者說是關閉了)。 這個函數的實例(或者說是 closure(閉包)) 是表達式的最終值。 相同函數的不一樣實例有可能引用不一樣的外部局部變量, 也可能擁有不一樣的環境表。
形參(函數定義須要的參數)是一些由實參(實際傳入參數)的值初始化的局部變量:
parlist1 ::= namelist [`,´ `...´] | `...´
當一個函數被調用, 若是函數沒有被定義爲接收不定長參數,即在形參列表的末尾註明三個點 ('...
'), 那麼實參列表就會被調整到形參列表的長度, 變長參數函數不會調整實參列表; 取而代之的是,它將把全部額外的參數放在一塊兒經過變長參數表達式傳遞給函數, 其寫法依舊是三個點。 這個表達式的值是一串實參值的列表,看起來就跟一個能夠返回多個結果的函數同樣。 若是一個變長參數表達式放在另外一個表達式中使用,或是放在另外一串表達式的中間, 那麼它的返回值就會被調整爲單個值。 若這個表達式放在了一系列表達式的最後一個,就不會作調整了(除非用括號給括了起來)。
咱們先作以下定義,而後再來看一個例子:
function f(a, b) end function g(a, b, ...) end function r() return 1,2,3 end
下面看看實參到形參數以及可變長參數的映射關係:
CALL PARAMETERS f(3) a=3, b=nil f(3, 4) a=3, b=4 f(3, 4, 5) a=3, b=4 f(r(), 10) a=1, b=10 f(r()) a=1, b=2 g(3) a=3, b=nil, ... --> (nothing) g(3, 4) a=3, b=4, ... --> (nothing) g(3, 4, 5, 8) a=3, b=4, ... --> 5 8 g(5, r()) a=5, b=1, ... --> 2 3
結果由 return 來返回(參見 §2.4.4)。 若是執行到函數末尾依舊沒有遇到任何 return 語句, 函數就不會返回任何結果。
冒號語法能夠用來定義方法, 就是說,函數能夠有一個隱式的形參 self
。 所以,以下寫法:
function t.a.b.c:f (params) body end
是這樣一種寫法的語法糖:
t.a.b.c.f = function (self, params) body end
Lua 是一個有詞法做用範圍的語言。 變量的做用範圍開始於聲明它們以後的第一個語句段, 結束於包含這個聲明的最內層語句塊的結束點。 看下面這些例子:
x = 10 -- 全局變量 do -- 新的語句塊 local x = x -- 新的一個 'x', 它的值如今是 10 print(x) --> 10 x = x+1 do -- 另外一個語句塊 local x = x+1 -- 又一個 'x' print(x) --> 12 end print(x) --> 11 end print(x) --> 10 (取到的是全局的那一個)
注意這裏,相似 local x = x
這樣的聲明, 新的 x
正在被聲明,可是尚未進入它的做用範圍, 因此第二個 x
指向的是外面一層的變量。
由於有這樣一個詞法做用範圍的規則, 因此能夠在函數內部自由的定義局部變量並使用它們。 當一個局部變量被更內層的函數中使用的時候, 它被內層函數稱做upvalue(上值),或是 外部局部變量。
注意,每次執行到一個 local 語句都會定義出一個新的局部變量。 看看這樣一個例子:
a = {} local x = 20 for i=1,10 do local y = 0 a[i] = function () y=y+1; return x+y end end
這個循環建立了十個 closure(這指十個匿名函數的實例)。 這些 closure 中的每個都使用了不一樣的 y
變量, 而它們又共享了同一份 x
。
由於 Lua 是一個嵌入式的擴展語言, 全部的 Lua 動做都是從宿主程序的 C 代碼調用 Lua 庫 (參見 lua_pcall
)中的一個函數開始的。 在 Lua 編譯或運行的任什麼時候候發生了錯誤,控制權都會交還給 C , 而 C 能夠來作一些恰當的措施(好比打印出一條錯誤信息)。
Lua 代碼能夠顯式的調用 error
函數來產生一條錯誤。 若是你須要在 Lua 中捕獲發生的錯誤, 你可使用 pcall
函數。
Lua 中的每一個值均可以用一個 metatable。 這個 metatable 就是一個原始的 Lua table , 它用來定義原始值在特定操做下的行爲。 你能夠經過在 metatable 中的特定域設一些值來改變擁有這個 metatable 的值 的指定操做之行爲。 舉例來講,當一個非數字的值做加法操做的時候, Lua 會檢查它的 metatable 中 "__add"
域中的是否有一個函數。 若是有這麼一個函數的話,Lua 調用這個函數來執行一次加法。
咱們叫 metatable 中的鍵名爲 事件 (event) ,把其中的值叫做 元方法 (metamethod)。 在上個例子中,事件是 "add"
而元方法就是那個執行加法操做的函數。
你能夠經過 getmetatable
函數來查詢到任何一個值的 metatable。
你能夠經過 setmetatable
函數來替換掉 table 的 metatable 。 你不能從 Lua 中改變其它任何類型的值的 metatable (使用 debug 庫例外); 要這樣作的話必須使用 C API 。
每一個 table 和 userdata 擁有獨立的 metatable (固然多個 table 和 userdata 能夠共享一個相同的表做它們的 metatable); 其它全部類型的值,每種類型都分別共享惟一的一個 metatable。 所以,全部的數字一塊兒只有一個 metatable ,全部的字符串也是,等等。
一個 metatable 能夠控制一個對象作數學運算操做、比較操做、鏈接操做、取長度操做、取下標操做時的行爲, metatable 中還能夠定義一個函數,讓 userdata 做垃圾收集時調用它。 對於這些操做,Lua 都將其關聯上一個被稱做事件的指定健。 當 Lua 須要對一個值發起這些操做中的一個時, 它會去檢查值中 metatable 中是否有對應事件。 若是有的話,鍵名對應的值(元方法)將控制 Lua 怎樣作這個操做。
metatable 能夠控制的操做已在下面列出來。 每一個操做都用相應的名字區分。 每一個操做的鍵名都是用操做名字加上兩個下劃線 '__
' 前綴的字符串; 舉例來講,"add" 操做的鍵名就是字符串 "__add"
。 這些操做的語義用一個 Lua 函數來描述解釋器如何執行更爲恰當。
這裏展現的用 Lua 寫的代碼僅做解說用; 實際的行爲已經硬編碼在解釋器中,其執行效率要遠高於這些模擬代碼。 這些用於描述的的代碼中用到的函數 ( rawget
, tonumber
,等等。) 均可以在 §5.1 中找到。 特別注意,咱們使用這樣一個表達式來從給定對象中提取元方法
metatable(obj)[event]
這個應該被解讀做
rawget(getmetatable(obj) or {}, event)
這就是說,訪問一個元方法再也不會觸發任何的元方法, 並且訪問一個沒有 metatable 的對象也不會失敗(而只是簡單返回 nil)。
+
操做。 下面這個 getbinhandler
函數定義了 Lua 怎樣選擇一個處理器來做二元操做。 首先,Lua 嘗試第一個操做數。 若是這個東西的類型沒有定義這個操做的處理器,而後 Lua 會嘗試第二個操做數。
function getbinhandler (op1, op2, event) return metatable(op1)[event] or metatable(op2)[event] end
經過這個函數, op1 + op2
的行爲就是
function add_event (op1, op2) local o1, o2 = tonumber(op1), tonumber(op2) if o1 and o2 then -- 兩個操做數都是數字? return o1 + o2 -- 這裏的 '+' 是原生的 'add' else -- 至少一個操做數不是數字時 local h = getbinhandler(op1, op2, "__add") if h then -- 以兩個操做數來調用處理器 return h(op1, op2) else -- 沒有處理器:缺省行爲 error(···) end end end
-
操做。 其行爲相似於 "add" 操做。*
操做。 其行爲相似於 "add" 操做。/
操做。 其行爲相似於 "add" 操做。%
操做。 其行爲相似於 "add" 操做, 它的原生操做是這樣的 o1 - floor(o1/o2)*o2
^
(冪)操做。 其行爲相似於 "add" 操做, 它的原生操做是調用 pow
函數(經過 C math 庫)。-
操做。 function unm_event (op) local o = tonumber(op) if o then -- 操做數是數字? return -o -- 這裏的 '-' 是一個原生的 'unm' else -- 操做數不是數字。 -- 嘗試從操做數中獲得處理器 local h = metatable(op).__unm if h then -- 以操做數爲參數調用處理器 return h(op) else -- 沒有處理器:缺省行爲 error(···) end end end
..
(鏈接)操做, function concat_event (op1, op2) if (type(op1) == "string" or type(op1) == "number") and (type(op2) == "string" or type(op2) == "number") then return op1 .. op2 -- 原生字符串鏈接 else local h = getbinhandler(op1, op2, "__concat") if h then return h(op1, op2) else error(···) end end end
#
操做。 function len_event (op) if type(op) == "string" then return strlen(op) -- 原生的取字符串長度 elseif type(op) == "table" then return #op -- 原生的取 table 長度 else local h = metatable(op).__len if h then -- 調用操做數的處理器 return h(op) else -- 沒有處理器:缺省行爲 error(···) end end end
關於 table 的長度參見 §2.5.5 。
==
操做。 函數 getcomphandler
定義了 Lua 怎樣選擇一個處理器來做比較操做。 元方法僅僅在參於比較的兩個對象類型相同且有對應操做相同的元方法時才起效。 function getcomphandler (op1, op2, event) if type(op1) ~= type(op2) then return nil end local mm1 = metatable(op1)[event] local mm2 = metatable(op2)[event] if mm1 == mm2 then return mm1 else return nil end end
"eq" 事件按以下方式定義:
function eq_event (op1, op2) if type(op1) ~= type(op2) then -- 不一樣的類型? return false -- 不一樣的對象 end if op1 == op2 then -- 原生的相等比較結果? return true -- 對象相等 end -- 嘗試使用元方法 local h = getcomphandler(op1, op2, "__eq") if h then return h(op1, op2) else return false end end
a ~= b
等價於 not (a == b)
。
<
操做。 function lt_event (op1, op2) if type(op1) == "number" and type(op2) == "number" then return op1 < op2 -- 數字比較 elseif type(op1) == "string" and type(op2) == "string" then return op1 < op2 -- 字符串按逐字符比較 else local h = getcomphandler(op1, op2, "__lt") if h then return h(op1, op2) else error(···); end end end
a > b
等價於 b < a
.
<=
操做。 function le_event (op1, op2) if type(op1) == "number" and type(op2) == "number" then return op1 <= op2 -- 數字比較 elseif type(op1) == "string" and type(op2) == "string" then return op1 <= op2 -- 字符串按逐字符比較 else local h = getcomphandler(op1, op2, "__le") if h then return h(op1, op2) else h = getcomphandler(op1, op2, "__lt") if h then return not h(op2, op1) else error(···); end end end end
a >= b
等價於 b <= a
。 注意,若是元方法 "le" 沒有提供,Lua 就嘗試 "lt" , 它假定 a <= b
等價於 not (b < a)
。
table[key]
。 function gettable_event (table, key) local h if type(table) == "table" then local v = rawget(table, key) if v ~= nil then return v end h = metatable(table).__index if h == nil then return nil end else h = metatable(table).__index if h == nil then error(···); end end if type(h) == "function" then return h(table, key) -- 調用處理器 else return h[key] -- 或是重複上述操做 end end
table[key] = value
。 function settable_event (table, key, value) local h if type(table) == "table" then local v = rawget(table, key) if v ~= nil then rawset(table, key, value); return end h = metatable(table).__newindex if h == nil then rawset(table, key, value); return end else h = metatable(table).__newindex if h == nil then error(···); end end if type(h) == "function" then return h(table, key,value) -- 調用處理器 else h[key] = value -- 或是重複上述操做 end end
function function_event (func, ...) if type(func) == "function" then return func(...) -- 原生的調用 else local h = metatable(func).__call if h then return h(func, ...) else error(···) end end end
類型爲 thread ,function ,以及 userdata 的對象,除了 metatable 外還能夠用另一個與之關聯的被稱做 它們的環境的一個表, 像 metatable 同樣,環境也是一個常規的 table ,多個對象能夠共享 同一個環境。
userdata 的環境在 Lua 中沒有意義。 這個東西只是爲了在程序員想把一個表關聯到一個 userdata 上時提供便利。
關聯在線程上的環境被稱做全局環境。 全局環境被用做它其中的線程以及線程建立的非嵌套函數 (經過 loadfile
, loadstring
或是 load
)的缺省環境。 並且它能夠被 C 代碼直接訪問(參見 §3.3)。
關聯在 C 函數上的環境能夠直接被 C 代碼訪問(參見 §3.3)。 它們會做爲這個 C 函數中建立的其它函數的缺省環境。
關聯在 Lua 函數上的環境用來接管在函數內對全局變量(參見 §2.3)的全部訪問。 它們也會做爲這個函數內建立的其它函數的缺省環境。
你能夠經過調用 setfenv
來改變一個 Lua 函數 或是正在運行中的線程的環境。 而想操控其它對象(userdata、C 函數、其它線程)的環境的話,就必須使用 C API 。
Lua 提供了一個自動的內存管理。 這就是說你不須要關心建立新對象的分配內存操做,也不須要在這些對象再也不須要時的主動釋放內存。 Lua 經過運行一個垃圾收集器來自動管理內存,以此一遍又一遍的回收死掉的對象 (這是指 Lua 中再也不訪問的到的對象)佔用的內存。 Lua 中全部對象都被自動管理,包括: table, userdata、 函數、線程、和字符串。
Lua 實現了一個增量標記清除的收集器。 它用兩個數字來控制垃圾收集週期: garbage-collector pause 和 garbage-collector step multiplier 。
garbage-collector pause 控制了收集器在開始一個新的收集週期以前要等待多久。 隨着數字的增大就致使收集器工做工做的不那麼主動。 小於 1 的值意味着收集器在新的週期開始時再也不等待。 當值爲 2 的時候意味着在總使用內存數量達到原來的兩倍時再開啓新的週期。
step multiplier 控制了收集器相對內存分配的速度。 更大的數字將致使收集器工做的更主動的同時,也使每步收集的尺寸增長。 小於 1 的值會使收集器工做的很是慢,可能致使收集器永遠都結束不了當前週期。 缺省值爲 2 ,這意味着收集器將之內存分配器的兩倍速運行。
你能夠經過在 C 中調用 lua_gc
或是在 Lua 中調用 collectgarbage
來改變這些數字。 二者都接受百分比數值(所以傳入參數 100 意味着實際值 1 )。 經過這些函數,你也能夠直接控制收集器(例如,中止或是重啓)。
使用 C API , 你能夠給 userdata (參見 §2.8)設置一個垃圾收集的元方法。 這個元方法也被稱爲結束子。 結束子容許你用額外的資源管理器和 Lua 的內存管理器協同工做 (好比關閉文件、網絡鏈接、或是數據庫鏈接,也能夠說釋放你本身的內存)。
一個 userdata 可被回收,若它的 metatable 中有 __gc
這個域 , 垃圾收集器就不當即收回它。 取而代之的是,Lua 把它們放到一個列表中。 最收集結束後,Lua 針對列表中的每一個 userdata 執行了下面這個函數的等價操做:
function gc_event (udata) local h = metatable(udata).__gc if h then h(udata) end end
在每一個垃圾收集週期的結尾,每一個在當前週期被收集起來的 userdata 的結束子會以 它們構造時的逆序依次調用。 也就是說,收集列表中,最後一個在程序中被建立的 userdata 的 結束子會被第一個調用。
weak table 是一個這樣的 table,它其中的元素都被弱引用。 弱引用將被垃圾收集器忽略掉, 換句話說, 若是對一個對象的引用只有弱引用, 垃圾收集器將回收這個對象。
weak table 的鍵和值均可以是 weak 的。 若是一個 table 只有鍵是 weak 的,那麼將運行收集器回收它們的鍵, 可是會阻止回收器回收對應的值。 而一個 table 的鍵和值都是 weak 時,就即容許收集器回收鍵又容許收回值。 任何狀況下,若是鍵和值中任一個被回收了,整個鍵值對就會從 table 中拿掉。 table 的 weak 特性能夠經過在它的 metatable 中設置 __mode
域來改變。 若是 __mode
域中是一個包含有字符 'k
' 的字符串時, table 的鍵就是 weak 的。 若是 __mode
域中是一個包含有字符 'v
' 的字符串時, table 的值就是 weak 的。
在你把一個 table 看成一個 metatable 使用以後, 就不能再修改 __mode
域的值。 不然,受這個 metatable 控制的 table 的 weak 行爲就成了未定義的。
Lua 支持 coroutine ,這個東西也被稱爲協同式多線程 (collaborative multithreading) 。 Lua 爲每一個 coroutine 提供一個獨立的運行線路。 然而和多線程系統中的線程不一樣,coroutine 只在顯式的調用了 yield 函數時纔會掛起。
建立一個 coroutine 須要調用一次 coroutine.create
。 它只接收單個參數,這個參數是 coroutine 的主函數。 create
函數僅僅建立一個新的 coroutine 而後返回它的控制器 (一個類型爲 thread 的對象); 它並不會啓動 coroutine 的運行。
當你第一次調用 coroutine.resume
時, 所需傳入的第一個參數就是 coroutine.create
的返回值。 這時,coroutine 從主函數的第一行開始運行。 接下來傳入coroutine.resume
的參數將被傳進 coroutine 的主函數。 在 coroutine 開始運行後,它講運行到自身終止或是遇到一個 yields 。
coroutine 能夠經過兩種方式來終止運行: 一種是正常退出,指它的主函數返回(最後一條指令被運行後,不管有沒有顯式的返回指令); 另外一種是非正常退出,它發生在未保護的錯誤發生的時候。 第一種狀況中, coroutine.resume
返回 true , 接下來會跟着 coroutine 主函數的一系列返回值。 第二種發生錯誤的狀況下,coroutine.resume
返回 false , 緊接着是一條錯誤信息。
coroutine 中切換出去,能夠調用 coroutine.yield
。 當 coroutine 切出,與之配合的 coroutine.resume
就當即返回, 甚至在 yield 發生在內層的函數調用中也能夠(就是說, 這不限於發生在主函數中,也能夠是主函數直接或間接調用的某個函數裏)。 在 yield 的狀況下,coroutine.resume
也是返回 true, 緊跟着那些被傳入coroutine.yield
的參數。 等到下次你在繼續一樣的 coroutine ,將從調用 yield 的斷點處運行下去。 斷點處 yield 的返回值將是 coroutine.resume
傳入的參數。
相似 coroutine.create
, coroutine.wrap
這個函數也將建立一個 coroutine , 可是它並不返回 coroutine 自己,而是返回一個函數取而代之。一旦你調用這個返回函數,就會切入 coroutine 運行。 全部傳入這個函數的參數等同於傳入 coroutine.resume
的參數。 coroutine.wrap
會返回全部應該由除第一個(錯誤代碼的那個布爾量) 以外的由 coroutine.resume
返回的值。 和 coroutine.resume
不一樣, coroutine.wrap
不捕獲任何錯誤; 全部的錯誤都應該由調用者本身傳遞。
看下面這段代碼展現的一個例子:
function foo (a) print("foo", a) return coroutine.yield(2*a) end co = coroutine.create(function (a,b) print("co-body", a, b) local r = foo(a+1) print("co-body", r) local r, s = coroutine.yield(a+b, a-b) print("co-body", r, s) return b, "end" end) print("main", coroutine.resume(co, 1, 10)) print("main", coroutine.resume(co, "r")) print("main", coroutine.resume(co, "x", "y")) print("main", coroutine.resume(co, "x", "y"))
當你運行它,將獲得以下輸出結果:
co-body 1 10 foo 2 main true 4 co-body r main true 11 -9 co-body x y main true 10 end main false cannot resume dead coroutine
這個部分描述了 Lua 的 C API , 也就是宿主程序跟 Lua 通信用的一組 C 函數。 全部的 API 函數按相關的類型以及常量都聲明在頭文件 lua.h
中。
雖然咱們說的是「函數」,但一部分簡單的 API 是以宏的形式提供的。 全部的這些宏都只使用它們的參數一次 (除了第一個參數,也就是 lua 狀態機), 所以你不需擔憂這些宏的展開會引發一些反作用。
在全部的 C 庫中,Lua API 函數都不去檢查參數的有效性和堅固性。 然而,你能夠在編譯 Lua 時加上打開一個宏開關來 開啓 luaconf.h
文件中的宏 luai_apicheck
以改變這個行爲。
Lua 使用一個虛擬棧來和 C 傳遞值。 棧上的的每一個元素都是一個 Lua 值 (nil,數字,字符串,等等)。
不管什麼時候 Lua 調用 C,被調用的函數都獲得一個新的棧, 這個棧獨立於 C 函數自己的堆棧,也獨立於之前的棧。 (譯註:在 C 函數裏,用 Lua API 不能訪問到 Lua 狀態機中本次調用以外的堆棧中的數據) 它裏面包含了 Lua 傳遞給 C 函數的全部參數, 而 C 函數則把要返回的結果也放入堆棧以返回給調用者 (參見lua_CFunction
)。
方便起見,全部針對棧的 API 查詢操做都不嚴格遵循棧的操做規則。 而是能夠用一個索引來指向棧上的任何元素: 正的索引指的是棧上的絕對位置(從一開始); 負的索引則指從棧頂開始的偏移量。 更詳細的說明一下,若是堆棧有 n 個元素, 那麼索引 1 表示第一個元素(也就是最早被壓入堆棧的元素) 而索引 n 則指最後一個元素; 索引 -1 也是指最後一個元素(即棧頂的元素), 索引 -n 是指第一個元素。 若是索引在 1 到棧頂之間(也就是,1 ≤ abs(index) ≤ top
) 咱們就說這是個有效的索引。
當你使用 Lua API 時,就有責任保證其堅固性。 特別須要注意的是,你有責任控制不要堆棧溢出。 你可使用 lua_checkstack
這個函數來擴大可用堆棧的尺寸。
不管什麼時候 Lua 調用 C , 它都只保證 LUA_MINSTACK
這麼多的堆棧空間可使用。 LUA_MINSTACK
通常被定義爲 20 , 所以,只要你不是不斷的把數據壓棧,一般你不用關心堆棧大小。
全部的查詢函數均可以接收一個索引,只要這個索引是任何棧提供的空間中的值。 棧能提供的最大空間是經過 lua_checkstack
來設置的。 這些索引被稱做可接受的索引,一般咱們把它定義爲:
(index < 0 && abs(index) <= top) || (index > 0 && index <= stackspace)
注意,0 永遠都不是一個可接受的索引。(譯註:下文中凡提到的索引,沒有特別註明的話,都指可接受的索引。)
除了特別聲明外,任何一個函數均可以接受另外一種有效的索引,它們被稱做「僞索引」。 這個能夠幫助 C 代碼訪問一些並不在棧上的 Lua 值。 僞索引被用來訪問線程的環境,函數的環境,註冊表,還有 C 函數的 upvalue (參見 §3.4)。
線程的環境(也就是全局變量放的地方)一般在僞索引 LUA_GLOBALSINDEX
處。 正在運行的 C 函數的環境則放在僞索引 LUA_ENVIRONINDEX
之處。
你能夠用常規的 table 操做來訪問和改變全局變量的值,只須要指定環境表的位置。 舉例而言,要訪問全局變量的值,這樣作:
lua_getfield(L, LUA_GLOBALSINDEX, varname);
當 C 函數被建立出來,咱們有可能會把一些值關聯在一塊兒, 也就是建立一個 C closure ; 這些被關聯起來的值被叫作 upvalue , 它們能夠在函數被調用的時候訪問的到。 (參見 lua_pushcclosure
)。
不管什麼時候去調用 C 函數,函數的 upvalue 都被放在指定的僞索引處。 咱們能夠用 lua_upvalueindex
這個宏來生成這些僞索引。 第一個關聯到函數的值放在lua_upvalueindex(1)
位置處,依次類推。 任何狀況下均可以用 lua_upvalueindex(n)
產生一個 upvalue 的索引, 即便 n 大於實際的 upvalue 數量也能夠。它均可以產生一個可接受但不必定有效的索引。
Lua 提供了一個註冊表,這是一個預約義出來的表,能夠用來保存任何 C 代碼想保存的 Lua 值。 這個表能夠用僞索引 LUA_REGISTRYINDEX
來定位。 任何 C 庫均可以在這張表裏保存數據,爲了防止衝突,你須要特別當心的選擇鍵名。 通常的用法是,你能夠用一個包含你的庫名的字符串作爲鍵名,或者能夠取你本身 C 代碼 中的一個地址,以 light userdata 的形式作鍵。
註冊表裏的整數健被用於補充庫中實現的引用系統的工做,通常說來不要把它們用於別的用途。
在內部實現中,Lua 使用了 C 的 longjmp
機制來處理錯誤。 (若是你使用 C++ 的話,也能夠選擇換用異常;參見 luaconf.h
文件。) 當 Lua 碰到任何錯誤(好比內存分配錯誤、類型錯誤、語法錯誤、還有一些運行時錯誤) 它都會產生一個錯誤出去; 也就是調用一個 long jump 。 在保護環境下,Lua 使用 setjmp
來設置一個恢復點; 任何發生的錯誤都會激活最近的一個恢復點。
幾乎全部的 API 函數均可能產生錯誤,例如內存分配錯誤。 但下面的一些函數運行在保護環境中(也就是說它們建立了一個保護環境再在其中運行), 所以它們不會產生錯誤出來: lua_newstate
, lua_close
, lua_load
, lua_pcall
, and lua_cpcall
。
在 C 函數裏,你也能夠經過調用 lua_error
產生一個錯誤。
在這裏咱們按字母次序列出了全部 C API 中的函數和類型。
lua_Alloc
typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize);
Lua 狀態機中使用的內存分配器函數的類型。 內存分配函數必須提供一個功能相似於 realloc
但又不徹底相同的函數。 它的參數有 ud
,一個由 lua_newstate
傳給它的指針; ptr
,一個指向已分配出來或是將被從新分配或是要釋放的內存塊指針; osize
,內存塊原來的尺寸; nsize
,新內存塊的尺寸。 若是且只有 osize
是零時,ptr
爲 NULL
。 當 nsize
是零,分配器必須返回 NULL
; 若是 osize
不是零,分配器應當釋放掉 ptr
指向的內存塊。 當 nsize
不是零,若分配器不能知足請求時,分配器返回 NULL
。 當 nsize
不是零而 osize
是零時,分配器應該和 malloc
有相同的行爲。 當 nsize
和 osize
都不是零時,分配器則應和 realloc
保持同樣的行爲。 Lua 假設分配器在 osize >= nsize
時永遠不會失敗。
這裏有一個簡單的分配器函數的實現。 這個實現被放在補充庫中,由 luaL_newstate
提供。
static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; /* not used */ if (nsize == 0) { free(ptr); return NULL; } else return realloc(ptr, nsize); }
這段代碼假設 free(NULL)
啥也不影響,並且 realloc(NULL, size)
等價於 malloc(size)
。 這兩點是 ANSI C 保證的行爲。
lua_atpanic
lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);
設置一個新的 panic (恐慌) 函數,並返回前一個。
若是在保護環境以外發生了任何錯誤, Lua 就會調用一個 panic 函數,接着調用 exit(EXIT_FAILURE)
, 這樣就開始退出宿主程序。 你的 panic 函數能夠永遠不返回(例如做一次長跳轉)來避免程序退出。
panic 函數能夠從棧頂取到出錯信息。
lua_call
void lua_call (lua_State *L, int nargs, int nresults);
調用一個函數。
要調用一個函數請遵循如下協議: 首先,要調用的函數應該被壓入堆棧; 接着,把須要傳遞給這個函數的參數按正序壓棧; 這是指第一個參數首先壓棧。 最後調用一下 lua_call
; nargs
是你壓入堆棧的參數個數。 當函數調用完畢後,全部的參數以及函數自己都會出棧。 而函數的返回值這時則被壓入堆棧。 返回值的個數將被調整爲 nresults
個, 除非 nresults
被設置成 LUA_MULTRET
。 在這種狀況下,全部的返回值都被壓入堆棧中。 Lua 會保證返回值都放入棧空間中。 函數返回值將按正序壓棧(第一個返回值首先壓棧), 所以在調用結束後,最後一個返回值將被放在棧頂。
被調用函數內發生的錯誤將(經過 longjmp
)一直上拋。
下面的例子中,這行 Lua 代碼等價於在宿主程序用 C 代碼作一些工做:
a = f("how", t.x, 14)
這裏是 C 裏的代碼:
lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* 將調用的函數 */ lua_pushstring(L, "how"); /* 第一個參數 */ lua_getfield(L, LUA_GLOBALSINDEX, "t"); /* table 的索引 */ lua_getfield(L, -1, "x"); /* 壓入 t.x 的值(第 2 個參數)*/ lua_remove(L, -2); /* 從堆棧中移去 't' */ lua_pushinteger(L, 14); /* 第 3 個參數 */ lua_call(L, 3, 1); /* 調用 'f',傳入 3 個參數,並索取 1 個返回值 */ lua_setfield(L, LUA_GLOBALSINDEX, "a"); /* 設置全局變量 'a' */
注意上面這段代碼是「平衡」的: 到了最後,堆棧恢復成起因的配置。 這是一種良好的編程習慣。
lua_CFunction
typedef int (*lua_CFunction) (lua_State *L);
C 函數的類型。
爲了正確的和 Lua 通信,C 函數必須使用下列 定義了參數以及返回值傳遞方法的協議: C 函數經過 Lua 中的堆棧來接受參數,參數以正序入棧(第一個參數首先入棧)。 所以,當函數開始的時候, lua_gettop(L)
能夠返回函數收到的參數個數。 第一個參數(若是有的話)在索引 1 的地方,而最後一個參數在索引 lua_gettop(L)
處。 當須要向 Lua 返回值的時候,C 函數只須要把它們以正序壓到堆棧上(第一個返回值最早壓入), 而後返回這些返回值的個數。 在這些返回值之下的,堆棧上的東西都會被 Lua 丟掉。 和 Lua 函數同樣,從 Lua 中調用 C 函數也能夠有不少返回值。
下面這個例子中的函數將接收若干數字參數,並返回它們的平均數與和:
static int foo (lua_State *L) { int n = lua_gettop(L); /* 參數的個數 */ lua_Number sum = 0; int i; for (i = 1; i <= n; i++) { if (!lua_isnumber(L, i)) { lua_pushstring(L, "incorrect argument"); lua_error(L); } sum += lua_tonumber(L, i); } lua_pushnumber(L, sum/n); /* 第一個返回值 */ lua_pushnumber(L, sum); /* 第二個返回值 */ return 2; /* 返回值的個數 */ }
lua_checkstack
int lua_checkstack (lua_State *L, int extra);
確保堆棧上至少有 extra
個空位。 若是不能把堆棧擴展到相應的尺寸,函數返回 false 。 這個函數永遠不會縮小堆棧; 若是堆棧已經比須要的大了,那麼就放在那裏不會產生變化。
lua_close
void lua_close (lua_State *L);
銷燬指定 Lua 狀態機中的全部對象(若是有垃圾收集相關的元方法的話,會調用它們), 而且釋放狀態機中使用的全部動態內存。 在一些平臺上,你能夠沒必要調用這個函數, 由於當宿主程序結束的時候,全部的資源就天然被釋放掉了。 另外一方面,長期運行的程序,好比一個後臺程序或是一個 web 服務器, 當再也不須要它們的時候就應該釋放掉相關狀態機。這樣能夠避免狀態機擴張的過大。
lua_concat
void lua_concat (lua_State *L, int n);
鏈接棧頂的 n
個值, 而後將這些值出棧,並把結果放在棧頂。 若是 n
爲 1 ,結果就是一個字符串放在棧上(即,函數什麼都不作); 若是 n
爲 0 ,結果是一個空串。 鏈接依照 Lua 中建立語義完成(參見 §2.5.4 )。
lua_cpcall
int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);
以保護模式調用 C 函數 func
。 func
只有能從堆棧上拿到一個參數,就是包含有 ud
的 light userdata。 當有錯誤時, lua_cpcall
返回和 lua_pcall
相同的錯誤代碼, 並在棧頂留下錯誤對象; 不然它返回零,並不會修改堆棧。 全部從 func
內返回的值都會被扔掉。
lua_createtable
void lua_createtable (lua_State *L, int narr, int nrec);
建立一個新的空 table 壓入堆棧。 這個新 table 將被預分配 narr
個元素的數組空間 以及 nrec
個元素的非數組空間。 當你明確知道表中須要多少個元素時,預分配就很是有用。 若是你不知道,可使用函數 lua_newtable
。
lua_dump
int lua_dump (lua_State *L, lua_Writer writer, void *data);
把函數 dump 成二進制 chunk 。 函數接收棧頂的 Lua 函數作參數,而後生成它的二進制 chunk 。 若被 dump 出來的東西被再次加載,加載的結果就至關於原來的函數。 當它在產生 chunk 的時候,lua_dump
經過調用函數 writer
(參見 lua_Writer
) 來寫入數據,後面的 data
參數會被傳入 writer
。
最後一次由寫入器 (writer) 返回值將做爲這個函數的返回值返回; 0 表示沒有錯誤。
這個函數不會把 Lua 返回彈出堆棧。
lua_equal
int lua_equal (lua_State *L, int index1, int index2);
若是依照 Lua 中 ==
操做符語義,索引 index1
和 index2
中的值相同的話,返回 1 。 不然返回 0 。 若是任何一個索引無效也會返回 0。
lua_error
int lua_error (lua_State *L);
產生一個 Lua 錯誤。 錯誤信息(實際上能夠是任何類型的 Lua 值)必須被置入棧頂。 這個函數會作一次長跳轉,所以它不會再返回。 (參見 luaL_error
)。
lua_gc
int lua_gc (lua_State *L, int what, int data);
控制垃圾收集器。
這個函數根據其參數 what
發起幾種不一樣的任務:
LUA_GCSTOP
: 中止垃圾收集器。LUA_GCRESTART
: 重啓垃圾收集器。LUA_GCCOLLECT
: 發起一次完整的垃圾收集循環。LUA_GCCOUNT
: 返回 Lua 使用的內存總量(以 K 字節爲單位)。LUA_GCCOUNTB
: 返回當前內存使用量除以 1024 的餘數。LUA_GCSTEP
: 發起一步增量垃圾收集。 步數由 data
控制(越大的值意味着越多步), 而其具體含義(具體數字表示了多少)並未標準化。 若是你想控制這個步數,必須實驗性的測試 data
的值。 若是這一步結束了一個垃圾收集週期,返回返回 1 。LUA_GCSETPAUSE
: 把 data
/100 設置爲 garbage-collector pause 的新值(參見 §2.10)。 函數返回之前的值。LUA_GCSETSTEPMUL
: 把 arg
/100 設置成 step multiplier (參見 §2.10)。 函數返回之前的值。lua_getallocf
lua_Alloc lua_getallocf (lua_State *L, void **ud);
返回給定狀態機的內存分配器函數。 若是 ud
不是 NULL
,Lua 把調用 lua_newstate
時傳入的那個指針放入 *ud
。
lua_getfenv
void lua_getfenv (lua_State *L, int index);
把索引處值的環境表壓入堆棧。
lua_getfield
void lua_getfield (lua_State *L, int index, const char *k);
把 t[k]
值壓入堆棧, 這裏的 t
是指有效索引 index
指向的值。 在 Lua 中,這個函數可能觸發對應 "index" 事件的元方法 (參見 §2.8)。
lua_getglobal
void lua_getglobal (lua_State *L, const char *name);
把全局變量 name
裏的值壓入堆棧。 這個是用一個宏定義出來的:
#define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s)
lua_getmetatable
int lua_getmetatable (lua_State *L, int index);
把給定索引指向的值的元表壓入堆棧。 若是索引無效,或是這個值沒有元表, 函數將返回 0 而且不會向棧上壓任何東西。
lua_gettable
void lua_gettable (lua_State *L, int index);
把 t[k]
值壓入堆棧, 這裏的 t
是指有效索引 index
指向的值, 而 k
則是棧頂放的值。
這個函數會彈出堆棧上的 key (把結果放在棧上相同位置)。 在 Lua 中,這個函數可能觸發對應 "index" 事件的元方法 (參見 §2.8)。
lua_gettop
int lua_gettop (lua_State *L);
返回棧頂元素的索引。 由於索引是從 1 開始編號的, 因此這個結果等於堆棧上的元素個數(所以返回 0 表示堆棧爲空)。
lua_insert
void lua_insert (lua_State *L, int index);
把棧頂元素插入指定的有效索引處, 並依次移動這個索引之上的元素。 不要用僞索引來調用這個函數, 由於僞索引不是真正指向堆棧上的位置。
lua_Integer
typedef ptrdiff_t lua_Integer;
這個類型被用於 Lua API 接收整數值。
缺省時這個被定義爲 ptrdiff_t
, 這個東西一般是機器能處理的最大整數類型。
lua_isboolean
int lua_isboolean (lua_State *L, int index);
當給定索引的值類型爲 boolean 時,返回 1 ,不然返回 0 。
lua_iscfunction
int lua_iscfunction (lua_State *L, int index);
當給定索引的值是一個 C 函數時,返回 1 ,不然返回 0 。
lua_isfunction
int lua_isfunction (lua_State *L, int index);
當給定索引的值是一個函數( C 或 Lua 函數都可)時,返回 1 ,不然返回 0 。
lua_islightuserdata
int lua_islightuserdata (lua_State *L, int index);
當給定索引的值是一個 light userdata 時,返回 1 ,不然返回 0 。
lua_isnil
int lua_isnil (lua_State *L, int index);
當給定索引的值是 nil 時,返回 1 ,不然返回 0 。
lua_isnumber
int lua_isnumber (lua_State *L, int index);
當給定索引的值是一個數字,或是一個可轉換爲數字的字符串時,返回 1 ,不然返回 0 。
lua_isstring
int lua_isstring (lua_State *L, int index);
當給定索引的值是一個字符串或是一個數字(數字總能轉換成字符串)時,返回 1 ,不然返回 0 。
lua_istable
int lua_istable (lua_State *L, int index);
當給定索引的值是一個 table 時,返回 1 ,不然返回 0 。
lua_isthread
int lua_isthread (lua_State *L, int index);
當給定索引的值是一個 thread 時,返回 1 ,不然返回 0 。
lua_isuserdata
int lua_isuserdata (lua_State *L, int index);
當給定索引的值是一個 userdata (不管是完整的 userdata 仍是 light userdata )時,返回 1 ,不然返回 0 。
lua_lessthan
int lua_lessthan (lua_State *L, int index1, int index2);
若是索引 index1
處的值小於 索引 index2
處的值時,返回 1 ; 不然返回 0 。 其語義遵循 Lua 中的 <
操做符(就是說,有可能調用元方法)。 若是任何一個索引無效,也會返回 0 。
lua_load
int lua_load (lua_State *L, lua_Reader reader, void *data, const char *chunkname);
加載一個 Lua chunk 。 若是沒有錯誤, lua_load
把一個編譯好的 chunk 做爲一個 Lua 函數壓入堆棧。 不然,壓入出錯信息。 lua_load
的返回值能夠是:
LUA_ERRSYNTAX
: 在預編譯時碰到語法錯誤;LUA_ERRMEM
: 內存分配錯誤。這個函數僅僅加栽 chunk ;而不會去運行它。
lua_load
會自動檢測 chunk 是文本的仍是二進制的, 而後作對應的加載操做(參見程序 luac
)。
lua_load
函數使用一個用戶提供的 reader
函數來 讀取 chunk (參見 lua_Reader
)。 data
參數會被傳入讀取器函數。
chunkname
這個參數能夠賦予 chunk 一個名字, 這個名字被用於出錯信息和調試信息(參見 §3.8)。
lua_newstate
lua_State *lua_newstate (lua_Alloc f, void *ud);
建立的一個新的獨立的狀態機。 若是建立不了(由於內存問題)返回 NULL
。 參數 f
是一個分配器函數; Lua 將經過這個函數作狀態機內全部的內存分配操做。 第二個參數 ud
,這個指針將在每次調用分配器時被直接傳入。
lua_newtable
void lua_newtable (lua_State *L);
建立一個空 table ,並將之壓入堆棧。 它等價於 lua_createtable(L, 0, 0)
。
lua_newthread
lua_State *lua_newthread (lua_State *L);
建立一個新線程,並將其壓入堆棧, 並返回維護這個線程的 lua_State
指針。 這個函數返回的新狀態機共享原有狀態機中的全部對象(好比一些 table), 可是它有獨立的執行堆棧。
沒有顯式的函數能夠用來關閉或銷燬掉一個線程。 線程跟其它 Lua 對象同樣是垃圾收集的條目之一。
lua_newuserdata
void *lua_newuserdata (lua_State *L, size_t size);
這個函數分配分配一塊指定大小的內存塊, 把內存塊地址做爲一個完整的 userdata 壓入堆棧,並返回這個地址。
userdata 表明 Lua 中的 C 值。 完整的 userdata 表明一塊內存。 它是一個對象(就像 table 那樣的對象): 你必須建立它,它有着本身的元表,並且它在被回收時,能夠被監測到。 一個完整的 userdata 只和它本身相等(在等於的原生做用下)。
當 Lua 經過 gc
元方法回收一個完整的 userdata 時, Lua 調用這個元方法並把 userdata 標記爲已終止。 等到這個 userdata 再次被收集的時候,Lua 會釋放掉相關的內存。
lua_next
int lua_next (lua_State *L, int index);
從棧上彈出一個 key(鍵), 而後把索引指定的表中 key-value(健值)對壓入堆棧 (指定 key 後面的下一 (next) 對)。 若是表中以無更多元素, 那麼 lua_next
將返回 0 (什麼也不壓入堆棧)。
典型的遍歷方法是這樣的:
/* table 放在索引 't' 處 */ lua_pushnil(L); /* 第一個 key */ while (lua_next(L, t) != 0) { /* 用一下 'key' (在索引 -2 處) 和 'value' (在索引 -1 處) */ printf("%s - %s\n", lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1))); /* 移除 'value' ;保留 'key' 作下一次迭代 */ lua_pop(L, 1); }
在遍歷一張表的時候, 不要直接對 key 調用 lua_tolstring
, 除非你知道這個 key 必定是一個字符串。 調用 lua_tolstring
有可能改變給定索引位置的值; 這會對下一次調用 lua_next
形成影響。
lua_Number
typedef double lua_Number;
Lua 中數字的類型。 確省是 double ,可是你能夠在 luaconf.h
中修改它。
經過修改配置文件你能夠改變 Lua 讓它操做其它數字類型(例如:float 或是 long )。
lua_objlen
size_t lua_objlen (lua_State *L, int index);
返回指定的索引處的值的長度。 對於 string ,那就是字符串的長度; 對於 table ,是取長度操做符 ('#
') 的結果; 對於 userdata ,就是爲其分配的內存塊的尺寸; 對於其它值,爲 0 。
lua_pcall
lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);
以保護模式調用一個函數。
nargs
和 nresults
的含義與 lua_call
中的相同。 若是在調用過程當中沒有發生錯誤, lua_pcall
的行爲和 lua_call
徹底一致。 可是,若是有錯誤發生的話, lua_pcall
會捕獲它, 而後把單一的值(錯誤信息)壓入堆棧,而後返回錯誤碼。 同 lua_call
同樣, lua_pcall
老是把函數自己和它的參數從棧上移除。
若是 errfunc
是 0 , 返回在棧頂的錯誤信息就和原始錯誤信息徹底一致。 不然,errfunc
就被當成是錯誤處理函數在棧上的索引。 (在當前的實現裏,這個索引不能是僞索引。) 在發生運行時錯誤時, 這個函數會被調用而參數就是錯誤信息。 錯誤處理函數的返回值將被 lua_pcall
做爲出錯信息返回在堆棧上。
典型的用法中,錯誤處理函數被用來在出錯信息上加上更多的調試信息,好比棧跟蹤信息 (stack traceback) 。 這些信息在 lua_pcall
返回後,由於棧已經展開 (unwound) , 因此收集不到了。
lua_pcall
函數在調用成功時返回 0 , 不然返回如下(定義在 lua.h
中的)錯誤代碼中的一個:
lua_pop
void lua_pop (lua_State *L, int n);
從堆棧中彈出 n
個元素。
lua_pushboolean
void lua_pushboolean (lua_State *L, int b);
把 b
做爲一個 boolean 值壓入堆棧。
lua_pushcclosure
void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
把一個新的 C closure 壓入堆棧。
當建立了一個 C 函數後,你能夠給它關聯一些值,這樣就是在建立一個 C closure (參見 §3.4); 接下來不管函數什麼時候被調用,這些值均可以被這個函數訪問到。 爲了將一些值關聯到一個 C 函數上, 首先這些值須要先被壓入堆棧(若是有多個值,第一個先壓)。 接下來調用 lua_pushcclosure
來建立出 closure 並把這個 C 函數壓到堆棧上。 參數 n
告之函數有多少個值須要關聯到函數上。 lua_pushcclosure
也會把這些值從棧上彈出。
lua_pushcfunction
void lua_pushcfunction (lua_State *L, lua_CFunction f);
將一個 C 函數壓入堆棧。 這個函數接收一個 C 函數指針,並將一個類型爲 function
的 Lua 值 壓入堆棧。當這個棧頂的值被調用時,將觸發對應的 C 函數。
註冊到 Lua 中的任何函數都必須遵循正確的協議來接收參數和返回值 (參見 lua_CFunction
)。
lua_pushcfunction
是做爲一個宏定義出現的:
#define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0)
lua_pushfstring
const char *lua_pushfstring (lua_State *L, const char *fmt, ...);
把一個格式化過的字符串壓入堆棧,而後返回這個字符串的指針。 它和 C 函數 sprintf
比較像,不過有一些重要的區別:
%%
' (插入一個 '%
'), '%s
' (插入一個帶零終止符的字符串,沒有長度限制), '%f
' (插入一個 lua_Number
), '%p
' (插入一個指針或是一個十六進制數), '%d
' (插入一個 int
), '%c
' (把一個 int
做爲一個字符插入)。lua_pushinteger
void lua_pushinteger (lua_State *L, lua_Integer n);
把 n
做爲一個數字壓棧。
lua_pushlightuserdata
void lua_pushlightuserdata (lua_State *L, void *p);
把一個 light userdata 壓棧。
userdata 在 Lua 中表示一個 C 值。 light userdata 表示一個指針。 它是一個像數字同樣的值: 你不須要專門建立它,它也沒有獨立的 metatable , 並且也不會被收集(由於歷來不須要建立)。 只要表示的 C 地址相同,兩個 light userdata 就相等。
lua_pushlstring
void lua_pushlstring (lua_State *L, const char *s, size_t len);
把指針 s
指向的長度爲 len
的字符串壓棧。 Lua 對這個字符串作一次內存拷貝(或是複用一個拷貝), 所以 s
處的內存在函數返回後,能夠釋放掉或是重用於其它用途。 字符串內能夠保存有零字符。
lua_pushnil
void lua_pushnil (lua_State *L);
把一個 nil 壓棧。
lua_pushnumber
void lua_pushnumber (lua_State *L, lua_Number n);
把一個數字 n
壓棧。
lua_pushstring
void lua_pushstring (lua_State *L, const char *s);
把指針 s
指向的以零結尾的字符串壓棧。 Lua 對這個字符串作一次內存拷貝(或是複用一個拷貝), 所以 s
處的內存在函數返回後,能夠釋放掉或是重用於其它用途。 字符串中不能包含有零字符;第一個碰到的零字符會認爲是字符串的結束。
lua_pushthread
int lua_pushthread (lua_State *L);
把 L
中提供的線程壓棧。 若是這個線程是當前狀態機的主線程的話,返回 1 。
lua_pushvalue
void lua_pushvalue (lua_State *L, int index);
把堆棧上給定有效處索引處的元素做一個拷貝壓棧。
lua_pushvfstring
const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp);
等價於 lua_pushfstring
, 不過是用 va_list
接收參數,而不是用可變數量的實際參數。
lua_rawequal
int lua_rawequal (lua_State *L, int index1, int index2);
若是兩個索引 index1
和 index2
處的值簡單地相等 (不調用元方法)則返回 1 。 不然返回 0 。 若是任何一個索引無效也返回 0 。
lua_rawget
void lua_rawget (lua_State *L, int index);
相似於 lua_gettable
, 可是做一次直接訪問(不觸發元方法)。
lua_rawgeti
void lua_rawgeti (lua_State *L, int index, int n);
把 t[n]
的值壓棧, 這裏的 t
是指給定索引 index
處的一個值。 這是一個直接訪問;就是說,它不會觸發元方法。
lua_rawset
void lua_rawset (lua_State *L, int index);
相似於 lua_settable
, 可是是做一個直接賦值(不觸發元方法)。
lua_rawseti
void lua_rawseti (lua_State *L, int index, int n);
等價於 t[n] = v
, 這裏的 t
是指給定索引 index
處的一個值, 而 v
是棧頂的值。
函數將把這個值彈出棧。 賦值操做是直接的;就是說,不會觸發元方法。
lua_Reader
typedef const char * (*lua_Reader) (lua_State *L, void *data, size_t *size);
lua_load
用到的讀取器函數, 每次它須要一塊新的 chunk 的時候, lua_load
就調用讀取器, 每次都會傳入一個參數 data
。 讀取器須要返回含有新的 chunk 的一塊內存的指針, 並把 size
設爲這塊內存的大小。 內存塊必須在下一次函數被調用以前一直存在。 讀取器能夠經過返回一個 NULL
來指示 chunk 結束。 讀取器可能返回多個塊,每一個塊能夠有任意的大於零的尺寸。
lua_register
void lua_register (lua_State *L, const char *name, lua_CFunction f);
把 C 函數 f
設到全局變量 name
中。 它經過一個宏定義:
#define lua_register(L,n,f) \ (lua_pushcfunction(L, f), lua_setglobal(L, n))
lua_remove
void lua_remove (lua_State *L, int index);
從給定有效索引處移除一個元素, 把這個索引之上的全部元素移下來填補上這個空隙。 不能用僞索引來調用這個函數, 由於僞索引並不指向真實的棧上的位置。
lua_replace
void lua_replace (lua_State *L, int index);
把棧頂元素移動到給定位置(而且把這個棧頂元素彈出), 不移動任何元素(所以在那個位置處的值被覆蓋掉)。
lua_resume
int lua_resume (lua_State *L, int narg);
在給定線程中啓動或繼續一個 coroutine 。
要啓動一個 coroutine 的話,首先你要建立一個新線程 (參見 lua_newthread
); 而後把主函數和若干參數壓到新線程的堆棧上; 最後調用 lua_resume
, 把 narg
設爲參數的個數。 此次調用會在 coroutine 掛起時或是結束運行後返回。 當函數返回時,堆棧中會有傳給 lua_yield
的全部值, 或是主函數的全部返回值。 若是 coroutine 切換時,lua_resume
返回 LUA_YIELD
, 而當 coroutine 結束運行且沒有任何錯誤時,返回 0 。 若是有錯則返回錯誤代碼(參見 lua_pcall
)。 在發生錯誤的狀況下, 堆棧沒有展開, 所以你可使用 debug API 來處理它。 出錯信息放在棧頂。 要繼續運行一個 coroutine 的話,你把須要傳給 yield
做結果的返回值壓入堆棧,而後調用 lua_resume
。
lua_setallocf
void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);
把指定狀態機的分配器函數換成帶上指針 ud
的 f
。
lua_setfenv
int lua_setfenv (lua_State *L, int index);
從堆棧上彈出一個 table 並把它設爲指定索引處值的新環境。 若是指定索引處的值即不是函數又不是線程或是 userdata , lua_setfenv
會返回 0 , 不然返回 1 。
lua_setfield
void lua_setfield (lua_State *L, int index, const char *k);
作一個等價於 t[k] = v
的操做, 這裏 t
是給出的有效索引 index
處的值, 而 v
是棧頂的那個值。
這個函數將把這個值彈出堆棧。 跟在 Lua 中同樣,這個函數可能觸發一個 "newindex" 事件的元方法 (參見 §2.8)。
lua_setglobal
void lua_setglobal (lua_State *L, const char *name);
從堆棧上彈出一個值,並將其設到全局變量 name
中。 它由一個宏定義出來:
#define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s)
lua_setmetatable
int lua_setmetatable (lua_State *L, int index);
把一個 table 彈出堆棧,並將其設爲給定索引處的值的 metatable 。
lua_settable
void lua_settable (lua_State *L, int index);
做一個等價於 t[k] = v
的操做, 這裏 t
是一個給定有效索引 index
處的值, v
指棧頂的值, 而 k
是棧頂之下的那個值。
這個函數會把鍵和值都從堆棧中彈出。 和在 Lua 中同樣,這個函數可能觸發 "newindex" 事件的元方法 (參見 §2.8)。
lua_settop
void lua_settop (lua_State *L, int index);
參數容許傳入任何可接受的索引以及 0 。 它將把堆棧的棧頂設爲這個索引。 若是新的棧頂比原來的大,超出部分的新元素將被填爲 nil 。 若是 index
爲 0 ,把棧上全部元素移除。
lua_State
typedef struct lua_State lua_State;
一個不透明的結構,它保存了整個 Lua 解釋器的狀態。 Lua 庫是徹底可重入的: 它沒有任何全局變量。 (譯註:從 C 語法上來講,也不盡然。例如,在 table 的實現中 用了一個靜態全局變量 dummynode_ ,但這在正確使用時並不影響可重入性。 只是萬一你錯誤連接了 lua 庫,不當心在同一進程空間中存在兩份 lua 庫實現的代碼的話, 多份 dummynode_ 不一樣的地址會致使一些問題。) 全部的信息都保存在這個結構中。
這個狀態機的指針必須做爲第一個參數傳遞給每個庫函數。 lua_newstate
是一個例外, 這個函數會從頭建立一個 Lua 狀態機。
lua_status
int lua_status (lua_State *L);
返回線程 L
的狀態。
正常的線程狀態是 0 。 當線程執行完畢或發生一個錯誤時,狀態值是錯誤碼。 若是線程被掛起,狀態爲 LUA_YIELD
。
lua_toboolean
int lua_toboolean (lua_State *L, int index);
把指定的索引處的的 Lua 值轉換爲一個 C 中的 boolean 值( 0 或是 1 )。 和 Lua 中作的全部測試同樣, lua_toboolean
會把任何 不一樣於 false 和 nil 的值看成 1 返回; 不然就返回 0 。 若是用一個無效索引去調用也會返回 0 。 (若是你想只接收真正的 boolean 值,就須要使用 lua_isboolean
來測試值的類型。)
lua_tocfunction
lua_CFunction lua_tocfunction (lua_State *L, int index);
把給定索引處的 Lua 值轉換爲一個 C 函數。 這個值必須是一個 C 函數;若是不是就返回 NULL
。
lua_tointeger
lua_Integer lua_tointeger (lua_State *L, int idx);
把給定索引處的 Lua 值轉換爲 lua_Integer
這樣一個有符號整數類型。 這個 Lua 值必須是一個數字或是一個能夠轉換爲數字的字符串 (參見 §2.2.1); 不然,lua_tointeger
返回 0 。
若是數字不是一個整數, 截斷小數部分的方式沒有被明肯定義。
lua_tolstring
const char *lua_tolstring (lua_State *L, int index, size_t *len);
把給定索引處的 Lua 值轉換爲一個 C 字符串。 若是 len
不爲 NULL
, 它還把字符串長度設到 *len
中。 這個 Lua 值必須是一個字符串或是一個數字; 不然返回返回 NULL
。 若是值是一個數字,lua_tolstring
還會把堆棧中的那個值的實際類型轉換爲一個字符串。 (當遍歷一個表的時候,把 lua_tolstring
做用在鍵上,這個轉換有可能致使 lua_next
弄錯。)
lua_tolstring
返回 Lua 狀態機中 字符串的以對齊指針。 這個字符串總能保證 ( C 要求的)最後一個字符爲零 ('\0
') , 並且它容許在字符串內包含多個這樣的零。 由於 Lua 中可能發生垃圾收集, 因此不保證 lua_tolstring
返回的指針, 在對應的值從堆棧中移除後依然有效。
lua_tonumber
lua_Number lua_tonumber (lua_State *L, int index);
把給定索引處的 Lua 值轉換爲 lua_Number
這樣一個 C 類型(參見 lua_Number
)。 這個 Lua 值必須是一個數字或是一個可轉換爲數字的字符串 (參見 §2.2.1 ); 不然,lua_tonumber
返回 0 。
lua_topointer
const void *lua_topointer (lua_State *L, int index);
把給定索引處的值轉換爲通常的 C 指針 (void*
) 。 這個值能夠是一個 userdata ,table ,thread 或是一個 function ; 不然,lua_topointer
返回 NULL
。 不一樣的對象有不一樣的指針。 不存在把指針再轉回原有類型的方法。
這個函數一般只爲產生 debug 信息用。
lua_tostring
const char *lua_tostring (lua_State *L, int index);
等價於 lua_tolstring
,而參數 len
設爲 NULL
。
lua_tothread
lua_State *lua_tothread (lua_State *L, int index);
把給定索引處的值轉換爲一個 Lua 線程(由 lua_State*
表明)。 這個值必須是一個線程;不然函數返回 NULL
。
lua_touserdata
void *lua_touserdata (lua_State *L, int index);
若是給定索引處的值是一個完整的 userdata ,函數返回內存塊的地址。 若是值是一個 light userdata ,那麼就返回它表示的指針。 不然,返回 NULL
。
lua_type
int lua_type (lua_State *L, int index);
返回給定索引處的值的類型, 當索引無效時則返回 LUA_TNONE
(那是指一個指向堆棧上的空位置的索引)。 lua_type
返回的類型是一些個在 lua.h
中定義的常量:LUA_TNIL
, LUA_TNUMBER
, LUA_TBOOLEAN
, LUA_TSTRING
, LUA_TTABLE
, LUA_TFUNCTION
, LUA_TUSERDATA
, LUA_TTHREAD
, LUA_TLIGHTUSERDATA
。
lua_typename
const char *lua_typename (lua_State *L, int tp);
返回 tp
表示的類型名, 這個 tp
必須是 lua_type
可能返回的值中之一。
lua_Writer
typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud);
由 lua_dump
用到的寫入器函數。 每次 lua_dump
產生了一塊新的 chunk ,它都會調用寫入器。 傳入要寫入的緩存 (p
) 和它的尺寸 (sz
) , 還有 lua_dump
的參數 data
。
寫入器會返回一個錯誤碼: 0 表示沒有錯誤; 別的值均表示一個錯誤,而且會讓 lua_dump
中止再次調用寫入器。
lua_xmove
void lua_xmove (lua_State *from, lua_State *to, int n);
傳遞 同一個 全局狀態機下不一樣線程中的值。
這個函數會從 from
的堆棧中彈出 n
個值, 而後把它們壓入 to
的堆棧中。
lua_yield
int lua_yield (lua_State *L, int nresults);
切出一個 coroutine 。
這個函數只能在一個 C 函數的返回表達式中調用。以下:
return lua_yield (L, nresults);
當一個 C 函數這樣調用 lua_yield
, 正在運行中的 coroutine 將從運行中掛起, 而後啓動這個 coroutine 用的那次對 lua_resume
的調用就返回了。 參數 nresults
指的是堆棧中須要返回的結果個數,這些返回值將被傳遞給 lua_resume
。
Lua 沒有內建的調試設施。 取而代之的是提供了一些函數接口和鉤子。 利用這些接口,能夠作出一些不一樣類型的調試器, 性能分析器,或是其它一些須要從解釋器中取到「內部信息」的工具。
lua_Debug
typedef struct lua_Debug { int event; const char *name; /* (n) */ const char *namewhat; /* (n) */ const char *what; /* (S) */ const char *source; /* (S) */ int currentline; /* (l) */ int nups; /* (u) upvalue 個數 */ int linedefined; /* (S) */ int lastlinedefined; /* (S) */ char short_src[LUA_IDSIZE]; /* (S) */ /* 私有部分 */ 其它域 } lua_Debug;
一個用來攜帶活動中函數的各類信息的結構。 lua_getstack
僅填寫這個結構中的私有部分, 這些部分之後會用到。 調用 lua_getinfo
則能夠填上 lua_Debug
中有用信息的那些域。
lua_Debug
中的各個域有下列含義:
source
: 若是函數是定義在一個字符串中,source
就是這個字符串。 若是函數定義在一個文件中, source
是一個以 '@
' 開頭的文件名。short_src
: 一個「可打印版本」的 source
,用於出錯信息。linedefined
: 函數定義開始處的行號。lastlinedefined
: 函數定義結束處的行號。what
: 若是函數是一個 Lua 函數,則爲一個字符串 "Lua"
; 若是是一個 C 函數,則爲 "C"
; 若是它是一個 chunk 的主體部分,則爲 "main"
; 若是是一個做了尾調用的函數,則爲 "tail"
。 別的狀況下,Lua 沒有關於函數的別的信息。currentline
: 給定函數正在執行的那一行。 當提供不了行號信息的時候,currentline
被設爲 -1 。name
: 給定函數的一個合理的名字。 由於 Lua 中的函數也是一個值, 因此它們沒有固定的名字: 一些函數多是全局複合變量的值, 另外一些可能僅僅只是被保存在一個 table 中。 lua_getinfo
函數會檢查函數是這樣被調用的,以此來找到一個適合的名字。 若是它找不到名字,name
就被設置爲 NULL
。namewhat
: 結實 name
域。 namewhat
的值能夠是 "global"
, "local"
, "method"
, "field"
, "upvalue"
, 或是 ""
(空串)。 這取決於函數怎樣被調用。 (Lua 用空串表示其它選項都不符合)nups
: 函數的 upvalue 的個數。lua_gethook
lua_Hook lua_gethook (lua_State *L);
返回當前的鉤子函數。
lua_gethookcount
int lua_gethookcount (lua_State *L);
返回當前鉤子記數。
lua_gethookmask
int lua_gethookmask (lua_State *L);
返回當前的鉤子掩碼 (mask) 。
lua_getinfo
int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
返回一個指定的函數或函數調用的信息。
當用於取得一次函數調用的信息時, 參數 ar
必須是一個有效的活動的記錄。 這條記錄能夠是前一次調用 lua_getstack
獲得的, 或是一個鉤子 (參見 lua_Hook
)獲得的參數。
用於獲取一個函數的信息時,能夠把這個函數壓入堆棧, 而後把 what
字符串以字符 '>
' 起頭。 (這個狀況下,lua_getinfo
從棧頂上彈出函數。) 例如,想知道函數 f
在哪一行定義的, 你能夠下下列代碼:
lua_Debug ar; lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* 取到全局變量 'f' */ lua_getinfo(L, ">S", &ar); printf("%d\n", ar.linedefined);
what
字符串中的每一個字符都篩選出結構 ar
結構中一些域用於填充,或是把一個值壓入堆棧:
n
': 填充 name
及 namewhat
域;S
': 填充 source
, short_src
, linedefined
, lastlinedefined
,以及 what
域;l
': 填充 currentline
域;u
': 填充 nups
域;f
': 把正在運行中指定級別處函數壓入堆棧; (譯註:通常用於獲取函數調用中的信息, 級別是由 ar 中的私有部分來提供。 若是用於獲取靜態函數,那麼就直接把指定函數從新壓回堆棧, 但這樣作一般無甚意義。)L
': 壓一個 table 入棧,這個 table 中的整數索引用於描述函數中哪些行是有效行。 (有效行指有實際代碼的行, 即你能夠置入斷點的行。 無效行包括空行和只有註釋的行。)這個函數出錯會返回 0 (例如,what
中有一個無效選項)。
lua_getlocal
const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);
從給定活動記錄中獲取一個局部變量的信息。 參數 ar
必須是一個有效的活動的記錄。 這條記錄能夠是前一次調用 lua_getstack
獲得的, 或是一個鉤子 (參見lua_Hook
)獲得的參數。 索引 n
用於選擇要檢閱哪一個局部變量 ( 1 表示第一個參數或是激活的第一個局部變量,以此類推,直到最後一個局部變量)。 lua_getlocal
把變量的值壓入堆棧並返回它的名字。
以 '(' (正小括號)開始的變量指內部變量 (循環控制變量,臨時變量,C 函數局部變量)。
當索引大於局部變量的個數時,返回 NULL
(什麼也不壓入)。
lua_getstack
int lua_getstack (lua_State *L, int level, lua_Debug *ar);
獲取解釋器的運行時棧的信息。
這個函數用正在運行中的給定級別處的函數的活動記錄來填寫 lua_Debug
結構的一部分。 0 級表示當前運行的函數, 而 n+1 級處的函數就是調用第 n 級函數的那一個。 若是沒有錯誤,lua_getstack
返回 1 ; 當調用傳入的級別大於堆棧深度的時候,返回 0 。
lua_getupvalue
const char *lua_getupvalue (lua_State *L, int funcindex, int n);
獲取一個 closure 的 upvalue 信息。 (對於 Lua 函數,upvalue 是函數須要使用的外部局部變量, 所以這些變量被包含在 closure 中。) lua_getupvalue
獲取第n
個 upvalue , 把這個 upvalue 的值壓入堆棧,而且返回它的名字。 funcindex
指向堆棧上 closure 的位置。 ( 由於 upvalue 在整個函數中都有效,因此它們沒有特別的次序。 所以,它們以字母次序來編號。)
當索引號比 upvalue 數量大的時候,返回 NULL
(並且不會壓入任何東西) 對於 C 函數,這個函數用空串 ""
表示全部 upvalue 的名字。
lua_Hook
typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
用於調試的鉤子函數類型。
不管什麼時候鉤子被調用,它的參數 ar
中的 event
域 都被設爲觸發鉤子的事件。 Lua 把這些事件定義爲如下常量: LUA_HOOKCALL
, LUA_HOOKRET
, LUA_HOOKTAILRET
,LUA_HOOKLINE
, and LUA_HOOKCOUNT
。 除此以外,對於 line 事件,currentline
域也被設置。 要想得到 ar
中的其餘域, 鉤子必須調用 lua_getinfo
。 對於返回事件,event
的正常值多是 LUA_HOOKRET
, 或者是 LUA_HOOKTAILRET
。 對於後一種狀況,Lua 會對一個函數作的尾調用也模擬出一個返回事件出來; 對於這個模擬的返回事件,調用 lua_getinfo
沒有什麼做用。
當 Lua 運行在一個鉤子內部時,它將屏蔽掉其它對鉤子的調用。 也就是說,若是一個鉤子函數內再調回 Lua 來執行一個函數或是一個 chunk , 這個執行操做不會觸發任何的鉤子。
lua_sethook
int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);
設置一個調試用鉤子函數。
參數 f
是鉤子函數。 mask
指定在哪些事件時會調用: 它由下列一組位常量構成 LUA_MASKCALL
, LUA_MASKRET
, LUA_MASKLINE
, 以及 LUA_MASKCOUNT
。 參數 count
只在 mask 中包含有 LUA_MASKCOUNT
纔有意義。 對於每一個事件,鉤子被調用的狀況解釋以下:
count
條指令後被調用。 (這個事件僅僅在 Lua 執行一個 Lua 函數時發生。)鉤子能夠經過設置 mask
爲零屏蔽。
lua_setlocal
const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);
設置給定活動記錄中的局部變量的值。 參數 ar
與 n
和 lua_getlocal
中的同樣 (參見 lua_getlocal
)。 lua_setlocal
把棧頂的值賦給變量而後返回變量的名字。 它會將值從棧頂彈出。
當索引大於局部變量的個數時,返回 NULL
(什麼也不彈出)。
lua_setupvalue
const char *lua_setupvalue (lua_State *L, int funcindex, int n);
設置 closure 的 upvalue 的值。 它把棧頂的值彈出並賦於 upvalue 並返回 upvalue 的名字。 參數 funcindex
與 n
和 lua_getupvalue
中的同樣 (參見lua_getupvalue
)。
當索引大於 upvalue 的個數時,返回 NULL
(什麼也不彈出)。
The auxiliary library provides several convenient functions to interface C with Lua. While the basic API provides the primitive functions for all interactions between C and Lua, the auxiliary library provides higher-level functions for some common tasks.
All functions from the auxiliary library are defined in header file lauxlib.h
and have a prefix luaL_
.
All functions in the auxiliary library are built on top of the basic API, and so they provide nothing that cannot be done with this API.
Several functions in the auxiliary library are used to check C function arguments. Their names are always luaL_check*
or luaL_opt*
. All of these functions raise an error if the check is not satisfied. Because the error message is formatted for arguments (e.g., "bad argument #1
"), you should not use these functions for other stack values.
Here we list all functions and types from the auxiliary library in alphabetical order.
luaL_addchar
void luaL_addchar (luaL_Buffer *B, char c);
Adds the character c
to the buffer B
(see luaL_Buffer
).
luaL_addlstring
void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);
Adds the string pointed to by s
with length l
to the buffer B
(see luaL_Buffer
). The string may contain embedded zeros.
luaL_addsize
void luaL_addsize (luaL_Buffer *B, size_t n);
Adds to the buffer B
(see luaL_Buffer
) a string of length n
previously copied to the buffer area (see luaL_prepbuffer
).
luaL_addstring
void luaL_addstring (luaL_Buffer *B, const char *s);
Adds the zero-terminated string pointed to by s
to the buffer B
(see luaL_Buffer
). The string may not contain embedded zeros.
luaL_addvalue
void luaL_addvalue (luaL_Buffer *B);
Adds the value at the top of the stack to the buffer B
(see luaL_Buffer
). Pops the value.
This is the only function on string buffers that can (and must) be called with an extra element on the stack, which is the value to be added to the buffer.
luaL_argcheck
void luaL_argcheck (lua_State *L, int cond, int narg, const char *extramsg);
Checks whether cond
is true. If not, raises an error with the following message, where func
is retrieved from the call stack:
bad argument #<narg> to <func> (<extramsg>)
luaL_argerror
int luaL_argerror (lua_State *L, int narg, const char *extramsg);
Raises an error with the following message, where func
is retrieved from the call stack:
bad argument #<narg> to <func> (<extramsg>)
This function never returns, but it is an idiom to use it in C functions as return luaL_argerror(args)
.
luaL_Buffer
typedef struct luaL_Buffer luaL_Buffer;
Type for a string buffer.
A string buffer allows C code to build Lua strings piecemeal. Its pattern of use is as follows:
b
of type luaL_Buffer
.luaL_buffinit(L, &b)
.luaL_add*
functions.luaL_pushresult(&b)
. This call leaves the final string on the top of the stack.During its normal operation, a string buffer uses a variable number of stack slots. So, while using a buffer, you cannot assume that you know where the top of the stack is. You can use the stack between successive calls to buffer operations as long as that use is balanced; that is, when you call a buffer operation, the stack is at the same level it was immediately after the previous buffer operation. (The only exception to this rule is luaL_addvalue
.) After calling luaL_pushresult
the stack is back to its level when the buffer was initialized, plus the final string on its top.
luaL_buffinit
void luaL_buffinit (lua_State *L, luaL_Buffer *B);
Initializes a buffer B
. This function does not allocate any space; the buffer must be declared as a variable (see luaL_Buffer
).
luaL_callmeta
int luaL_callmeta (lua_State *L, int obj, const char *e);
Calls a metamethod.
If the object at index obj
has a metatable and this metatable has a field e
, this function calls this field and passes the object as its only argument. In this case this function returns 1 and pushes onto the stack the value returned by the call. If there is no metatable or no metamethod, this function returns 0 (without pushing any value on the stack).
luaL_checkany
void luaL_checkany (lua_State *L, int narg);
Checks whether the function has an argument of any type (including nil) at position narg
.
luaL_checkint
int luaL_checkint (lua_State *L, int narg);
Checks whether the function argument narg
is a number and returns this number cast to an int
.
luaL_checkinteger
lua_Integer luaL_checkinteger (lua_State *L, int narg);
Checks whether the function argument narg
is a number and returns this number cast to a lua_Integer
.
luaL_checklong
long luaL_checklong (lua_State *L, int narg);
Checks whether the function argument narg
is a number and returns this number cast to a long
.
luaL_checklstring
const char *luaL_checklstring (lua_State *L, int narg, size_t *l);
Checks whether the function argument narg
is a string and returns this string; if l
is not NULL
fills *l
with the string's length.
luaL_checknumber
lua_Number luaL_checknumber (lua_State *L, int narg);
Checks whether the function argument narg
is a number and returns this number.
luaL_checkoption
int luaL_checkoption (lua_State *L, int narg, const char *def, const char *const lst[]);
Checks whether the function argument narg
is a string and searches for this string in the array lst
(which must be NULL-terminated). Returns the index in the array where the string was found. Raises an error if the argument is not a string or if the string cannot be found.
If def
is not NULL
, the function uses def
as a default value when there is no argument narg
or if this argument is nil.
This is a useful function for mapping strings to C enums. (The usual convention in Lua libraries is to use strings instead of numbers to select options.)
luaL_checkstack
void luaL_checkstack (lua_State *L, int sz, const char *msg);
Grows the stack size to top + sz
elements, raising an error if the stack cannot grow to that size. msg
is an additional text to go into the error message.
luaL_checkstring
const char *luaL_checkstring (lua_State *L, int narg);
Checks whether the function argument narg
is a string and returns this string.
luaL_checktype
void luaL_checktype (lua_State *L, int narg, int t);
Checks whether the function argument narg
has type t
.
luaL_checkudata
void *luaL_checkudata (lua_State *L, int narg, const char *tname);
Checks whether the function argument narg
is a userdata of the type tname
(see luaL_newmetatable
).
luaL_dofile
int luaL_dofile (lua_State *L, const char *filename);
Loads and runs the given file. It is defined as the following macro:
(luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
It returns 0 if there are no errors or 1 in case of errors.
luaL_dostring
int luaL_dostring (lua_State *L, const char *str);
Loads and runs the given string. It is defined as the following macro:
(luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
It returns 0 if there are no errors or 1 in case of errors.
luaL_error
int luaL_error (lua_State *L, const char *fmt, ...);
Raises an error. The error message format is given by fmt
plus any extra arguments, following the same rules of lua_pushfstring
. It also adds at the beginning of the message the file name and the line number where the error occurred, if this information is available.
This function never returns, but it is an idiom to use it in C functions as return luaL_error(args)
.
luaL_getmetafield
int luaL_getmetafield (lua_State *L, int obj, const char *e);
Pushes onto the stack the field e
from the metatable of the object at index obj
. If the object does not have a metatable, or if the metatable does not have this field, returns 0 and pushes nothing.
luaL_getmetatable
void luaL_getmetatable (lua_State *L, const char *tname);
Pushes onto the stack the metatable associated with name tname
in the registry (see luaL_newmetatable
).
luaL_gsub
const char *luaL_gsub (lua_State *L, const char *s, const char *p, const char *r);
Creates a copy of string s
by replacing any occurrence of the string p
with the string r
. Pushes the resulting string on the stack and returns it.
luaL_loadbuffer
int luaL_loadbuffer (lua_State *L, const char *buff, size_t sz, const char *name);
Loads a buffer as a Lua chunk. This function uses lua_load
to load the chunk in the buffer pointed to by buff
with size sz
.
This function returns the same results as lua_load
. name
is the chunk name, used for debug information and error messages.
luaL_loadfile
int luaL_loadfile (lua_State *L, const char *filename);
Loads a file as a Lua chunk. This function uses lua_load
to load the chunk in the file named filename
. If filename
is NULL
, then it loads from the standard input. The first line in the file is ignored if it starts with a #
.
This function returns the same results as lua_load
, but it has an extra error code LUA_ERRFILE
if it cannot open/read the file.
As lua_load
, this function only loads the chunk; it does not run it.
luaL_loadstring
int luaL_loadstring (lua_State *L, const char *s);
Loads a string as a Lua chunk. This function uses lua_load
to load the chunk in the zero-terminated string s
.
This function returns the same results as lua_load
.
Also as lua_load
, this function only loads the chunk; it does not run it.
luaL_newmetatable
int luaL_newmetatable (lua_State *L, const char *tname);
If the registry already has the key tname
, returns 0. Otherwise, creates a new table to be used as a metatable for userdata, adds it to the registry with key tname
, and returns 1.
In both cases pushes onto the stack the final value associated with tname
in the registry.
luaL_newstate
lua_State *luaL_newstate (void);
Creates a new Lua state. It calls lua_newstate
with an allocator based on the standard C realloc
function and then sets a panic function (seelua_atpanic
) that prints an error message to the standard error output in case of fatal errors.
Returns the new state, or NULL
if there is a memory allocation error.
luaL_openlibs
void luaL_openlibs (lua_State *L);
Opens all standard Lua libraries into the given state.
luaL_optint
int luaL_optint (lua_State *L, int narg, int d);
If the function argument narg
is a number, returns this number cast to an int
. If this argument is absent or is nil, returns d
. Otherwise, raises an error.
luaL_optinteger
lua_Integer luaL_optinteger (lua_State *L, int narg, lua_Integer d);
If the function argument narg
is a number, returns this number cast to a lua_Integer
. If this argument is absent or is nil, returns d
. Otherwise, raises an error.
luaL_optlong
long luaL_optlong (lua_State *L, int narg, long d);
If the function argument narg
is a number, returns this number cast to a long
. If this argument is absent or is nil, returns d
. Otherwise, raises an error.
luaL_optlstring
const char *luaL_optlstring (lua_State *L, int narg, const char *d, size_t *l);
If the function argument narg
is a string, returns this string. If this argument is absent or is nil, returns d
. Otherwise, raises an error.
If l
is not NULL
, fills the position *l
with the results's length.
luaL_optnumber
lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);
If the function argument narg
is a number, returns this number. If this argument is absent or is nil, returns d
. Otherwise, raises an error.
luaL_optstring
const char *luaL_optstring (lua_State *L, int narg, const char *d);
If the function argument narg
is a string, returns this string. If this argument is absent or is nil, returns d
. Otherwise, raises an error.
luaL_prepbuffer
char *luaL_prepbuffer (luaL_Buffer *B);
Returns an address to a space of size LUAL_BUFFERSIZE
where you can copy a string to be added to buffer B
(see luaL_Buffer
). After copying the string into this space you must call luaL_addsize
with the size of the string to actually add it to the buffer.
luaL_pushresult
void luaL_pushresult (luaL_Buffer *B);
Finishes the use of buffer B
leaving the final string on the top of the stack.
luaL_ref
int luaL_ref (lua_State *L, int t);
Creates and returns a reference, in the table at index t
, for the object at the top of the stack (and pops the object).
A reference is a unique integer key. As long as you do not manually add integer keys into table t
, luaL_ref
ensures the uniqueness of the key it returns. You can retrieve an object referred by reference r
by calling lua_rawgeti(L, t, r)
. Function luaL_unref
frees a reference and its associated object.
If the object at the top of the stack is nil, luaL_ref
returns the constant LUA_REFNIL
. The constant LUA_NOREF
is guaranteed to be different from any reference returned by luaL_ref
.
luaL_Reg
typedef struct luaL_Reg { const char *name; lua_CFunction func; } luaL_Reg;
Type for arrays of functions to be registered by luaL_register
. name
is the function name and func
is a pointer to the function. Any array of luaL_Reg
must end with an sentinel entry in which both name
and func
are NULL
.
luaL_register
void luaL_register (lua_State *L, const char *libname, const luaL_Reg *l);
Opens a library.
When called with libname
equal to NULL
, it simply registers all functions in the list l
(see luaL_Reg
) into the table on the top of the stack.
When called with a non-null libname
, luaL_register
creates a new table t
, sets it as the value of the global variable libname
, sets it as the value ofpackage.loaded[libname]
, and registers on it all functions in the list l
. If there is a table in package.loaded[libname]
or in variable libname
, reuses this table instead of creating a new one.
In any case the function leaves the table on the top of the stack.
luaL_typename
const char *luaL_typename (lua_State *L, int idx);
Returns the name of the type of the value at index idx
.
luaL_typerror
int luaL_typerror (lua_State *L, int narg, const char *tname);
Generates an error with a message like the following:
location: bad argument narg to 'func' (tname expected, got rt)
where location
is produced by luaL_where
, func
is the name of the current function, and rt
is the type name of the actual argument.
luaL_unref
void luaL_unref (lua_State *L, int t, int ref);
Releases reference ref
from the table at index t
(see luaL_ref
). The entry is removed from the table, so that the referred object can be collected. The reference ref
is also freed to be used again.
If ref
is LUA_NOREF
or LUA_REFNIL
, luaL_unref
does nothing.
luaL_where
void luaL_where (lua_State *L, int lvl);
Pushes onto the stack a string identifying the current position of the control at level lvl
in the call stack. Typically this string has the following format:
chunkname:currentline:
Level 0 is the running function, level 1 is the function that called the running function, etc.
This function is used to build a prefix for error messages.
The standard Lua libraries provide useful functions that are implemented directly through the C API. Some of these functions provide essential services to the language (e.g., type
and getmetatable
); others provide access to "outside" services (e.g., I/O); and others could be implemented in Lua itself, but are quite useful or have critical performance requirements that deserve an implementation in C (e.g., sort
).
All libraries are implemented through the official C API and are provided as separate C modules. Currently, Lua has the following standard libraries:
Except for the basic and package libraries, each library provides all its functions as fields of a global table or as methods of its objects.
To have access to these libraries, the C host program should call the luaL_openlibs
function, which opens all standard libraries. Alternatively, it can open them individually by calling luaopen_base
(for the basic library), luaopen_package
(for the package library), luaopen_string
(for the string library), luaopen_table
(for the table library), luaopen_math
(for the mathematical library), luaopen_io
(for the I/O and the Operating System libraries), and luaopen_debug
(for the debug library). These functions are declared in lualib.h
and should not be called directly: you must call them like any other Lua C function, e.g., by using lua_call
.
The basic library provides some core functions to Lua. If you do not include this library in your application, you should check carefully whether you need to provide implementations for some of its facilities.
assert (v [, message])
Issues an error when the value of its argument v
is false (i.e., nil or false); otherwise, returns all its arguments. message
is an error message; when absent, it defaults to "assertion failed!"
collectgarbage (opt [, arg])
This function is a generic interface to the garbage collector. It performs different functions according to its first argument, opt
:
arg
(larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value of arg
. Returns true if the step finished a collection cycle.arg
/100 as the new value for the pause of the collector (see §2.10).arg
/100 as the new value for the step multiplier of the collector (see §2.10).
dofile (filename)
Opens the named file and executes its contents as a Lua chunk. When called without arguments, dofile
executes the contents of the standard input (stdin
). Returns all values returned by the chunk. In case of errors, dofile
propagates the error to its caller (that is, dofile
does not run in protected mode).
error (message [, level])
Terminates the last protected function called and returns message
as the error message. Function error
never returns.
Usually, error
adds some information about the error position at the beginning of the message. The level
argument specifies how to get the error position. With level 1 (the default), the error position is where the error
function was called. Level 2 points the error to where the function that called error
was called; and so on. Passing a level 0 avoids the addition of error position information to the message.
_G
A global variable (not a function) that holds the global environment (that is, _G._G = _G
). Lua itself does not use this variable; changing its value does not affect any environment, nor vice-versa. (Use setfenv
to change environments.)
getfenv (f)
Returns the current environment in use by the function. f
can be a Lua function or a number that specifies the function at that stack level: Level 1 is the function calling getfenv
. If the given function is not a Lua function, or if f
is 0, getfenv
returns the global environment. The default for f
is 1.
getmetatable (object)
If object
does not have a metatable, returns nil. Otherwise, if the object's metatable has a "__metatable"
field, returns the associated value. Otherwise, returns the metatable of the given object.
ipairs (t)
Returns three values: an iterator function, the table t
, and 0, so that the construction
for i,v in ipairs(t) do body end
will iterate over the pairs (1,t[1]
), (2,t[2]
), ···, up to the first integer key absent from the table.
load (func [, chunkname])
Loads a chunk using function func
to get its pieces. Each call to func
must return a string that concatenates with previous results. A return ofnil (or no value) signals the end of the chunk.
If there are no errors, returns the compiled chunk as a function; otherwise, returns nil plus the error message. The environment of the returned function is the global environment.
chunkname
is used as the chunk name for error messages and debug information.
loadfile ([filename])
Similar to load
, but gets the chunk from file filename
or from the standard input, if no file name is given.
loadstring (string [, chunkname])
Similar to load
, but gets the chunk from the given string.
To load and run a given string, use the idiom
assert(loadstring(s))()
next (table [, index])
Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. next
returns the next index of the table and its associated value. When called with nil as its second argument, next
returns an initial index and its associated value. When called with the last index, or with nil in an empty table, next
returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can use next(t)
to check whether a table is empty.
The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numeric order, use a numericalfor or the ipairs
function.)
The behavior of next
is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields.
pairs (t)
Returns three values: the next
function, the table t
, and nil, so that the construction
for k,v in pairs(t) do body end
will iterate over all key–value pairs of table t
.
See function next
for the caveats of modifying the table during its traversal.
pcall (f, arg1, ···)
Calls function f
with the given arguments in protected mode. This means that any error inside f
is not propagated; instead, pcall
catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case,pcall
also returns all results from the call, after this first result. In case of any error, pcall
returns false plus the error message.
print (···)
Receives any number of arguments, and prints their values to stdout
, using the tostring
function to convert them to strings. print
is not intended for formatted output, but only as a quick way to show a value, typically for debugging. For formatted output, use string.format
.
rawequal (v1, v2)
Checks whether v1
is equal to v2
, without invoking any metamethod. Returns a boolean.
rawget (table, index)
Gets the real value of table[index]
, without invoking any metamethod. table
must be a table; index
may be any value.
rawset (table, index, value)
Sets the real value of table[index]
to value
, without invoking any metamethod. table
must be a table, index
any value different from nil, and value
any Lua value.
This function returns table
.
select (index, ···)
If index
is a number, returns all arguments after argument number index
. Otherwise, index
must be the string "#"
, and select
returns the total number of extra arguments it received.
setfenv (f, table)
Sets the environment to be used by the given function. f
can be a Lua function or a number that specifies the function at that stack level: Level 1 is the function calling setfenv
. setfenv
returns the given function.
As a special case, when f
is 0 setfenv
changes the environment of the running thread. In this case, setfenv
returns no values.
setmetatable (table, metatable)
Sets the metatable for the given table. (You cannot change the metatable of other types from Lua, only from C.) If metatable
is nil, removes the metatable of the given table. If the original metatable has a "__metatable"
field, raises an error.
This function returns table
.
tonumber (e [, base])
Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber
returns this number; otherwise, it returns nil.
An optional argument specifies the base to interpret the numeral. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A
' (in either upper or lower case) represents 10, 'B
' represents 11, and so forth, with 'Z
' representing 35. In base 10 (the default), the number may have a decimal part, as well as an optional exponent part (see §2.1). In other bases, only unsigned integers are accepted.
tostring (e)
Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, usestring.format
.
If the metatable of e
has a "__tostring"
field, then tostring
calls the corresponding value with e
as argument, and uses the result of the call as its result.
type (v)
Returns the type of its only argument, coded as a string. The possible results of this function are "nil
" (a string, not the value nil), "number
", "string
", "boolean
", "table
", "function
", "thread
", and "userdata
".
unpack (list [, i [, j]])
Returns the elements from the given table. This function is equivalent to
return list[i], list[i+1], ···, list[j]
except that the above code can be written only for a fixed number of elements. By default, i
is 1 and j
is the length of the list, as defined by the length operator (see §2.5.5).
_VERSION
A global variable (not a function) that holds a string containing the current interpreter version. The current contents of this variable is "Lua 5.1
".
xpcall (f, err)
This function is similar to pcall
, except that you can set a new error handler.
xpcall
calls function f
in protected mode, using err
as the error handler. Any error inside f
is not propagated; instead, xpcall
catches the error, calls the err
function with the original error object, and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In this case, xpcall
also returns all results from the call, after this first result. In case of any error, xpcall
returns false plus the result from err
.
The operations related to coroutines comprise a sub-library of the basic library and come inside the table coroutine
. See §2.11 for a general description of coroutines.
coroutine.create (f)
Creates a new coroutine, with body f
. f
must be a Lua function. Returns this new coroutine, an object with type "thread"
.
coroutine.resume (co [, val1, ···])
Starts or continues the execution of coroutine co
. The first time you resume a coroutine, it starts running its body. The values val1
, ··· are passed as the arguments to the body function. If the coroutine has yielded, resume
restarts it; the values val1
, ··· are passed as the results from the yield.
If the coroutine runs without any errors, resume
returns true plus any values passed to yield
(if the coroutine yields) or any values returned by the body function (if the coroutine terminates). If there is any error, resume
returns false plus the error message.
coroutine.running ()
Returns the running coroutine, or nil when called by the main thread.
coroutine.status (co)
Returns the status of coroutine co
, as a string: "running"
, if the coroutine is running (that is, it called status
); "suspended"
, if the coroutine is suspended in a call to yield
, or if it has not started running yet; "normal"
if the coroutine is active but not running (that is, it has resumed another coroutine); and "dead"
if the coroutine has finished its body function, or if it has stopped with an error.
coroutine.wrap (f)
Creates a new coroutine, with body f
. f
must be a Lua function. Returns a function that resumes the coroutine each time it is called. Any arguments passed to the function behave as the extra arguments to resume
. Returns the same values returned by resume
, except the first boolean. In case of error, propagates the error.
coroutine.yield (···)
Suspends the execution of the calling coroutine. The coroutine cannot be running a C function, a metamethod, or an iterator. Any arguments toyield
are passed as extra results to resume
.
The package library provides basic facilities for loading and building modules in Lua. It exports two of its functions directly in the global environment: require
and module
. Everything else is exported in a table package
.
module (name [, ···])
Creates a module. If there is a table in package.loaded[name]
, this table is the module. Otherwise, if there is a global table t
with the given name, this table is the module. Otherwise creates a new table t
and sets it as the value of the global name
and the value of package.loaded[name]
. This function also initializes t._NAME
with the given name, t._M
with the module (t
itself), and t._PACKAGE
with the package name (the full module name minus last component; see below). Finally, module
sets t
as the new environment of the current function and the new value of package.loaded[name]
, so that require
returns t
.
If name
is a compound name (that is, one with components separated by dots), module
creates (or reuses, if they already exist) tables for each component. For instance, if name
is a.b.c
, then module
stores the module table in field c
of field b
of global a
.
This function may receive optional options after the module name, where each option is a function to be applied over the module.
require (modname)
Loads the given module. The function starts by looking into the package.loaded
table to determine whether modname
is already loaded. If it is, thenrequire
returns the value stored at package.loaded[modname]
. Otherwise, it tries to find a loader for the module.
To find a loader, first require
queries package.preload[modname]
. If it has a value, this value (which should be a function) is the loader. Otherwiserequire
searches for a Lua loader using the path stored in package.path
. If that also fails, it searches for a C loader using the path stored inpackage.cpath
. If that also fails, it tries an all-in-one loader (see below).
When loading a C library, require
first uses a dynamic link facility to link the application with the library. Then it tries to find a C function inside this library to be used as the loader. The name of this C function is the string "luaopen_
" concatenated with a copy of the module name where each dot is replaced by an underscore. Moreover, if the module name has a hyphen, its prefix up to (and including) the first hyphen is removed. For instance, if the module name is a.v1-b.c
, the function name will be luaopen_b_c
.
If require
finds neither a Lua library nor a C library for a module, it calls the all-in-one loader. This loader searches the C path for a library for the root name of the given module. For instance, when requiring a.b.c
, it will search for a C library for a
. If found, it looks into it for an open function for the submodule; in our example, that would be luaopen_a_b_c
. With this facility, a package can pack several C submodules into one single library, with each submodule keeping its original open function.
Once a loader is found, require
calls the loader with a single argument, modname
. If the loader returns any value, require
assigns the returned value to package.loaded[modname]
. If the loader returns no value and has not assigned any value to package.loaded[modname]
, then require
assigns true to this entry. In any case, require
returns the final value of package.loaded[modname]
.
If there is any error loading or running the module, or if it cannot find any loader for the module, then require
signals an error.
package.cpath
The path used by require
to search for a C loader.
Lua initializes the C path package.cpath
in the same way it initializes the Lua path package.path
, using the environment variable LUA_CPATH
(plus another default path defined in luaconf.h
).
package.loaded
A table used by require
to control which modules are already loaded. When you require a module modname
and package.loaded[modname]
is not false, require
simply returns the value stored there.
package.loadlib (libname, funcname)
Dynamically links the host program with the C library libname
. Inside this library, looks for a function funcname
and returns this function as a C function. (So, funcname
must follow the protocol (see lua_CFunction
)).
This is a low-level function. It completely bypasses the package and module system. Unlike require
, it does not perform any path searching and does not automatically adds extensions. libname
must be the complete file name of the C library, including if necessary a path and extension. funcname
must be the exact name exported by the C library (which may depend on the C compiler and linker used).
This function is not supported by ANSI C. As such, it is only available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, plus other Unix systems that support the dlfcn
standard).
package.path
The path used by require
to search for a Lua loader.
At start-up, Lua initializes this variable with the value of the environment variable LUA_PATH
or with a default path defined in luaconf.h
, if the environment variable is not defined. Any ";;
" in the value of the environment variable is replaced by the default path.
A path is a sequence of templates separated by semicolons. For each template, require
will change each interrogation mark in the template byfilename
, which is modname
with each dot replaced by a "directory separator" (such as "/
" in Unix); then it will try to load the resulting file name. So, for instance, if the Lua path is
"./?.lua;./?.lc;/usr/local/?/init.lua"
the search for a Lua loader for module foo
will try to load the files ./foo.lua
, ./foo.lc
, and /usr/local/foo/init.lua
, in that order.
package.preload
A table to store loaders for specific modules (see require
).
package.seeall (module)
Sets a metatable for module
with its __index
field referring to the global environment, so that this module inherits values from the global environment. To be used as an option to function module
.
This library provides generic functions for string manipulation, such as finding and extracting substrings, and pattern matching. When indexing a string in Lua, the first character is at position 1 (not at 0, as in C). Indices are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on.
The string library provides all its functions inside the table string
. It also sets a metatable for strings where the __index
field points to thestring
table. Therefore, you can use the string functions in object-oriented style. For instance, string.byte(s, i)
can be written as s:byte(i)
.
string.byte (s [, i [, j]])
Returns the internal numerical codes of the characters s[i]
, s[i+1]
, ···, s[j]
. The default value for i
is 1; the default value for j
is i
.
Note that numerical codes are not necessarily portable across platforms.
string.char (···)
Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument.
Note that numerical codes are not necessarily portable across platforms.
string.dump (function)
Returns a string containing a binary representation of the given function, so that a later loadstring
on this string returns a copy of the function.function
must be a Lua function without upvalues.
string.find (s, pattern [, init [, plain]])
Looks for the first match of pattern
in the string s
. If it finds a match, then find
returns the indices of s
where this occurrence starts and ends; otherwise, it returns nil. A third, optional numerical argument init
specifies where to start the search; its default value is 1 and may be negative. A value of true as a fourth, optional argument plain
turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in pattern
being considered "magic". Note that if plain
is given, then init
must be given as well.
If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.
string.format (formatstring, ···)
Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the printf
family of standard C functions. The only differences are that the options/modifiers *
, l
, L
,n
, p
, and h
are not supported and that there is an extra option, q
. The q
option formats a string in a form suitable to be safely read back by the Lua interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written. For instance, the call
string.format('%q', 'a string with "quotes" and \n new line')
will produce the string:
"a string with \"quotes\" and \ new line"
The options c
, d
, E
, e
, f
, g
, G
, i
, o
, u
, X
, and x
all expect a number as argument, whereas q
and s
expect a string.
This function does not accept string values containing embedded zeros.
string.gmatch (s, pattern)
Returns an iterator function that, each time it is called, returns the next captures from pattern
over string s
.
If pattern
specifies no captures, then the whole match is produced in each call.
As an example, the following loop
s = "hello world from Lua" for w in string.gmatch(s, "%a+") do print(w) end
will iterate over all the words from string s
, printing one per line. The next example collects all pairs key=value
from the given string into a table:
t = {} s = "from=world, to=Lua" for k, v in string.gmatch(s, "(%w+)=(%w+)") do t[k] = v end
string.gsub (s, pattern, repl [, n])
Returns a copy of s
in which all occurrences of the pattern
have been replaced by a replacement string specified by repl
, which may be a string, a table, or a function. gsub
also returns, as its second value, the total number of substitutions made.
If repl
is a string, then its value is used for replacement. The character %
works as an escape character: any sequence in repl
of the form %n
, with n between 1 and 9, stands for the value of the n-th captured substring (see below). The sequence %0
stands for the whole match. The sequence%%
stands for a single %
.
If repl
is a table, then the table is queried for every match, using the first capture as the key; if the pattern specifies no captures, then the whole match is used as the key.
If repl
is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order; if the pattern specifies no captures, then the whole match is passed as a sole argument.
If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).
The optional last parameter n
limits the maximum number of substitutions to occur. For instance, when n
is 1 only the first occurrence of pattern
is replaced.
Here are some examples:
x = string.gsub("hello world", "(%w+)", "%1 %1") --> x="hello hello world world" x = string.gsub("hello world", "%w+", "%0 %0", 1) --> x="hello hello world" x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") --> x="world hello Lua from" x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv) --> x="home = /home/roberto, user = roberto" x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) return loadstring(s)() end) --> x="4+5 = 9" local t = {name="lua", version="5.1"} x = string.gsub("$name%-$version.tar.gz", "%$(%w+)", t) --> x="lua-5.1.tar.gz"
string.len (s)
Receives a string and returns its length. The empty string ""
has length 0. Embedded zeros are counted, so "a\000bc\000"
has length 5.
string.lower (s)
Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged. The definition of what an uppercase letter is depends on the current locale.
string.match (s, pattern [, init])
Looks for the first match of pattern
in the string s
. If it finds one, then match
returns the captures from the pattern; otherwise it returns nil. If pattern
specifies no captures, then the whole match is returned. A third, optional numerical argument init
specifies where to start the search; its default value is 1 and may be negative.
string.rep (s, n)
Returns a string that is the concatenation of n
copies of the string s
.
string.reverse (s)
Returns a string that is the string s
reversed.
string.sub (s, i [, j])
Returns the substring of s
that starts at i
and continues until j
; i
and j
may be negative. If j
is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call string.sub(s,1,j)
returns a prefix of s
with length j
, and string.sub(s, -i)
returns a suffix of s
with length i
.
string.upper (s)
Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged. The definition of what a lowercase letter is depends on the current locale.
A character class is used to represent a set of characters. The following combinations are allowed in describing a character class:
^$()%.[]*+-?
) represents the character x itself..
: (a dot) represents all characters.%a
: represents all letters.%c
: represents all control characters.%d
: represents all digits.%l
: represents all lowercase letters.%p
: represents all punctuation characters.%s
: represents all space characters.%u
: represents all uppercase letters.%w
: represents all alphanumeric characters.%x
: represents all hexadecimal digits.%z
: represents the character with representation 0.%x
: (where x is any non-alphanumeric character) represents the character x. This is the standard way to escape the magic characters. Any punctuation character (even the non magic) can be preceded by a '%
' when used to represent itself in a pattern.[set]
: represents the class which is the union of all characters in set. A range of characters may be specified by separating the end characters of the range with a '-
'. All classes %
x described above may also be used as components in set. All other characters in setrepresent themselves. For example, [%w_]
(or [_%w]
) represents all alphanumeric characters plus the underscore, [0-7]
represents the octal digits, and [0-7%l%-]
represents the octal digits plus the lowercase letters plus the '-
' character. The interaction between ranges and classes is not defined. Therefore, patterns like [%a-z]
or [a-%%]
have no meaning.
[^set]
: represents the complement of set, where set is interpreted as above.For all classes represented by single letters (%a
, %c
, etc.), the corresponding uppercase letter represents the complement of the class. For instance, %S
represents all non-space characters.
The definitions of letter, space, and other character groups depend on the current locale. In particular, the class [a-z]
may not be equivalent to%l
.
A pattern item may be
*
', which matches 0 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;+
', which matches 1 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;-
', which also matches 0 or more repetitions of characters in the class. Unlike '*
', these repetition items will always match the shortest possible sequence;?
', which matches 0 or 1 occurrence of a character in the class;%n
, for n between 1 and 9; such item matches a substring equal to the n-th captured string (see below);%bxy
, where x and y are two distinct characters; such item matches strings that start with x, end with y, and where the x and y arebalanced. This means that, if one reads the string from left to right, counting +1 for an x and -1 for a y, the ending y is the first y where the count reaches 0. For instance, the item %b()
matches expressions with balanced parentheses.A pattern is a sequence of pattern items. A '^
' at the beginning of a pattern anchors the match at the beginning of the subject string. A '$
' at the end of a pattern anchors the match at the end of the subject string. At other positions, '^
' and '$
' have no special meaning and represent themselves.
A pattern may contain sub-patterns enclosed in parentheses; they describe captures. When a match succeeds, the substrings of the subject string that match captures are stored (captured) for future use. Captures are numbered according to their left parentheses. For instance, in the pattern"(a*(.)%w(%s*))"
, the part of the string matching "a*(.)%w(%s*)"
is stored as the first capture (and therefore has number 1); the character matching ".
" is captured with number 2, and the part matching "%s*
" has number 3.
As a special case, the empty capture ()
captures the current string position (a number). For instance, if we apply the pattern "()aa()"
on the string "flaaap"
, there will be two captures: 3 and 5.
A pattern cannot contain embedded zeros. Use %z
instead.
This library provides generic functions for table manipulation. It provides all its functions inside the table table
.
Most functions in the table library assume that the table represents an array or a list. For these functions, when we talk about the "length" of a table we mean the result of the length operator.
table.concat (table [, sep [, i [, j]]])
Given an array where all elements are strings or numbers, returns table[i]..sep..table[i+1] ··· sep..table[j]
. The default value for sep
is the empty string, the default for i
is 1, and the default for j
is the length of the table. If i
is greater than j
, returns the empty string.
table.insert (table, [pos,] value)
Inserts element value
at position pos
in table
, shifting up other elements to open space, if necessary. The default value for pos
is n+1
, where n
is the length of the table (see §2.5.5), so that a call table.insert(t,x)
inserts x
at the end of table t
.
table.maxn (table)
Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.)
table.remove (table [, pos])
Removes from table
the element at position pos
, shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for pos
is n
, where n
is the length of the table, so that a call table.remove(t)
removes the last element of table t
.
table.sort (table [, comp])
Sorts table elements in a given order, in-place, from table[1]
to table[n]
, where n
is the length of the table. If comp
is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that not comp(a[i+1],a[i])
will be true after the sort). If comp
is not given, then the standard Lua operator <
is used instead.
The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.
This library is an interface to the standard C math library. It provides all its functions inside the table math
.
math.abs (x)
Returns the absolute value of x
.
math.acos (x)
Returns the arc cosine of x
(in radians).
math.asin (x)
Returns the arc sine of x
(in radians).
math.atan (x)
Returns the arc tangent of x
(in radians).
math.atan2 (x, y)
Returns the arc tangent of x/y
(in radians), but uses the signs of both parameters to find the quadrant of the result. (It also handles correctly the case of y
being zero.)
math.ceil (x)
Returns the smallest integer larger than or equal to x
.
math.cos (x)
Returns the cosine of x
(assumed to be in radians).
math.cosh (x)
Returns the hyperbolic cosine of x
.
math.deg (x)
Returns the angle x
(given in radians) in degrees.
math.exp (x)
Returns the the value ex.
math.floor (x)
Returns the largest integer smaller than or equal to x
.
math.fmod (x, y)
Returns the remainder of the division of x
by y
.
math.frexp (x)
Returns m
and e
such that x = m2e, e
is an integer and the absolute value of m
is in the range [0.5, 1) (or zero when x
is zero).
math.huge
The value HUGE_VAL
, a value larger than or equal to any other numerical value.
math.ldexp (m, e)
Returns m2e (e
should be an integer).
math.log (x)
Returns the natural logarithm of x
.
math.log10 (x)
Returns the base-10 logarithm of x
.
math.max (x, ···)
Returns the maximum value among its arguments.
math.min (x, ···)
Returns the minimum value among its arguments.
math.modf (x)
Returns two numbers, the integral part of x
and the fractional part of x
.
math.pi
The value of pi.
math.pow (x, y)
Returns xy. (You can also use the expression x^y
to compute this value.)
math.rad (x)
Returns the angle x
(given in degrees) in radians.
math.random ([m [, n]])
This function is an interface to the simple pseudo-random generator function rand
provided by ANSI C. (No guarantees can be given for its statistical properties.)
When called without arguments, returns a pseudo-random real number in the range [0,1). When called with a number m
, math.random
returns a pseudo-random integer in the range [1, m]. When called with two numbers m
and n
, math.random
returns a pseudo-random integer in the range [m, n].
math.randomseed (x)
Sets x
as the "seed" for the pseudo-random generator: equal seeds produce equal sequences of numbers.
math.sin (x)
Returns the sine of x
(assumed to be in radians).
math.sinh (x)
Returns the hyperbolic sine of x
.
math.sqrt (x)
Returns the square root of x
. (You can also use the expression x^0.5
to compute this value.)
math.tan (x)
Returns the tangent of x
(assumed to be in radians).
math.tanh (x)
Returns the hyperbolic tangent of x
.
The I/O library provides two different styles for file manipulation. The first one uses implicit file descriptors; that is, there are operations to set a default input file and a default output file, and all input/output operations are over these default files. The second style uses explicit file descriptors.
When using implicit file descriptors, all operations are supplied by table io
. When using explicit file descriptors, the operation io.open
returns a file descriptor and then all operations are supplied as methods of the file descriptor.
The table io
also provides three predefined file descriptors with their usual meanings from C: io.stdin
, io.stdout
, and io.stderr
.
Unless otherwise stated, all I/O functions return nil on failure (plus an error message as a second result) and some value different from nil on success.
io.close ([file])
Equivalent to file:close()
. Without a file
, closes the default output file.
io.flush ()
Equivalent to file:flush
over the default output file.
io.input ([file])
When called with a file name, it opens the named file (in text mode), and sets its handle as the default input file. When called with a file handle, it simply sets this file handle as the default input file. When called without parameters, it returns the current default input file.
In case of errors this function raises the error, instead of returning an error code.
io.lines ([filename])
Opens the given file name in read mode and returns an iterator function that, each time it is called, returns a new line from the file. Therefore, the construction
for line in io.lines(filename) do body end
will iterate over all lines of the file. When the iterator function detects the end of file, it returns nil (to finish the loop) and automatically closes the file.
The call io.lines()
(with no file name) is equivalent to io.input():lines()
; that is, it iterates over the lines of the default input file. In this case it does not close the file when the loop ends.
io.open (filename [, mode])
This function opens a file, in the mode specified in the string mode
. It returns a new file handle, or, in case of errors, nil plus an error message.
The mode
string can be any of the following:
The mode
string may also have a 'b
' at the end, which is needed in some systems to open the file in binary mode. This string is exactly what is used in the standard C function fopen
.
io.output ([file])
Similar to io.input
, but operates over the default output file.
io.popen (prog [, mode])
Starts program prog
in a separated process and returns a file handle that you can use to read data from this program (if mode
is "r"
, the default) or to write data to this program (if mode
is "w"
).
This function is system dependent and is not available on all platforms.
io.read (···)
Equivalent to io.input():read
.
io.tmpfile ()
Returns a handle for a temporary file. This file is opened in update mode and it is automatically removed when the program ends.
io.type (obj)
Checks whether obj
is a valid file handle. Returns the string "file"
if obj
is an open file handle, "closed file"
if obj
is a closed file handle, ornil if obj
is not a file handle.
io.write (···)
Equivalent to io.output():write
.
file:close ()
Closes file
. Note that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen.
file:flush ()
Saves any written data to file
.
file:lines ()
Returns an iterator function that, each time it is called, returns a new line from the file. Therefore, the construction
for line in file:lines() do body end
will iterate over all lines of the file. (Unlike io.lines
, this function does not close the file when the loop ends.)
file:read (···)
Reads the file file
, according to the given formats, which specify what to read. For each format, the function returns a string (or a number) with the characters read, or nil if it cannot read data with the specified format. When called without formats, it uses a default format that reads the entire next line (see below).
The available formats are
file:seek ([whence] [, offset])
Sets and gets the file position, measured from the beginning of the file, to the position given by offset
plus a base specified by the stringwhence
, as follows:
In case of success, function seek
returns the final file position, measured in bytes from the beginning of the file. If this function fails, it returns nil, plus a string describing the error.
The default value for whence
is "cur"
, and for offset
is 0. Therefore, the call file:seek()
returns the current file position, without changing it; the call file:seek("set")
sets the position to the beginning of the file (and returns 0); and the call file:seek("end")
sets the position to the end of the file, and returns its size.
file:setvbuf (mode [, size])
Sets the buffering mode for an output file. There are three available modes:
flush
the file (see io.flush
)).For the last two cases, sizes
specifies the size of the buffer, in bytes. The default is an appropriate size.
file:write (···)
Writes the value of each of its arguments to the file
. The arguments must be strings or numbers. To write other values, use tostring
or string.format
before write
.
This library is implemented through table os
.
os.clock ()
Returns an approximation of the amount in seconds of CPU time used by the program.
os.date ([format [, time]])
Returns a string or a table containing date and time, formatted according to the given string format
.
If the time
argument is present, this is the time to be formatted (see the os.time
function for a description of this value). Otherwise, date
formats the current time.
If format
starts with '!
', then the date is formatted in Coordinated Universal Time. After this optional character, if format
is the string "*t
", then date
returns a table with the following fields: year
(four digits), month
(1--12), day
(1--31), hour
(0--23), min
(0--59), sec
(0--61), wday
(weekday, Sunday is 1), yday
(day of the year), and isdst
(daylight saving flag, a boolean).
If format
is not "*t
", then date
returns the date as a string, formatted according to the same rules as the C function strftime
.
When called without arguments, date
returns a reasonable date and time representation that depends on the host system and on the current locale (that is, os.date()
is equivalent to os.date("%c")
).
os.difftime (t2, t1)
Returns the number of seconds from time t1
to time t2
. In POSIX, Windows, and some other systems, this value is exactly t2
-t1
.
os.execute ([command])
This function is equivalent to the C function system
. It passes command
to be executed by an operating system shell. It returns a status code, which is system-dependent. If command
is absent, then it returns nonzero if a shell is available and zero otherwise.
os.exit ([code])
Calls the C function exit
, with an optional code
, to terminate the host program. The default value for code
is the success code.
os.getenv (varname)
Returns the value of the process environment variable varname
, or nil if the variable is not defined.
os.remove (filename)
Deletes the file or directory with the given name. Directories must be empty to be removed. If this function fails, it returns nil, plus a string describing the error.
os.rename (oldname, newname)
Renames file or directory named oldname
to newname
. If this function fails, it returns nil, plus a string describing the error.
os.setlocale (locale [, category])
Sets the current locale of the program. locale
is a string specifying a locale; category
is an optional string describing which category to change:"all"
, "collate"
, "ctype"
, "monetary"
, "numeric"
, or "time"
; the default category is "all"
. The function returns the name of the new locale, or nil if the request cannot be honored.
When called with nil as the first argument, this function only returns the name of the current locale for the given category.
os.time ([table])
Returns the current time when called without arguments, or a time representing the date and time specified by the given table. This table must have fields year
, month
, and day
, and may have fields hour
, min
, sec
, and isdst
(for a description of these fields, see the os.date
function).
The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the "epoch"). In other systems, the meaning is not specified, and the number returned by time
can be used only as an argument to date
and difftime
.
os.tmpname ()
Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed.
This library provides the functionality of the debug interface to Lua programs. You should exert care when using this library. The functions provided here should be used exclusively for debugging and similar tasks, such as profiling. Please resist the temptation to use them as a usual programming tool: they can be very slow. Moreover, several of its functions violate some assumptions about Lua code (e.g., that variables local to a function cannot be accessed from outside or that userdata metatables cannot be changed by Lua code) and therefore can compromise otherwise secure code.
All functions in this library are provided inside the debug
table. All functions that operate over a thread have an optional first argument which is the thread to operate over. The default is always the current thread.
debug.debug ()
Enters an interactive mode with the user, running each string that the user enters. Using simple commands and other debug facilities, the user can inspect global and local variables, change their values, evaluate expressions, and so on. A line containing only the word cont
finishes this function, so that the caller continues its execution.
Note that commands for debug.debug
are not lexically nested within any function, and so have no direct access to local variables.
debug.getfenv (o)
Returns the environment of object o
.
debug.gethook ([thread])
Returns the current hook settings of the thread, as three values: the current hook function, the current hook mask, and the current hook count (as set by the debug.sethook
function).
debug.getinfo ([thread,] function [, what])
Returns a table with information about a function. You can give the function directly, or you can give a number as the value of function
, which means the function running at level function
of the call stack of the given thread: level 0 is the current function (getinfo
itself); level 1 is the function that called getinfo
; and so on. If function
is a number larger than the number of active functions, then getinfo
returns nil.
The returned table may contain all the fields returned by lua_getinfo
, with the string what
describing which fields to fill in. The default for what
is to get all information available, except the table of valid lines. If present, the option 'f
' adds a field named func
with the function itself. If present, the option 'L
' adds a field named activelines
with the table of valid lines.
For instance, the expression debug.getinfo(1,"n").name
returns a name of the current function, if a reasonable name can be found, and the expressiondebug.getinfo(print)
returns a table with all available information about the print
function.
debug.getlocal ([thread,] level, local)
This function returns the name and the value of the local variable with index local
of the function at level level
of the stack. (The first parameter or local variable has index 1, and so on, until the last active local variable.) The function returns nil if there is no local variable with the given index, and raises an error when called with a level
out of range. (You can call debug.getinfo
to check whether the level is valid.)
Variable names starting with '(
' (open parentheses) represent internal variables (loop control variables, temporaries, and C function locals).
debug.getmetatable (object)
Returns the metatable of the given object
or nil if it does not have a metatable.
debug.getregistry ()
Returns the registry table (see §3.5).
debug.getupvalue (func, up)
This function returns the name and the value of the upvalue with index up
of the function func
. The function returns nil if there is no upvalue with the given index.
debug.setfenv (object, table)
Sets the environment of the given object
to the given table
. Returns object
.
debug.sethook ([thread,] hook, mask [, count])
Sets the given function as a hook. The string mask
and the number count
describe when the hook will be called. The string mask may have the following characters, with the given meaning:
"c"
: The hook is called every time Lua calls a function;"r"
: The hook is called every time Lua returns from a function;"l"
: The hook is called every time Lua enters a new line of code.With a count
different from zero, the hook is called after every count
instructions.
When called without arguments, debug.sethook
turns off the hook.
When the hook is called, its first parameter is a string describing the event that has triggered its call: "call"
, "return"
(or "tail return"
), "line"
, and "count"
. For line events, the hook also gets the new line number as its second parameter. Inside a hook, you can call getinfo
with level 2 to get more information about the running function (level 0 is the getinfo
function, and level 1 is the hook function), unless the event is "tail return"
. In this case, Lua is only simulating the return, and a call to getinfo
will return invalid data.
debug.setlocal ([thread,] level, local, value)
This function assigns the value value
to the local variable with index local
of the function at level level
of the stack. The function returns nil if there is no local variable with the given index, and raises an error when called with a level
out of range. (You can call getinfo
to check whether the level is valid.) Otherwise, it returns the name of the local variable.
debug.setmetatable (object, table)
Sets the metatable for the given object
to the given table
(which can be nil).
debug.setupvalue (func, up, value)
This function assigns the value value
to the upvalue with index up
of the function func
. The function returns nil if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue.
debug.traceback ([thread,] [message] [, level])
Returns a string with a traceback of the call stack. An optional message
string is appended at the beginning of the traceback. An optional level
number tells at which level to start the traceback (default is 1, the function calling traceback
).
Although Lua has been designed as an extension language, to be embedded in a host C program, it is also frequently used as a stand-alone language. An interpreter for Lua as a stand-alone language, called simply lua
, is provided with the standard distribution. The stand-alone interpreter includes all standard libraries, including the debug library. Its usage is:
lua [options] [script [args]]
The options are:
-e stat
: executes string stat;-l mod
: "requires" mod;-i
: enters interactive mode after running script;-v
: prints version information;--
: stops handling options;-
: executes stdin
as a file and stops handling options.After handling its options, lua
runs the given script, passing to it the given args as string arguments. When called without arguments, lua
behaves as lua -v -i
when the standard input (stdin
) is a terminal, and as lua -
otherwise.
Before running any argument, the interpreter checks for an environment variable LUA_INIT
. If its format is @filename
, then lua
executes the file. Otherwise, lua
executes the string itself.
All options are handled in order, except -i
. For instance, an invocation like
$ lua -e'a=1' -e 'print(a)' script.lua
will first set a
to 1, then print the value of a
(which is '1
'), and finally run the file script.lua
with no arguments. (Here $
is the shell prompt. Your prompt may be different.)
Before starting to run the script, lua
collects all arguments in the command line in a global table called arg
. The script name is stored at index 0, the first argument after the script name goes to index 1, and so on. Any arguments before the script name (that is, the interpreter name plus the options) go to negative indices. For instance, in the call
$ lua -la b.lua t1 t2
the interpreter first runs the file a.lua
, then creates a table
arg = { [-2] = "lua", [-1] = "-la", [0] = "b.lua", [1] = "t1", [2] = "t2" }
and finally runs the file b.lua
. The script is called with arg[1]
, arg[2]
, ··· as arguments; it can also access these arguments with the vararg expression '...
'.
In interactive mode, if you write an incomplete statement, the interpreter waits for its completion by issuing a different prompt.
If the global variable _PROMPT
contains a string, then its value is used as the prompt. Similarly, if the global variable _PROMPT2
contains a string, its value is used as the secondary prompt (issued during incomplete statements). Therefore, both prompts can be changed directly on the command line. For instance,
$ lua -e"_PROMPT='myprompt> '" -i
(the outer pair of quotes is for the shell, the inner pair is for Lua), or in any Lua programs by assigning to _PROMPT
. Note the use of -i
to enter interactive mode; otherwise, the program would just end silently right after the assignment to _PROMPT
.
To allow the use of Lua as a script interpreter in Unix systems, the stand-alone interpreter skips the first line of a chunk if it starts with #
. Therefore, Lua scripts can be made into executable programs by using chmod +x
and the #!
form, as in
#!/usr/local/bin/lua
(Of course, the location of the Lua interpreter may be different in your machine. If lua
is in your PATH
, then
#!/usr/bin/env lua
is a more portable solution.)
Here we list the incompatibilities that you may found when moving a program from Lua 5.0 to Lua 5.1. You can avoid most of the incompatibilities compiling Lua with appropriate options (see file luaconf.h
). However, all these compatibility options will be removed in the next version of Lua.
arg
with a table with the extra arguments to the vararg expression. (See compile-time option LUA_COMPAT_VARARG
in luaconf.h
.)[[string]]
) does not allow nesting. You can use the new syntax ([=[string]=]
) in these cases. (See compile-time option LUA_COMPAT_LSTR
in luaconf.h
.)string.gfind
was renamed string.gmatch
. (See compile-time option LUA_COMPAT_GFIND
in luaconf.h
.)string.gsub
is called with a function as its third argument, whenever this function returns nil or false the replacement string is the whole match, instead of the empty string.table.setn
was deprecated. Function table.getn
corresponds to the new length operator (#
); use the operator instead of the function. (See compile-time option LUA_COMPAT_GETN
in luaconf.h
.)loadlib
was renamed package.loadlib
. (See compile-time option LUA_COMPAT_LOADLIB
in luaconf.h
.)math.mod
was renamed math.fmod
. (See compile-time option LUA_COMPAT_MOD
in luaconf.h
.)table.foreach
and table.foreachi
are deprecated. You can use a for loop with pairs
or ipairs
instead.require
due to the new module system. However, the new behavior is mostly compatible with the old, but require
gets the path from package.path
instead of from LUA_PATH
.collectgarbage
has different arguments. Function gcinfo
is deprecated; use collectgarbage("count")
instead.luaopen_*
functions (to open libraries) cannot be called directly, like a regular C function. They must be called through Lua, like a Lua function.lua_open
was replaced by lua_newstate
to allow the user to set a memory-allocation function. You can use luaL_newstate
from the standard library to create a state with a standard allocation function (based on realloc
).luaL_getn
and luaL_setn
(from the auxiliary library) are deprecated. Use lua_objlen
instead of luaL_getn
and nothing instead of luaL_setn
.luaL_openlib
was replaced by luaL_register
.luaL_checkudata
now throws an error when the given value is not a userdata of the expected type. (In Lua 5.0 it returned NULL
.)Here is the complete syntax of Lua in extended BNF. (It does not describe operator precedences.)
chunk ::= {stat [`;´]} [laststat [`;´]] block ::= chunk stat ::= varlist1 `=´ explist1 | functioncall | do block end | while exp do block end | repeat block until exp | if exp then block {elseif exp then block} [else block] end | for Name `=´ exp `,´ exp [`,´ exp] do block end | for namelist in explist1 do block end | function funcname funcbody | local function Name funcbody | local namelist [`=´ explist1] laststat ::= return [explist1] | break funcname ::= Name {`.´ Name} [`:´ Name] varlist1 ::= var {`,´ var} var ::= Name | prefixexp `[´ exp `]´ | prefixexp `.´ Name namelist ::= Name {`,´ Name} explist1 ::= {exp `,´} exp exp ::= nil | false | true | Number | String | `...´ | function | prefixexp | tableconstructor | exp binop exp | unop exp prefixexp ::= var | functioncall | `(´ exp `)´ functioncall ::= prefixexp args | prefixexp `:´ Name args args ::= `(´ [explist1] `)´ | tableconstructor | String function ::= function funcbody funcbody ::= `(´ [parlist1] `)´ block end parlist1 ::= namelist [`,´ `...´] | `...´ tableconstructor ::= `{´ [fieldlist] `}´ fieldlist ::= field {fieldsep field} [fieldsep] field ::= `[´ exp `]´ `=´ exp | Name `=´ exp | exp fieldsep ::= `,´ | `;´ binop ::= `+´ | `-´ | `*´ | `/´ | `^´ | `%´ | `..´ | `<´ | `<=´ | `>´ | `>=´ | `==´ | `~=´ | and | or unop ::= `-´ | not | `#´
Last update: Tue Oct 3 21:27:28 BRT 2006 譯文最後更新:修改幾處別字 2009年4月7日