Lua 5.1 οֲ

by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes

Ʒ www.codingnow.com

Copyright © 2006 Lua.org, PUC-Rio. All rights reserved.


1 -

Lua һչʽԣƳ֧ͨõĹʽ̣ʩ Lua Ҳ̣ܶʽ̣ʽṩܺõ֧֡ ΪһǿĽűԣκҪijʹá Lua һ clean C дɵĿʽṩν Clean C ָ ANSI C C++ йͨһӼ

ΪһչʽԣLua û "main" ĸֻ Ƕ һй򱻳 embedding program Ϊ host ͨúִһС Lua 룬Զд Lua ע C Lua á Щչ C Դչ Lua ԴͿԶƳԣ ǹһͳһľ䷨ʽĿܡ Lua ĹٷͰһ lua ļ򵥵 Lua ṩһ֤ Lua

Lua һʹɾ˶ʹùһûκα֤ ֲĶʵ֣ Lua Ĺٷվ www.lua.org ҵ

οֲһĵЩطȽϿ Lua 뷨֣̽Կ Lua վṩļġ й Lua ̵ϸڽܣԶһ Roberto 飬Programming in Lua (Second Edition)

2 -

һڴӴʷ﷨䷨ Lua 仰˵һЩ token ǣЧģαЩϷʽʲô塣

ԵĹɸóչ BNF ʽдҲӣ {a} ˼ 0 a [a] ˼һѡ a յķŻᱣԭӣؼ kword յķд `=´ Lua ﷨ڱֲҵ

2.1 - ʷԼ

Lua õ Ҳ ʶκηֿͷĸ֡»ɵַ ϼбйֵĶ塣 ĸĶڵǰϵͳжĸеĸԱڱʶ ʶΪ

ĹؼDZģ֣

     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' ʾ㡣

ֻҪѲͬšСбܡЩַַʱ űʹתκֱַдıһЩƷԻӰļϵͳijЩ⣬ Dz Lua κ⡣

ַһֳķʽ塣 ǰķż n ȺŶΪ n š ˵0 ijд [[ һijд [=[ ˵ȵȡ ijչҲƶ壻 ٸӣ4 ijд ]====] һַκһijſʼɵһͬijŽ ʷܷ̽ƣκתҺԵκβͬijš ַʽַ԰κζȻضķų⡣

һԼǣijźһз зͲַڡ ٸӣһϵͳʹ 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

עͿڳַڵκεط (--) ʼ IJһţһעͣ÷Χֱĩ һעͣ÷Χֱijš עͨʱδ顣

2.2 - ֵ

Lua һ ̬ ζűûֵֻͣ͡ вͶ塣еֵЯԼϢ

Lua еֵһ (first-class) ġ ζеֵԱڱݵһУΪء

Lua аֻͣ nil, boolean, number, string, function, userdata, thread, and table. Nil ֻһֵ nil Ҫ;ڱʶͱκֵIJ죻 ͨҪһֵʱõ 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 ޸ġIJֻͨ 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 Էһֵ͵ַ

2.2.1 - ǿת

Lua ṩʱֵַԶת κζַѧ᳢һתַתһ֡ ෴ۺʱһҪΪַʹʱֶԺĸʽתΪַ ҪȫתΪַʹַе format μ string.format

2.3 -

дϱĵطζŵ䱣ֵ֮ Lua ȫֱֲ table

һһֿԱʾһȫֱҲԱʾһֲ һIJһʽľֲ

	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 ж ʹǣֻǷͶѡ

2.4 - ΣStatement

Lua ֹ֧ʽΣ Pascal C ϰֵƽṹãб

2.4.1 - Chunk飩

Lua һִеԪ chunk һ chunk һΣǻᱻѭִС ÿοһֺŽ

	chunk ::= {stat [`;´]}

пյΣ ';;' ǷǷġ

lua һ chunk һӵв μ §2.5.9 chunk ڿԶֲղҷֵ

chunk ԱһļУҲԱһַС һ chunk ִУᱻԤеָУ ȻЩָ

chunk ҲԱԤɶʽϸڲο luac ԴʽṩijͱĶʽijǿ໥滻ģ Lua ԶʶļͲȷĴ

2.4.2 -

һΣ﷨˵һһ chunk ͬ

	block ::= chunk

һԱʽдһΣ

	stat ::= do block end

ʽڿƱ÷Χá ʱʽ鱻һв return break μ §2.4.4

2.4.3 - ֵ

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 ж ǽڽ͵Ŀд

2.4.4 - ƽṹ

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 ͿַҲΪ棩

repeatuntil ѭУ ڲĽ㲻 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 һһˡ

2.4.5 - For

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

ע⼸㣺

һʽ 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

ע¼㣺

2.4.6 - ѺΪ

Ϊʹÿܵĸã ÿԱΪһִУ

	stat ::= functioncall

£еķֵ §2.5.8 н͡

2.4.7 - ֲ

ֲκεط ԰һʼֵ

	stat ::= local namelist [`=´ explist1]

еĻʼֵΪͬڸֵμ §2.4.3 еıʼΪ nil

һ chunk ͬʱҲһ飨μ §2.4.1 ԾֲԷ chunk Щʽע֮⡣ Щֲ÷Χһֱ쵽 chunk ĩβ

ֲĿɼ §2.6 н͡

2.5 - ʽ

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

2.5.1 - ѧ

Lua ֳ֧ѧ Ԫ + ӷ - * ˷ / % ȡģԼ ^ ݣ һԪ - ȡ ֲǿתΪֵַμ §2.2.1 Щͨĺ塣 ݲԶκֵ磬 x^(-0.5) x ƽĵ ȡģΪ

     a % b == a - math.floor(a/b)*b

˵ԸԲעȡģĽΪ

2.5.2 - Ƚϲ

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

2.5.3 - ߼

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

ⱾֲУ --> ָǰʽĽ

2.5.4 - ӷ

Lua ַӲд ('..') ַ֣Ӳ §2.2.1 ᵽĹתΪַ 򣬻ȡԪ "concat" μ §2.8

2.5.5 - ȡȲ

ȡȲдһԪ # ַijֽһַһֽڼַȣ

table t ijȱһ± n t[n] nil t[n+1] Ϊ nilt[1] Ϊ nil n Ϳ㡣 ڳ飬 1 n һЩǿյֵʱ ijȾ;ȷΪ nһֵ±ꡣ һն ˵nil ֵڷǿֵ֮䣩 ô #t ָκһ nil ֵǰһλõ± ˵κһ nil ֵпܱĽ

2.5.6 - ȼ

Lua вȼд±Уӵ͵ȼ

     or
     and
     <     >     <=    >=    ~=    ==
     ..
     +     -
     *     /     %
     not   #     - (unary)
     ^

ͨı Ӳ ('..') ݲ ('^') Ǵġ еIJǴҡ

2.5.7 - Table

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

ʼһָ ƿԷɻɴ롣

2.5.8 -

Lua еĺõ﷨£

	functioncall ::= prefixexp args

ʱһprefixexp args ȱֵ prefixexp ֵ function ôͱøIJá 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 ʵʵβãʵβݹ飩 βУ õĺõĺĶջ ˣڳִеǶβõIJûƵġ ȻβýɾĺκεϢ ע⣬βֻض﷨£ ʱ return ֻеһΪ ﷨ʹõúĽԾȷء ˣЩӶβã

     return (f(x))        -- ֵΪһ
     return 2 * f(x)
     return x, f(x)       -- ɷֵ
     f(x); return         -- ޷ֵ
     return x or f(x)     -- ֵΪһ

2.5.9 -

﷨£

	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հ DZʽֵ ͬIJͬʵпòͬⲿֲ ҲӵвͬĻ

βΣҪIJһЩʵΣʵʴֵʼľֲ

	parlist1 ::= namelist [`,´ `...´] | `...´

һã ûбΪղβбĩβע ('...') ôʵбͻᱻβбijȣ 䳤ʵб ȡ֮ǣжIJһͨ䳤ʽݸ д㡣 ʽֵһʵֵб͸һԷضĺһ һ䳤ʽһʽʹãǷһʽм䣬 ôķֵͻᱻΪֵ ʽһϵбʽһͲˣŸ

¶壬Ȼһӣ

     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

2.6 - ӹ

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

2.7 -

Ϊ Lua һǶʽչԣ е Lua Ǵ C Lua μ lua_pcallеһʼġ Lua еκʱ˴󣬿Ȩύ C C һЩǡĴʩӡһϢ

Lua ʽĵ error һ Ҫ Lua вĴ ʹ pcall

2.8 - MetatableԪ

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 ԿƵIJг ÿӦ֡ ÿļòּ» '__' ǰ׺ַ ˵"add" ļַ "__add" Щһ Lua ִиΪǡ

չʾ Lua дĴ˵ã ʵʵΪѾӲڽУִЧҪԶЩģ롣 ЩĵĴõĺ rawget tonumber ȵȡ §5.1 ҵ رע⣬ʹһʽӸȡԪ

     metatable(obj)[event]

Ӧñ

     rawget(getmetatable(obj) or {}, event)

˵һԪٻᴥκεԪ ҷһû metatable ĶҲʧܣֻǼ򵥷 nil

2.9 -

Ϊ 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 е̵߳Ļ ٿuserdataC ̣߳ĻĻͱʹ C API

2.10 - ռ

Lua ṩһԶڴ ˵㲻ҪĴ¶ķڴҲҪЩҪʱͷڴ档 Lua ͨһռԶڴ棬ԴһһĻĶ ָ Lua вٷʵĵĶռõڴ档 Lua ж󶼱Զ table, userdata ַ̡߳

Lua ʵһռ ռڣ garbage-collector pause garbage-collector step multiplier

garbage-collector pause ռڿʼһµռ֮ǰҪȴá ֵ͵ռIJô С 1 ֵζռµڿʼʱٵȴ ֵΪ 2 ʱζʹڴﵽԭʱٿµڡ

step multiplier ռڴٶȡ ֽռĸͬʱҲʹÿռijߴӡ С 1 ֵʹռķdzܵռԶ˵ǰڡ ȱʡֵΪ 2 ζռڴС

ͨ C е lua_gc Lua е collectgarbage ıЩ֡ ߶ܰٷֱֵ˴ 100 ζʵֵ 1 ͨЩҲֱӿռ磬ֹͣ

2.10.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 ӻᱻһá

2.10.2 - Weak Table

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 Ϊͳδġ

2.11 - Coroutine Э̣ͬ

Lua ֧ coroutine ҲΪЭͬʽ߳ (collaborative multithreading) Lua Ϊÿ coroutine ṩһ· ȻͶ߳ϵͳе̲߳ͬcoroutine ֻʽĵ yield ʱŻ

һ coroutine Ҫһ coroutine.create ֻյ coroutine create һµ coroutine Ȼ󷵻Ŀ һΪ thread Ķ󣩣 coroutine С

һε coroutine.resume ʱ 贫ĵһ coroutine.create ķֵ ʱcoroutine ĵһпʼС coroutine.resume IJ coroutine coroutine ʼкеֹһ yields

coroutine ַͨʽֹУ һ˳ָأһָкûʽķָ; һǷ˳δĴʱ һУ coroutine.resume true coroutine һϵзֵ ڶַ£ coroutine.resume false һϢ

coroutine лȥԵ coroutine.yield coroutine г֮ϵ coroutine.resume أ yield ڲĺҲԣ˵ ⲻڷУҲֱӻӵõij yield £coroutine.resume ҲǷ true Щ coroutine.yield IJ ȵ´ڼͬ coroutine ӵ yield Ķϵ㴦ȥ ϵ㴦 yield ķֵ coroutine.resume IJ

coroutine.create coroutine.wrap Ҳһ coroutine coroutine Ƿһȡ֮һغͻ coroutine С дIJͬڴ coroutine.resume IJ 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

3 - ӿڣAPI

Lua C API Ҳ Lua ͨѶõһ C е API صԼͷļ lua.h С

Ȼ˵ǡһּ򵥵 API Ժʽṩġ еЩ궼ֻʹǵIJһ ˵һҲ lua ״̬ 㲻赣ЩչһЩá

е C УLua API ȥЧԺͼԡ Ȼڱ Lua ʱϴһ꿪 luaconf.h ļеĺ luai_apicheck ԸıΪ

3.1 - ջ

Lua ʹһջ C ֵ ջϵĵÿԪضһ Lua ֵ nilַ֣ȵȣ

ۺʱ Lua Cõĺõһµջ ջ C ĶջҲǰջ ע C  Lua API ܷʵ Lua ״̬бε֮Ķջеݣ Lua ݸ C в C ҪصĽҲջԷظ μ lua_CFunction

ջ API ѯϸѭջIJ ǿһָջϵκԪأ ָջϵľλãһʼ ָջʼƫ ϸ˵һ£ջ n Ԫأ ô 1 ʾһԪأҲȱѹջԪأ n ָһԪأ -1 ҲָһԪأջԪأ -n ָһԪء 1 ջ֮䣨Ҳǣ1 ≤ abs(index) ≤ top Ǿ˵ǸЧ

3.2 - ջߴ

ʹ Lua API ʱα֤ԡ رҪעǣοƲҪջ ʹ lua_checkstack öջijߴ硣

ۺʱ Lua C ֻ֤ LUA_MINSTACK ôĶջռʹá LUA_MINSTACK һ㱻Ϊ 20 ˣֻҪ㲻Dzϵİѹջͨ㲻ùĶջС

еIJѯԽһֻҪκջṩĿռеֵ ջṩռͨ lua_checkstack õġ ЩɽܵͨǰΪ

     (index < 0 && abs(index) <= top) ||
     (index > 0 && index <= stackspace)

ע⣬0 ԶһɽܵעзᵽûرעĻָɽܵ

3.3 - α

ر⣬κһԽһЧDZα ԰ C һЩջϵ Lua ֵ α̵߳ĻĻע C upvalue μ §3.4

̵߳ĻҲȫֱŵĵطͨα LUA_GLOBALSINDEX е C Ļα LUA_ENVIRONINDEX ֮

ó table ʺ͸ıȫֱֵֻҪָλá ԣҪȫֱֵ

     lua_getfield(L, LUA_GLOBALSINDEX, varname);

3.4 - C Closure

C пܻһЩֵһ ҲǴһ C closure Щֵ upvalue ǿںõʱʵĵ μ lua_pushcclosure

ۺʱȥ C upvalue ָα ǿ lua_upvalueindex Щα һֵ lua_upvalueindex(1) λôơ κ¶ lua_upvalueindex(n) һ upvalue ʹn ʵʵ upvalue ҲԡԲһɽܵһЧ

3.5 - ע

Lua ṩһעһԤıκ C 뱣 Lua ֵ α LUA_REGISTRYINDEX λ κ C ⶼűﱣݣΪ˷ֹͻҪرСĵѡ һ÷ǣһĿַΪ߿ȡԼ C еһַ light userdata ʽ

עڲʵֵϵͳĹһ˵Ҫڱ;

3.6 - C еĴ

ڲʵУLua ʹ C longjmp ʹ C++ ĻҲѡ쳣μ luaconf.h ļ Lua κδ󣨱ڴʹ﷨󡢻һЩʱ һȥ Ҳǵһ long jump ڱ£Lua ʹ setjmp һָ㣻 κηĴ󶼻ἤһָ㡣

е API ܲڴ һЩڱУҲ˵ǴһУ Dz lua_newstate, lua_close, lua_load, lua_pcall, and lua_cpcall

C Ҳͨ lua_error һ

3.7 -

ǰĸг C API еĺ͡


lua_Alloc

typedef void * (*lua_Alloc) (void *ud,
                             void *ptr,
                             size_t osize,
                             size_t nsize);

Lua ״̬ʹõڴ͡ ڴ亯ṩһ realloc ֲȫͬĺ IJ ud һ lua_newstate ָ룻 ptr һָѷǽ·Ҫͷŵڴָ룻 osize ڴԭijߴ磻 nsize ڴijߴ硣 ֻ 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);

һ

ҪһѭЭ飺 ȣҪõĺӦñѹջ ţҪݸIJѹջ ָһѹջ һ lua_call nargs ѹջIJ ϺеIJԼջ ķֵʱѹջ ֵĸΪ 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) ԷغյIJ һеĻ 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 λ ܰѶջչӦijߴ磬 false ԶСջ ջѾҪĴˣôͷﲻ仯


lua_close

void lua_close (lua_State *L);

ָ Lua ״̬ежռصԪĻǣ ͷ״̬ʹõж̬ڴ档 һЩƽ̨ϣԲص ΪʱеԴȻͷŵˡ һ棬еij򣬱һ̨һ 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 Ԫصķռ䡣 ȷ֪ҪٸԪʱԤͷdzá 㲻֪ʹú 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 дݣ datawriter

һд (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_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 ķֵǣ

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);

ֵָijȡ string Ǿַijȣ table ȡȲ ('#') Ľ userdata Ϊڴijߴ磻 ֵΪ 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 ǰѺIJջƳ

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 Ƚ񣬲һЩҪ


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 ָijΪ 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 ȡܷض飬ÿĴijߴ硣


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 IJ 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 IJ 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 жij 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) ijߴ (sz) lua_dump IJ 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

3.8 - Խӿ

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 еĸк壺


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õIJ

ڻȡһϢʱ԰ѹջ Ȼ 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 ṹһЩ䣬ǰһֵѹջ

᷵ 0 磬what һЧѡ


lua_getlocal

const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);

Ӹ¼лȡһֲϢ ar һЧĻļ¼ ¼ǰһε lua_getstack õģ һ μ lua_HookõIJ 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);

ڵԵĹӺ͡

ۺʱӱãIJ 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 塣 ÿ¼ӱõ£

ӿͨ 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 ʲôҲ

4 - The Auxiliary Library

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.

4.1 - Functions and Types

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:

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 (see lua_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 of package.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.

5 - Standard Libraries

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.

5.1 - Basic Functions

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:


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 of nil (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 numerical for 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, use string.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.

5.2 - Coroutine Manipulation

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 to yield are passed as extra results to resume.

5.3 - Modules

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, then require 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. Otherwise require 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 in package.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 by filename, 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.

5.4 - String Manipulation

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 the string 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.

5.4.1 - Patterns

Character Class:

A character class is used to represent a set of characters. The following combinations are allowed in describing a character class:

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.

Pattern Item:

A pattern item may be

Pattern:

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.

Captures:

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.

5.5 - Table Manipulation

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.

5.6 - Mathematical Functions

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.

5.7 - Input and Output Facilities

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, or nil 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 string whence, 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:

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.

5.8 - Operating System Facilities

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.

5.9 - The Debug Library

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 expression debug.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:

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).

6 - Lua Stand-alone

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:

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.)

7 - Incompatibilities with the Previous Version

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.

7.1 - Changes in the Language

7.2 - Changes in the Libraries

7.3 - Changes in the API

8 - The Complete Syntax of Lua

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
£޸ļ 200947