Sei sulla pagina 1di 96

Lua 5.

1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Lua 5.1 Reference Manual


byRobertoIerusalimschy,LuizHenriquedeFigueiredo,WaldemarCeles
Copyright20062012Lua.org,PUC-Rio.FreelyavailableunderthetermsoftheLualicense.

contentsindexotherversionsenglishportugusespaol

1 - Introduction
Lua is an extension programming language designed to support general procedural programming with data description facilities. It also offers good support for object-oriented programming,functionalprogramming,anddata-drivenprogramming.Luaisintendedtobeused as a powerful, light-weight scripting language for any program that needs one. Lua is implementedasalibrary,writtenincleanC(thatis,inthecommonsubsetofANSICandC++). Beinganextensionlanguage,Luahasnonotionofa"main"program:itonlyworksembeddedin ahostclient,calledtheembeddingprogramorsimplythehost.Thishostprogramcaninvoke functionsto execute a piece ofLua code,can write and read Lua variables,and can register CfunctionstobecalledbyLuacode.ThroughtheuseofCfunctions,Luacanbeaugmentedto copewithawiderangeofdifferentdomains,thuscreatingcustomizedprogramminglanguages sharingasyntacticalframework.TheLuadistributionincludesasamplehostprogramcalledlua, whichusestheLualibrarytoofferacomplete,stand-aloneLuainterpreter. Luaisfreesoftware,andisprovidedasusualwithnoguarantees,asstatedinitslicense.The implementationdescribedinthismanualisavailableatLua'sofficialwebsite,www.lua.org. Likeanyotherreferencemanual,thisdocumentisdryinplaces.Foradiscussionofthedecisions behindthedesignofLua,seethetechnicalpapersavailableatLua'swebsite.Foradetailed introductiontoprogramminginLua,seeRoberto'sbook,ProgramminginLua(SecondEdition).

2 - The Language
Thissectiondescribesthelexis,thesyntax,andthesemanticsofLua.Inotherwords,thissection describeswhichtokensarevalid,howtheycanbecombined,andwhattheircombinationsmean.

1 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

The language constructs will be explained using the usual extended BNFnotation,in which {a}means0ormorea's,and[a]meansanoptionala.Non-terminalsareshownlikenon-terminal, keywordsareshownlikekword,andotherterminalsymbolsareshownlike`=.Thecomplete syntaxofLuacanbefoundin8attheendofthismanual.

2.1 - Lexical Conventions


Names(alsocalledidentifiers)inLuacanbeanystringofletters,digits,andunderscores,not beginning with a digit.This coincides with the definition ofnames in mostlanguages.(The definition ofletterdependson the currentlocale:anycharacterconsidered alphabeticbythe currentlocale can be used in an identifier.)Identifiersare used to name variablesand table fields. Thefollowingkeywordsarereservedandcannotbeusedasnames: and end in repeat break false local return do for nil then else function not true elseif if or until

while

Luaisacase-sensitivelanguage:andisareservedword,butAndandANDaretwodifferent,valid names.Asaconvention,namesstartingwithanunderscorefollowedbyuppercaseletters(such as_VERSION)arereservedforinternalglobalvariablesusedbyLua. Thefollowingstringsdenoteothertokens: + == ( ; ~= ) : * <= { , / >= } . % < [ .. ^ > ] ... # =

Literal strings can be delimited by matching single or double quotes, and can contain the followingC-likeescapesequences:'\a'(bell),'\b'(backspace),'\f'(formfeed),'\n'(newline), '\r'(carriagereturn),'\t'(horizontaltab),'\v'(verticaltab),'\\'(backslash),'\"'(quotationmark [doublequote]),and'\''(apostrophe[singlequote]).Moreover,abackslashfollowedbyareal newline resultsin a newline in the string.Acharacterin a string can also be specified byits numerical value using the escape sequence \ddd,where ddd is a sequence ofup to three decimaldigits.(Notethatifanumericalescapeistobefollowedbyadigit,itmustbeexpressed usingexactlythreedigits.)StringsinLuacancontainany8-bitvalue,includingembeddedzeros, whichcanbespecifiedas'\0'. Literalstringscanalsobedefinedusingalongformatenclosedbylongbrackets.Wedefinean openinglongbracketoflevelnasanopeningsquarebracketfollowedbynequalsignsfollowed byanotheropeningsquarebracket.So,anopeninglongbracketoflevel0iswrittenas[[,an openinglongbracketoflevel1iswrittenas[=[,andsoon.Aclosinglongbracketisdefined similarly;forinstance,aclosinglongbracketoflevel4iswrittenas]====].Alongstringstarts withanopeninglongbracketofanylevelandendsatthefirstclosinglongbracketofthesame level. Literals in this bracketed form can run for several lines, do not interpret any escape
2 of 96 05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

sequences,and ignore long bracketsofanyotherlevel.Theycan contain anything excepta closingbracketoftheproperlevel. For convenience,when the opening long bracketis immediately followed by a newline,the newline isnotincluded in the string.Asan example,in a systemusing ASCII(in which 'a'is codedas97,newlineiscodedas10,and'1'iscodedas49),thefiveliteralstringsbelowdenote thesamestring: a = 'alo\n123"' a = "alo\n123\"" a = '\97lo\10\04923"' a = [[alo 123"]] a = [==[ alo 123"]==] A numerical constantcan be written with an optional decimal partand an optional decimal exponent.Luaalsoacceptsintegerhexadecimalconstants,byprefixingthemwith0x.Examples ofvalidnumericalconstantsare 3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56

Acommentstartswithadoublehyphen(--)anywhereoutsideastring.Ifthetextimmediately after--isnotanopeninglongbracket,thecommentisashortcomment,whichrunsuntiltheend ofthe line.Otherwise,itis a long comment,which runs until the corresponding closing long bracket.Longcommentsarefrequentlyusedtodisablecodetemporarily.

2.2 - Values and Types


Luaisadynamicallytypedlanguage.Thismeansthatvariablesdonothavetypes;onlyvalues do.Therearenotypedefinitionsinthelanguage.Allvaluescarrytheirowntype. All valuesin Lua are first-classvalues.Thismeansthatall valuescan be stored in variables, passedasargumentstootherfunctions,andreturnedasresults. ThereareeightbasictypesinLua:nil,boolean,number,string,function,userdata,thread,and table.Nilisthetypeofthevaluenil,whosemainpropertyistobedifferentfromanyothervalue;it usuallyrepresentstheabsenceofa useful value.Booleanisthe typeofthe valuesfalseand true.Bothnilandfalsemakeaconditionfalse;anyothervaluemakesittrue.Numberrepresents real(double-precisionfloating-point)numbers.(ItiseasytobuildLuainterpretersthatuseother internal representations for numbers,such as single-precision floator long integers;see file luaconf.h.)Stringrepresentsarraysofcharacters.Luais8-bitclean:stringscancontainany 8-bitcharacter,includingembeddedzeros('\0')(see2.1). Luacancall(andmanipulate)functionswritteninLuaandfunctionswritteninC(see2.5.8). ThetypeuserdataisprovidedtoallowarbitraryCdatatobestoredinLuavariables.Thistype

3 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

corresponds to a block of raw memory and has no pre-defined operations in Lua, except assignment and identity test. However, by using metatables, the programmer can define operationsforuserdatavalues(see2.8).UserdatavaluescannotbecreatedormodifiedinLua, onlythroughtheCAPI.Thisguaranteestheintegrityofdataownedbythehostprogram. The type thread represents independent threads of execution and it is used to implement coroutines(see2.11).DonotconfuseLuathreadswithoperating-systemthreads.Luasupports coroutinesonallsystems,eventhosethatdonotsupportthreads. Thetypetableimplementsassociativearrays,thatis,arraysthatcanbeindexednotonlywith numbers,butwithanyvalue(exceptnil).Tablescanbeheterogeneous;thatis,theycancontain valuesofalltypes(exceptnil).TablesarethesoledatastructuringmechanisminLua;theycan be used to represent ordinary arrays, symbol tables, sets, records, graphs, trees, etc. To represent records, Lua uses the field name as an index. The language supports this representation by providing a.name as syntactic sugar for a["name"]. There are several convenientwaystocreatetablesinLua(see2.5.7). Like indices,the value ofa table field can be ofanytype (exceptnil).In particular,because functions are first-class values,table fields can contain functions.Thus tables can also carry methods(see2.5.9). Tables, functions, threads, and (full) userdata values are objects: variables do not actually contain these values,only references to them.Assignment,parameter passing,and function returnsalwaysmanipulatereferencestosuchvalues;theseoperationsdonotimplyanykindof copy. Thelibraryfunctiontypereturnsastringdescribingthetypeofagivenvalue.

2.2.1 - Coercion
Luaprovidesautomaticconversionbetweenstringandnumbervaluesatruntime.Anyarithmetic operation applied to a string tries to convert this string to a number, following the usual conversion rules. Conversely, whenever a number is used where a string is expected, the numberisconvertedtoastring,inareasonableformat.Forcompletecontroloverhownumbers areconvertedtostrings,usetheformatfunctionfromthestringlibrary(seestring.format).

2.3 - Variables
Variablesareplacesthatstorevalues.TherearethreekindsofvariablesinLua:globalvariables, localvariables,andtablefields. Asinglenamecandenoteaglobalvariableoralocalvariable(orafunction'sformalparameter, whichisaparticularkindoflocalvariable): var ::= Name Namedenotesidentifiers,asdefinedin2.1.

4 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Anyvariable isassumed to be global unlessexplicitlydeclared asa local (see 2.4.7).Local variablesarelexicallyscoped:localvariablescanbefreelyaccessedbyfunctionsdefinedinside theirscope(see2.6). Beforethefirstassignmenttoavariable,itsvalueisnil. Squarebracketsareusedtoindexatable: var ::= prefixexp `[ exp `] Themeaningofaccessestoglobalvariablesandtablefieldscanbechangedviametatables.An accesstoanindexedvariablet[i]isequivalenttoacallgettable_event(t,i).(See2.8for acompletedescriptionofthegettable_eventfunction.Thisfunctionisnotdefinedorcallable inLua.Weuseithereonlyforexplanatorypurposes.) Thesyntaxvar.Nameisjustsyntacticsugarforvar["Name"]: var ::= prefixexp `. Name All global variables live as fields in ordinary Lua tables,called environmenttables or simply environments (see 2.9).Each function has its own reference to an environment,so thatall globalvariablesinthisfunctionwillrefertothisenvironmenttable.Whenafunctioniscreated,it inheritstheenvironmentfromthefunctionthatcreatedit.TogettheenvironmenttableofaLua function, you call getfenv. To replace it, you call setfenv. (You can only manipulate the environmentofCfunctionsthroughthedebuglibrary;(see5.9).) Anaccesstoaglobalvariablexisequivalentto_env.x,whichinturnisequivalentto gettable_event(_env, "x") where_envistheenvironmentoftherunningfunction.(See2.8foracompletedescriptionof thegettable_eventfunction.ThisfunctionisnotdefinedorcallableinLua.Similarly,the_env variableisnotdefinedinLua.Weusethemhereonlyforexplanatorypurposes.)

2.4 - Statements
Luasupportsanalmostconventionalsetofstatements,similartothoseinPascalorC.Thisset includesassignments,controlstructures,functioncalls,andvariabledeclarations.

2.4.1 - Chunks
TheunitofexecutionofLuaiscalledachunk.Achunkissimplyasequenceofstatements,which areexecutedsequentially.Eachstatementcanbeoptionallyfollowedbyasemicolon: chunk ::= {stat [`;]} Therearenoemptystatementsandthus';;'isnotlegal. Luahandlesachunkasthebodyofananonymousfunctionwithavariablenumberofarguments

5 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

(see2.5.9).Assuch,chunkscandefinelocalvariables,receivearguments,andreturnvalues. Achunkcanbestoredinafileorinastringinsidethehostprogram.Toexecuteachunk,Luafirst pre-compilesthechunkintoinstructionsforavirtualmachine,andthenitexecutesthecompiled codewithaninterpreterforthevirtualmachine. Chunkscanalsobepre-compiledintobinaryform;seeprogramluacfordetails.Programsin sourceandcompiledformsareinterchangeable;Luaautomaticallydetectsthefiletypeandacts accordingly.

2.4.2 - Blocks
Ablockisalistofstatements;syntactically,ablockisthesameasachunk: block ::= chunk Ablockcanbeexplicitlydelimitedtoproduceasinglestatement: stat ::= do block end Explicitblocksareusefultocontrolthescopeofvariabledeclarations.Explicitblocksarealso sometimesusedtoaddareturnorbreakstatementinthemiddleofanotherblock(see2.4.4).

2.4.3 - Assignment
Luaallowsmultipleassignments.Therefore,thesyntaxforassignmentdefinesalistofvariables ontheleftsideandalistofexpressionsontherightside.Theelementsinbothlistsareseparated bycommas: stat ::= varlist `= explist varlist ::= var {`, var} explist ::= exp {`, exp} Expressionsarediscussedin2.5. Beforetheassignment,thelistofvaluesisadjustedtothelengthofthelistofvariables.Ifthere aremorevaluesthanneeded,theexcessvaluesarethrownaway.Iftherearefewervaluesthan needed,thelistisextendedwithasmanynil'sasneeded.Ifthelistofexpressionsendswitha functioncall,thenallvaluesreturnedbythatcallenterthelistofvalues,beforetheadjustment (exceptwhenthecallisenclosedinparentheses;see2.5). Theassignmentstatementfirstevaluatesallitsexpressionsandonlythenaretheassignments performed.Thusthecode i = 3 i, a[i] = i+1, 20 setsa[3]to 20,withoutaffecting a[4]because the iin a[i]isevaluated (to 3)before itis assigned4.Similarly,theline

6 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

x, y = y, x exchangesthevaluesofxandy,and x, y, z = y, z, x cyclicallypermutesthevaluesofx,y,andz. Themeaningofassignmentstoglobalvariablesandtablefieldscanbechangedviametatables. An assignment to an indexed variable t[i] = val is equivalent to settable_event(t,i,val). (See 2.8 for a complete description of the settable_event function.This function is notdefined or callable in Lua.We use ithere only for explanatory purposes.) Anassignmenttoaglobalvariablex = valisequivalenttotheassignment_env.x = val, whichinturnisequivalentto settable_event(_env, "x", val) where_envistheenvironmentoftherunningfunction.(The_envvariableisnotdefinedinLua. Weuseithereonlyforexplanatorypurposes.)

2.4.4 - Control Structures


Thecontrolstructuresif,while,andrepeathavetheusualmeaningandfamiliarsyntax: stat ::= while exp do block end stat ::= repeat block until exp stat ::= if exp then block {elseif exp then block} [else block] end Luaalsohasaforstatement,intwoflavors(see2.4.5). The condition expression ofa control structure can return any value.Both false and nilare considered false.All valuesdifferentfromniland false are considered true (in particular,the number0andtheemptystringarealsotrue). In the repeatuntilloop,the innerblockdoesnotend atthe untilkeyword,butonlyafterthe condition.So,theconditioncanrefertolocalvariablesdeclaredinsidetheloopblock. Thereturnstatementisusedtoreturnvaluesfromafunctionorachunk(whichisjustafunction). Functionsandchunkscanreturnmorethanonevalue,andsothesyntaxforthereturnstatement is stat ::= return [explist] Thebreakstatementisusedtoterminatetheexecutionofawhile,repeat,orforloop,skippingto thenextstatementaftertheloop: stat ::= break Abreakendstheinnermostenclosingloop.

7 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Thereturnandbreakstatementscanonlybewrittenasthelaststatementofablock.Ifitisreally necessarytoreturnorbreakinthemiddleofablock,thenanexplicitinnerblockcanbeused,as intheidiomsdo return endanddo break end,becausenowreturnandbreakarethelast statementsintheir(inner)blocks.

2.4.5 - For Statement


Theforstatementhastwoforms:onenumericandonegeneric. Thenumericforlooprepeatsablockofcodewhileacontrolvariablerunsthroughanarithmetic progression.Ithasthefollowingsyntax: stat ::= for Name `= exp `, exp [`, exp] do block end Theblockisrepeatedfornamestartingatthevalueofthefirstexp,untilitpassesthesecondexp bystepsofthethirdexp.Moreprecisely,aforstatementlike for v = e1, e2, e3 do block end isequivalenttothecode: 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 Notethefollowing: Allthreecontrolexpressionsareevaluatedonlyonce,beforetheloopstarts.Theymustall resultinnumbers. var,limit,andstepareinvisiblevariables.Thenamesshownhereareforexplanatory purposesonly. Ifthethirdexpression(thestep)isabsent,thenastepof1isused. Youcanusebreaktoexitaforloop. Theloopvariablevislocaltotheloop;youcannotuseitsvalueaftertheforendsoris broken.Ifyouneedthisvalue,assignittoanothervariablebeforebreakingorexitingthe loop. The genericfor statementworksoverfunctions,called iterators.On each iteration,the iterator functioniscalledtoproduceanewvalue,stoppingwhenthisnewvalueisnil.Thegenericfor loophasthefollowingsyntax: stat ::= for namelist in explist do block end namelist ::= Name {`, Name}

8 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Aforstatementlike for var_1, , var_n in explist do block end isequivalenttothecode: 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 Notethefollowing: explistisevaluatedonlyonce.Itsresultsareaniteratorfunction,astate,andaninitial valueforthefirstiteratorvariable. f,s,andvarareinvisiblevariables.Thenamesarehereforexplanatorypurposesonly. Youcanusebreaktoexitaforloop. Theloopvariablesvar_iarelocaltotheloop;youcannotusetheirvaluesafterthefor ends.Ifyou need these values,then assign themto othervariablesbefore breaking or exitingtheloop.

2.4.6 - Function Calls as Statements


Toallowpossibleside-effects,functioncallscanbeexecutedasstatements: stat ::= functioncall Inthiscase,allreturnedvaluesarethrownaway.Functioncallsareexplainedin2.5.8.

2.4.7 - Local Declarations


Localvariablescanbedeclaredanywhereinsideablock.Thedeclarationcanincludeaninitial assignment: stat ::= local namelist [`= explist] Ifpresent,aninitialassignmenthasthesamesemanticsofamultipleassignment(see2.4.3). Otherwise,allvariablesareinitializedwithnil. Achunkisalsoablock(see2.4.1),andsolocalvariablescanbedeclaredinachunkoutside anyexplicitblock.Thescopeofsuchlocalvariablesextendsuntiltheendofthechunk. Thevisibilityrulesforlocalvariablesareexplainedin2.6.

9 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

2.5 - Expressions
ThebasicexpressionsinLuaarethefollowing: 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 `) Numbers and literal strings are explained in 2.1; variables are explained in 2.3; function definitionsareexplainedin2.5.9;functioncallsareexplainedin2.5.8;tableconstructorsare explainedin2.5.7.Varargexpressions,denotedbythreedots('...'),canonlybeusedwhen directlyinsideavarargfunction;theyareexplainedin2.5.9. Binaryoperatorscomprise arithmeticoperators(see 2.5.1),relational operators(see 2.5.2), logical operators (see 2.5.3),and the concatenation operator (see 2.5.4).Unary operators comprisetheunaryminus(see2.5.1),theunarynot(see2.5.3),andtheunarylengthoperator (see2.5.5). Bothfunctioncallsandvarargexpressionscanresultinmultiplevalues.Ifanexpressionisused asastatement(onlypossibleforfunctioncalls(see2.4.6)),thenitsreturnlistisadjustedtozero elements,thusdiscardingallreturnedvalues.Ifanexpressionisusedasthelast(ortheonly) elementofa listofexpressions,then no adjustmentis made (unless the call is enclosed in parentheses).Inallothercontexts,Luaadjuststheresultlisttooneelement,discardingallvalues exceptthefirstone. Herearesomeexamples: f() g(f(), x) g(x, f()) a,b,c = f(), x a,b = ... -------------adjusted to 0 results f() is adjusted to 1 result g gets x plus all results from f() f() is adjusted to 1 result (c gets nil) a gets the first vararg parameter, b gets the second (both a and b can get nil if there is no corresponding vararg parameter) f() is adjusted to 2 results f() is adjusted to 3 results returns all results from f() returns all received vararg parameters returns x, y, and all results from f() creates a list with all results from f()

a,b,c = x, f() a,b,c = f() return f() return ... return x,y,f() {f()}

10 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

{...} {f(), nil}

-- creates a list with all vararg parameters -- f() is adjusted to 1 result

Anyexpressionenclosedinparenthesesalwaysresultsinonlyonevalue.Thus,(f(x,y,z))is alwaysa single value,even iffreturnsseveral values.(The value of(f(x,y,z))isthe first valuereturnedbyforniliffdoesnotreturnanyvalues.)

2.5.1 - Arithmetic Operators


Lua supports the usual arithmetic operators: the binary + (addition), - (subtraction), * (multiplication),/(division),%(modulo),and ^(exponentiation);and unary-(negation).Ifthe operands are numbers, or strings that can be converted to numbers (see 2.2.1), then all operations have the usual meaning. Exponentiation works for any exponent. For instance, x^(-0.5)computestheinverseofthesquarerootofx.Moduloisdefinedas a % b == a - math.floor(a/b)*b Thatis,itistheremainderofadivisionthatroundsthequotienttowardsminusinfinity.

2.5.2 - Relational Operators


TherelationaloperatorsinLuaare == ~= < > <= >=

Theseoperatorsalwaysresultinfalseortrue. Equality(==)firstcomparesthetypeofitsoperands.Ifthetypesaredifferent,thentheresultis false.Otherwise,thevaluesoftheoperandsarecompared.Numbersandstringsarecompared intheusualway.Objects(tables,userdata,threads,andfunctions)arecomparedbyreference: twoobjectsareconsideredequalonlyiftheyarethesameobject.Everytimeyoucreateanew object(a table,userdata,thread,orfunction),thisnew objectisdifferentfromanypreviously existingobject. YoucanchangethewaythatLuacomparestablesanduserdatabyusingthe"eq"metamethod (see2.8). Theconversionrulesof2.2.1donotapplytoequalitycomparisons.Thus,"0"==0evaluatesto false,andt[0]andt["0"]denotedifferententriesinatable. Theoperator~=isexactlythenegationofequality(==). Theorderoperatorsworkasfollows.Ifbothargumentsarenumbers,thentheyarecomparedas such.Otherwise,ifbothargumentsarestrings,thentheirvaluesarecomparedaccordingtothe currentlocale.Otherwise,Luatriestocallthe"lt"orthe"le"metamethod(see2.8).Acomparison a > bistranslatedtob < aanda >= bistranslatedtob <= a.

2.5.3 - Logical Operators


The logical operatorsin Lua are and,or,and not.Like the control structures(see 2.4.4),all
11 of 96 05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

logicaloperatorsconsiderbothfalseandnilasfalseandanythingelseastrue. Thenegationoperatornotalwaysreturnsfalseortrue.Theconjunctionoperatorandreturnsits first argument if this value is false or nil; otherwise, and returns its second argument. The disjunction operator or returns its first argument if this value is different from nil and false; otherwise,orreturnsitssecondargument.Bothandandoruseshort-cutevaluation;thatis,the secondoperandisevaluatedonlyifnecessary.Herearesomeexamples: 10 or 20 10 or error() nil or "a" nil and 10 false and error() false and nil false or nil 10 and 20 --> --> --> --> --> --> --> --> 10 10 "a" nil false false nil 20

(Inthismanual,-->indicatestheresultoftheprecedingexpression.)

2.5.4 - Concatenation
The string concatenation operator in Lua is denoted by two dots ('..').Ifboth operands are stringsornumbers,thentheyareconvertedtostringsaccordingtotherulesmentionedin2.2.1. Otherwise,the"concat"metamethodiscalled(see2.8).

2.5.5 - The Length Operator


Thelengthoperatorisdenotedbytheunaryoperator#.Thelengthofastringisitsnumberof bytes(thatis,theusualmeaningofstringlengthwheneachcharacterisonebyte). Thelengthofatabletisdefinedtobeanyintegerindexnsuchthatt[n]isnotnilandt[n+1]is nil;moreover,ift[1]isnil,ncanbezero.Foraregulararray,withnon-nilvaluesfrom1toa givenn,itslengthisexactlythatn,theindexofitslastvalue.Ifthearrayhas"holes"(thatis,nil valuesbetweenothernon-nilvalues),then#tcanbeanyoftheindicesthatdirectlyprecedesa nilvalue(thatis,itmayconsideranysuchnilvalueastheendofthearray).

2.5.6 - Precedence
OperatorprecedenceinLuafollowsthetablebelow,fromlowertohigherpriority: or and < .. + * not ^

> / #

<=

>=

~=

==

% - (unary)

12 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

As usual, you can use parentheses to change the precedences of an expression. The concatenation ('..') and exponentiation ('^') operators are right associative. All other binary operatorsareleftassociative.

2.5.7 - Table Constructors


Tableconstructorsareexpressionsthatcreate tables.Everytime aconstructorisevaluated,a newtableiscreated.Aconstructorcanbeusedtocreateanemptytableortocreateatableand initializesomeofitsfields.Thegeneralsyntaxforconstructorsis tableconstructor ::= `{ [fieldlist] `} fieldlist ::= field {fieldsep field} [fieldsep] field ::= `[ exp `] `= exp | Name `= exp | exp fieldsep ::= `, | `; Eachfieldoftheform[exp1] = exp2addstothenewtableanentrywithkeyexp1andvalue exp2.Afieldoftheformname = expisequivalentto["name"] = exp.Finally,fieldsoftheform expareequivalentto[i] = exp,whereiareconsecutivenumericalintegers,startingwith1. Fieldsintheotherformatsdonotaffectthiscounting.Forexample, a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } isequivalentto do local t = {} t[f(1)] = g t[1] = "x" t[2] = "y" t.x = 1 t[3] = f(x) t[30] = 23 t[4] = 45 a = t end

-----

1st exp 2nd exp t["x"] = 1 3rd exp

-- 4th exp

Ifthe lastfield in the listhas the form expand the expression is a function call or a vararg expression,thenallvaluesreturnedbythisexpressionenterthelistconsecutively(see2.5.8). Toavoidthis,enclosethefunctioncallorthevarargexpressioninparentheses(see2.5). Thefieldlistcanhaveanoptionaltrailingseparator,asaconvenienceformachine-generated code.

2.5.8 - Function Calls


AfunctioncallinLuahasthefollowingsyntax: functioncall ::= prefixexp args Inafunctioncall,firstprefixexpandargsareevaluated.Ifthevalueofprefixexphastypefunction,

13 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

thenthisfunctioniscalledwiththegivenarguments.Otherwise,theprefixexp"call"metamethod iscalled,havingasfirstparameterthevalueofprefixexp,followedbytheoriginalcallarguments (see2.8). Theform functioncall ::= prefixexp `: Name args can be used to call "methods".Acall v:name(args)issyntacticsugarforv.name(v,args), exceptthatvisevaluatedonlyonce. Argumentshavethefollowingsyntax: args ::= `( [explist] `) args ::= tableconstructor args ::= String Allargumentexpressionsareevaluatedbeforethecall.Acalloftheformf{fields}issyntactic sugar for f({fields}); that is, the argument list is a single new table. A call of the form f'string'(orf"string"orf[[string]])issyntacticsugarforf('string');thatis,the argumentlistisasingleliteralstring. Asanexceptiontothefree-formatsyntaxofLua,youcannotputalinebreakbeforethe'('ina functioncall.Thisrestrictionavoidssomeambiguitiesinthelanguage.Ifyouwrite a = f (g).x(a) Luawouldseethatasasinglestatement,a = f(g).x(a).So,ifyouwanttwostatements,you mustaddasemi-colonbetweenthem.Ifyouactuallywanttocallf,youmustremovetheline breakbefore(g). Acall ofthe formreturnfunctioncall iscalled a tail call.Lua implementspropertail calls(or proper tail recursion):in a tail call,the called function reuses the stack entry ofthe calling function.Therefore,thereisnolimitonthenumberofnestedtailcallsthataprogramcanexecute. However,atailcallerasesanydebuginformationaboutthecallingfunction.Notethatatailcall onlyhappenswithaparticularsyntax,wherethereturnhasonesinglefunctioncallasargument; thissyntaxmakesthecallingfunctionreturnexactlythereturnsofthecalledfunction.So,noneof thefollowingexamplesaretailcalls: return (f(x)) return 2 * f(x) return x, f(x) f(x); return return x or f(x) -- results adjusted to 1 -- additional results -- results discarded -- results adjusted to 1

2.5.9 - Function Definitions


Thesyntaxforfunctiondefinitionis

14 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

function ::= function funcbody funcbody ::= `( [parlist] `) block end Thefollowingsyntacticsugarsimplifiesfunctiondefinitions: stat ::= function funcname funcbody stat ::= local function Name funcbody funcname ::= Name {`. Name} [`: Name] Thestatement function f () body end translatesto f = function () body end Thestatement function t.a.b.c.f () body end translatesto t.a.b.c.f = function () body end Thestatement local function f () body end translatesto local f; f = function () body end notto local f = function () body end (Thisonlymakesadifferencewhenthebodyofthefunctioncontainsreferencestof.) A function definition is an executable expression,whose value has type function.When Lua pre-compilesachunk,allitsfunctionbodiesarepre-compiledtoo.Then,wheneverLuaexecutes thefunctiondefinition,thefunctionisinstantiated(orclosed).Thisfunctioninstance(orclosure)is thefinalvalueoftheexpression.Differentinstancesofthesamefunctioncanrefertodifferent externallocalvariablesandcanhavedifferentenvironmenttables. Parametersactaslocalvariablesthatareinitializedwiththeargumentvalues: parlist ::= namelist [`, `...] | `... Whenafunctioniscalled,thelistofargumentsisadjustedtothelengthofthelistofparameters, unlessthefunctionisavariadicorvarargfunction,whichisindicatedbythreedots('...')atthe endofitsparameterlist.Avarargfunctiondoesnotadjustitsargumentlist;instead,itcollectsall

15 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

extra argumentsand suppliesthemto the function through a vararg expression,which isalso writtenasthreedots.Thevalueofthisexpressionisalistofallactualextraarguments,similarto afunctionwithmultipleresults.Ifavarargexpressionisusedinsideanotherexpressionorinthe middleofalistofexpressions,thenitsreturnlistisadjustedtooneelement.Iftheexpressionis usedasthelastelementofalistofexpressions,thennoadjustmentismade(unlessthatlast expressionisenclosedinparentheses). Asanexample,considerthefollowingdefinitions: function f(a, b) end function g(a, b, ...) end function r() return 1,2,3 end Then, we have the following mapping from arguments to parameters and to the vararg expression: CALL f(3) f(3, 4) f(3, 4, 5) f(r(), 10) f(r()) g(3) g(3, 4) g(3, 4, 5, 8) g(5, r()) PARAMETERS a=3, a=3, a=3, a=1, a=1, a=3, a=3, a=3, a=5, b=nil b=4 b=4 b=10 b=2 b=nil, b=4, b=4, b=1, ... ... ... ... --> --> --> --> (nothing) (nothing) 5 8 2 3

Resultsare returned using the returnstatement(see 2.4.4).Ifcontrol reachesthe end ofa functionwithoutencounteringareturnstatement,thenthefunctionreturnswithnoresults. The colon syntax is used for defining methods,thatis,functions thathave an implicitextra parameterself.Thus,thestatement function t.a.b.c:f (params) body end issyntacticsugarfor t.a.b.c.f = function (self, params) body end

2.6 - Visibility Rules


Luaisalexicallyscopedlanguage.Thescopeofvariablesbeginsatthefirststatementaftertheir declarationandlastsuntiltheendoftheinnermostblockthatincludesthedeclaration.Consider thefollowingexample: x = 10 do -- global variable -- new block

16 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

local x = x print(x) x = x+1 do local x = x+1 print(x) end print(x) end print(x)

-- new 'x', with value 10 --> 10 -- another block -- another 'x' --> 12 --> 11 --> 10 (the global one)

Noticethat,inadeclarationlikelocal x = x,thenewxbeingdeclaredisnotinscopeyet,and sothesecondxreferstotheoutsidevariable. Becauseofthelexicalscopingrules,localvariablescanbefreelyaccessedbyfunctionsdefined insidetheirscope.Alocalvariableusedbyaninnerfunctioniscalledanupvalue,orexternal localvariable,insidetheinnerfunction. Notice that each execution of a local statement defines new local variables. Consider the followingexample: a = {} local x = 20 for i=1,10 do local y = 0 a[i] = function () y=y+1; return x+y end end Theloopcreatestenclosures(thatis,teninstancesoftheanonymousfunction).Eachofthese closuresusesadifferentyvariable,whileallofthemsharethesamex.

2.7 - Error Handling


BecauseLuaisanembeddedextensionlanguage,allLuaactionsstartfromCcodeinthehost program calling a function from the Lua library (see lua_pcall).Whenever an error occurs duringLuacompilationorexecution,controlreturnstoC,whichcantakeappropriatemeasures (suchasprintinganerrormessage). Lua code can explicitlygenerate an errorbycalling the errorfunction.Ifyou need to catch errorsinLua,youcanusethepcallfunction.

2.8 - Metatables
EveryvalueinLuacanhaveametatable.ThismetatableisanordinaryLuatablethatdefinesthe behavioroftheoriginalvalueundercertainspecialoperations.Youcanchangeseveralaspects ofthebehaviorofoperationsoveravaluebysettingspecificfieldsinitsmetatable.Forinstance, whenanon-numericvalueistheoperandofanaddition,Luachecksforafunctioninthefield
17 of 96 05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

"__add"initsmetatable.Ifitfindsone,Luacallsthisfunctiontoperformtheaddition. Wecallthekeysinametatableeventsandthevaluesmetamethods.Inthepreviousexample,the eventis"add"andthemetamethodisthefunctionthatperformstheaddition. Youcanquerythemetatableofanyvaluethroughthegetmetatablefunction. Youcanreplacethemetatableoftablesthroughthesetmetatablefunction.Youcannotchange themetatableofothertypesfromLua(exceptbyusingthedebuglibrary);youmustusetheCAPI forthat. Tablesandfulluserdatahaveindividualmetatables(althoughmultipletablesanduserdatacan share theirmetatables).Valuesofall othertypesshare one single metatable pertype;thatis, thereisonesinglemetatableforallnumbers,oneforallstrings,etc. A metatable controls how an object behaves in arithmetic operations, order comparisons, concatenation,length operation,and indexing.A metatable also can define a function to be called when a userdata isgarbage collected.Foreach ofthese operationsLua associatesa specifickeycalledanevent.WhenLuaperformsoneoftheseoperationsoveravalue,itchecks whetherthisvaluehasametatablewiththecorrespondingevent.Ifso,thevalueassociatedwith thatkey(themetamethod)controlshowLuawillperformtheoperation. Metatablescontrol theoperationslistednext.Eachoperationisidentified byitscorresponding name.Thekeyforeachoperationisastringwithitsnameprefixedbytwounderscores,'__';for instance,thekeyforoperation"add"isthestring"__add".Thesemanticsoftheseoperationsis betterexplainedbyaLuafunctiondescribinghowtheinterpreterexecutestheoperation. ThecodeshownhereinLuaisonlyillustrative;therealbehaviorishardcodedintheinterpreter and it is much more efficient than this simulation. All functions used in these descriptions (rawget,tonumber,etc.)are described in 5.1.In particular,to retrieve the metamethod ofa givenobject,weusetheexpression metatable(obj)[event] Thisshouldbereadas rawget(getmetatable(obj) or {}, event) Thatis,the accessto a metamethod doesnotinvoke othermetamethods,and the accessto objectswithnometatablesdoesnotfail(itsimplyresultsinnil). "add":the+operation. The function getbinhandler below defines how Lua chooses a handler for a binary operation.First,Lua tries the firstoperand.Ifits type does notdefine a handler for the operation,thenLuatriesthesecondoperand. function getbinhandler (op1, op2, event) return metatable(op1)[event] or metatable(op2)[event] end

18 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Byusingthisfunction,thebehavioroftheop1 + op2is function add_event (op1, op2) local o1, o2 = tonumber(op1), tonumber(op2) if o1 and o2 then -- both operands are numeric? return o1 + o2 -- '+' here is the primitive 'add' else -- at least one of the operands is not numeric local h = getbinhandler(op1, op2, "__add") if h then -- call the handler with both operands return (h(op1, op2)) else -- no handler available: default behavior error() end end end "sub":the-operation.Behaviorsimilartothe"add"operation. "mul":the*operation.Behaviorsimilartothe"add"operation. "div":the/operation.Behaviorsimilartothe"add"operation. "mod":the%operation.Behaviorsimilartothe"add"operation,withtheoperationo1 floor(o1/o2)*o2astheprimitiveoperation. "pow":the^(exponentiation)operation.Behaviorsimilartothe"add"operation,withthe functionpow(fromtheCmathlibrary)astheprimitiveoperation. "unm":theunary-operation. function unm_event (op) local o = tonumber(op) if o then -- operand is numeric? return -o -- '-' here is the primitive 'unm' else -- the operand is not numeric. -- Try to get a handler from the operand local h = metatable(op).__unm if h then -- call the handler with the operand return (h(op)) else -- no handler available: default behavior error() end end end "concat":the..(concatenation)operation. function concat_event (op1, op2) if (type(op1) == "string" or type(op1) == "number") and (type(op2) == "string" or type(op2) == "number") then return op1 .. op2 -- primitive string concatenation else local h = getbinhandler(op1, op2, "__concat")

19 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

if h then return (h(op1, op2)) else error() end end end "len":the#operation. function len_event (op) if type(op) == "string" then return strlen(op) -- primitive string length elseif type(op) == "table" then return #op -- primitive table length else local h = metatable(op).__len if h then -- call the handler with the operand return (h(op)) else -- no handler available: default behavior error() end end end See2.5.5foradescriptionofthelengthofatable. "eq": the == operation. The function getcomphandler defines how Lua chooses a metamethodforcomparisonoperators.Ametamethodonlyisselectedwhenbothobjects beingcomparedhavethesametypeandthesamemetamethodfortheselectedoperation. function getcomphandler (op1, op2, event) if type(op1) ~= type(op2) then return nil end local mm1 = metatable(op1)[event] local mm2 = metatable(op2)[event] if mm1 == mm2 then return mm1 else return nil end end The"eq"eventisdefinedasfollows: function eq_event (op1, op2) if type(op1) ~= type(op2) then -- different types? return false -- different objects end if op1 == op2 then -- primitive equal? return true -- objects are equal end -- try metamethod local h = getcomphandler(op1, op2, "__eq") if h then
20 of 96 05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

return (h(op1, op2)) else return false end end a ~= bisequivalenttonot (a == b). "lt":the<operation. function lt_event (op1, op2) if type(op1) == "number" and type(op2) == "number" then return op1 < op2 -- numeric comparison elseif type(op1) == "string" and type(op2) == "string" then return op1 < op2 -- lexicographic comparison else local h = getcomphandler(op1, op2, "__lt") if h then return (h(op1, op2)) else error() end end end a > bisequivalenttob < a. "le":the<=operation. function le_event (op1, op2) if type(op1) == "number" and type(op2) == "number" then return op1 <= op2 -- numeric comparison elseif type(op1) == "string" and type(op2) == "string" then return op1 <= op2 -- lexicographic comparison else local h = getcomphandler(op1, op2, "__le") if h then return (h(op1, op2)) else h = getcomphandler(op1, op2, "__lt") if h then return not h(op2, op1) else error() end end end end a >= bisequivalenttob <= a.Notethat,intheabsenceofa"le"metamethod,Luatries the"lt",assumingthata <= bisequivalenttonot (b < a).
21 of 96 05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

"index":Theindexingaccesstable[key]. function gettable_event (table, key) local h if type(table) == "table" then local v = rawget(table, key) if v ~= nil then return v end h = metatable(table).__index if h == nil then return nil end else h = metatable(table).__index if h == nil then error() end end if type(h) == "function" then return (h(table, key)) -- call the handler else return h[key] -- or repeat operation on it end end "newindex":Theindexingassignmenttable[key] = value. function settable_event (table, key, value) local h if type(table) == "table" then local v = rawget(table, key) if v ~= nil then rawset(table, key, value); return end h = metatable(table).__newindex if h == nil then rawset(table, key, value); return end else h = metatable(table).__newindex if h == nil then error() end end if type(h) == "function" then h(table, key,value) -- call the handler else h[key] = value -- or repeat operation on it end end "call":calledwhenLuacallsavalue. function function_event (func, ...) if type(func) == "function" then return func(...) -- primitive call else local h = metatable(func).__call if h then

22 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

return h(func, ...) else error() end end end

2.9 - Environments
Besides metatables, objects of types thread, function, and userdata have another table associatedwiththem,calledtheirenvironment.Likemetatables,environmentsareregulartables andmultipleobjectscansharethesameenvironment. Threadsarecreatedsharingtheenvironmentofthecreatingthread.UserdataandCfunctions are created sharing the environment of the creating Cfunction. Non-nested Lua functions (createdbyloadfile,loadstringorload)arecreatedsharingtheenvironmentofthecreating thread.NestedLuafunctionsarecreatedsharingtheenvironmentofthecreatingLuafunction. EnvironmentsassociatedwithuserdatahavenomeaningforLua.Itisonlyaconveniencefeature forprogrammerstoassociateatabletoauserdata. Environments associated with threads are called global environments.They are used as the defaultenvironmentforthreadsandnon-nestedLuafunctionscreatedbythethreadandcanbe directlyaccessedbyCcode(see3.3). TheenvironmentassociatedwithaCfunctioncanbedirectlyaccessedbyCcode(see3.3).Itis usedasthedefaultenvironmentforotherCfunctionsanduserdatacreatedbythefunction. EnvironmentsassociatedwithLuafunctionsareusedtoresolveallaccessestoglobalvariables withinthefunction(see2.3).TheyareusedasthedefaultenvironmentfornestedLuafunctions createdbythefunction. YoucanchangetheenvironmentofaLuafunctionortherunningthreadbycallingsetfenv.You can get the environment of a Lua function or the running thread by calling getfenv. To manipulatetheenvironmentofotherobjects(userdata,Cfunctions,otherthreads)youmustuse theCAPI.

2.10 - Garbage Collection


Luaperformsautomaticmemorymanagement.Thismeansthatyouhavetoworryneitherabout allocatingmemoryfornewobjectsnoraboutfreeingitwhentheobjectsarenolongerneeded. Luamanagesmemoryautomaticallybyrunningagarbagecollectorfromtimetotimetocollectall deadobjects(thatis,objectsthatarenolongeraccessiblefromLua).AllmemoryusedbyLuais subjecttoautomaticmanagement:tables,userdata,functions,threads,strings,etc. Lua implements an incremental mark-and-sweep collector.Ituses two numbers to control its

23 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

garbage-collectioncycles:thegarbage-collectorpauseandthegarbage-collectorstepmultiplier. Bothusepercentagepointsasunits(sothatavalueof100meansaninternalvalueof1). Thegarbage-collectorpausecontrolshowlongthecollectorwaitsbeforestartinganewcycle. Largervaluesmakethecollectorlessaggressive.Valuessmallerthan100meanthecollector willnotwaittostartanewcycle.Avalueof200meansthatthecollectorwaitsforthetotalmemory inusetodoublebeforestartinganewcycle. The step multiplier controls the relative speed ofthe collector relative to memory allocation. Largervaluesmakethecollectormoreaggressivebutalsoincreasethesizeofeachincremental step.Valuessmallerthan100makethecollectortooslowandcanresultinthecollectornever finishingacycle.Thedefault,200,meansthatthecollectorrunsat"twice"thespeedofmemory allocation. Youcanchangethesenumbersbycallinglua_gcinCorcollectgarbageinLua.Withthese functionsyoucanalsocontrolthecollectordirectly(e.g.,stopandrestartit).

2.10.1 - Garbage-Collection Metamethods


Using the CAPI,you can setgarbage-collector metamethods for userdata (see 2.8).These metamethods are also called finalizers. Finalizers allow you to coordinate Lua's garbage collection with external resource management (such as closing files, network or database connections,orfreeingyourownmemory). Garbage userdata with a field __gcin their metatables are notcollected immediately by the garbagecollector.Instead,Luaputstheminalist.Afterthecollection,Luadoestheequivalentof thefollowingfunctionforeachuserdatainthatlist: function gc_event (udata) local h = metatable(udata).__gc if h then h(udata) end end Attheendofeachgarbage-collectioncycle,thefinalizersforuserdataarecalledinreverseorder oftheircreation,amongthosecollectedinthatcycle.Thatis,thefirstfinalizertobecalledisthe oneassociatedwiththeuserdatacreatedlastintheprogram.Theuserdataitselfisfreedonlyin thenextgarbage-collectioncycle.

2.10.2 - Weak Tables


Aweaktableisatablewhoseelementsareweakreferences.Aweakreferenceisignoredbythe garbagecollector.Inotherwords,iftheonlyreferencestoanobjectareweakreferences,then thegarbagecollectorwillcollectthisobject. Aweaktable can have weakkeys,weakvalues,orboth.Atable with weakkeysallowsthe collectionofitskeys,butpreventsthecollectionofitsvalues.Atablewithbothweakkeysand weakvaluesallowsthecollectionofbothkeysandvalues.Inanycase,ifeitherthekeyorthe

24 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

valueiscollected,thewholepairisremovedfromthetable.Theweaknessofatableiscontrolled bythe__modefieldofitsmetatable.Ifthe__modefieldisastringcontainingthecharacter'k',the keysinthetableareweak.If__modecontains'v',thevaluesinthetableareweak. After you use a table as a metatable,you should notchange the value ofits __modefield. Otherwise,theweakbehaviorofthetablescontrolledbythismetatableisundefined.

2.11 - Coroutines
Luasupportscoroutines,alsocalledcollaborativemultithreading.AcoroutineinLuarepresents anindependentthreadofexecution.Unlikethreadsinmultithreadsystems,however,acoroutine onlysuspendsitsexecutionbyexplicitlycallingayieldfunction. Youcreateacoroutinewithacalltocoroutine.create.Itssoleargumentisafunctionthatis themainfunctionofthecoroutine.Thecreatefunctiononlycreatesanewcoroutineandreturns ahandletoit(anobjectoftypethread);itdoesnotstartthecoroutineexecution. When you first call coroutine.resume, passing as its first argument a thread returned by coroutine.create,thecoroutinestartsitsexecution,atthefirstlineofitsmainfunction.Extra argumentspassedtocoroutine.resumearepassedontothecoroutinemainfunction.Afterthe coroutinestartsrunning,itrunsuntilitterminatesoryields. Acoroutine can terminate itsexecution in two ways:normally,when itsmain function returns (explicitlyorimplicitly,afterthelastinstruction);andabnormally,ifthereisanunprotectederror.In thefirstcase,coroutine.resumereturnstrue,plusanyvaluesreturnedbythecoroutinemain function.Incaseoferrors,coroutine.resumereturnsfalseplusanerrormessage. Acoroutine yieldsbycalling coroutine.yield.When a coroutine yields,the corresponding coroutine.resumereturnsimmediately,eveniftheyieldhappensinsidenestedfunctioncalls (thatis,notinthemainfunction,butinafunctiondirectlyorindirectlycalledbythemainfunction). In the case of a yield, coroutine.resume also returns true, plus any values passed to coroutine.yield.Thenexttimeyouresumethesamecoroutine,itcontinuesitsexecutionfrom the pointwhere ityielded,with the call to coroutine.yieldreturning any extra arguments passedtocoroutine.resume. Likecoroutine.create,thecoroutine.wrapfunctionalsocreatesacoroutine,butinsteadof returningthecoroutineitself,itreturnsafunctionthat,whencalled,resumesthecoroutine.Any arguments passed to this function go as extra arguments to coroutine.resume. coroutine.wrapreturnsallthevaluesreturnedbycoroutine.resume,exceptthefirstone(the booleanerrorcode).Unlikecoroutine.resume,coroutine.wrapdoesnotcatcherrors;any errorispropagatedtothecaller. Asanexample,considerthefollowingcode: function foo (a) print("foo", a) return coroutine.yield(2*a) end
25 of 96 05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

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", print("main", print("main", print("main", coroutine.resume(co, coroutine.resume(co, coroutine.resume(co, coroutine.resume(co, 1, 10)) "r")) "x", "y")) "x", "y"))

Whenyourunit,itproducesthefollowingoutput: co-body 1 foo 2 main co-body main co-body main main true r true x true false 10

4 11 -9 y 10 end cannot resume dead coroutine

3 - The Application Program Interface


This section describes the CAPIfor Lua,thatis,the setofCfunctions available to the host programtocommunicatewithLua.AllAPIfunctionsandrelatedtypesandconstantsaredeclared intheheaderfilelua.h. Evenwhenweusetheterm"function",anyfacilityintheAPImaybeprovidedasamacroinstead. Allsuchmacrosuseeachoftheirargumentsexactlyonce(exceptforthefirstargument,whichis alwaysaLuastate),andsodonotgenerateanyhiddenside-effects. As in most Clibraries, the Lua API functions do not check their arguments for validity or consistency.However,youcanchangethisbehaviorbycompilingLuawithaproperdefinitionfor themacroluai_apicheck,infileluaconf.h.

3.1 - The Stack


LuausesavirtualstacktopassvaluestoandfromC.EachelementinthisstackrepresentsaLua value(nil,number,string,etc.). WheneverLuacallsC,thecalledfunctiongetsanewstack,whichisindependentofprevious

26 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

stacksandofstacksofCfunctionsthatarestillactive.Thisstackinitiallycontainsanyarguments totheCfunctionanditiswheretheCfunctionpushesitsresultstobereturnedtothecaller(see lua_CFunction). Forconvenience,mostqueryoperationsintheAPIdonotfollowastrictstackdiscipline.Instead, theycan referto anyelementin the stackbyusing an index:Apositive indexrepresentsan absolutestackposition(startingat1);anegativeindexrepresentsanoffsetrelativetothetopof thestack.Morespecifically,ifthestackhasnelements,thenindex1representsthefirstelement (thatis,theelementthatwaspushedontothestackfirst)andindexnrepresentsthelastelement; index-1alsorepresentsthelastelement(thatis,theelementatthetop)andindex-nrepresents thefirstelement.Wesaythatanindexisvalidifitliesbetween1andthestacktop(thatis,if1 abs(index) top).

3.2 - Stack Size


WhenyouinteractwithLuaAPI,youareresponsibleforensuringconsistency.Inparticular,you areresponsibleforcontrollingstackoverflow.Youcanusethefunctionlua_checkstacktogrow thestacksize. Whenever Lua calls C,itensures thatatleastLUA_MINSTACKstack positions are available. LUA_MINSTACKisdefined as20,so thatusuallyyou do nothave to worryaboutstackspace unlessyourcodehasloopspushingelementsontothestack. Mostqueryfunctionsacceptasindicesanyvalueinsidetheavailablestackspace,thatis,indices uptothemaximumstacksizeyouhavesetthroughlua_checkstack.Suchindicesarecalled acceptableindices.Moreformally,wedefineanacceptableindexasfollows: (index < 0 && abs(index) <= top) || (index > 0 && index <= stackspace) Notethat0isneveranacceptableindex.

3.3 - Pseudo-Indices
Unlessotherwisenoted,anyfunctionthatacceptsvalidindicescanalsobecalledwithpseudoindices,whichrepresentsomeLuavaluesthatareaccessibletoCcodebutwhicharenotinthe stack.Pseudo-indicesareusedtoaccessthethreadenvironment,thefunctionenvironment,the registry,andtheupvaluesofaCfunction(see3.4). The thread environment (where global variables live) is always at pseudo-index LUA_GLOBALSINDEX. The environment of the running Cfunction is always at pseudo-index LUA_ENVIRONINDEX. Toaccessandchangethevalueofglobalvariables,youcanuseregulartableoperationsover anenvironmenttable.Forinstance,toaccessthevalueofaglobalvariable,do

27 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

lua_getfield(L, LUA_GLOBALSINDEX, varname);

3.4 - C Closures
When a Cfunction iscreated,itispossible to associate some valueswith it,thuscreating a Cclosure;these valuesare called upvaluesand are accessible to the function wheneveritis called(seelua_pushcclosure). Whenever a Cfunction is called,its upvalues are located atspecific pseudo-indices.These pseudo-indicesareproducedbythemacrolua_upvalueindex.Thefirstvalueassociatedwith a function is at position lua_upvalueindex(1), and so on. Any access to lua_upvalueindex(n),wherenisgreaterthanthenumberofupvaluesofthecurrentfunction (butnotgreaterthan256),producesanacceptable(butinvalid)index.

3.5 - Registry
Luaprovidesaregistry,apre-definedtablethatcanbeusedbyanyCcodetostorewhatever Luavalueitneedstostore.Thistableisalwayslocatedatpseudo-indexLUA_REGISTRYINDEX. AnyClibrarycanstoredataintothistable,butitshouldtakecaretochoosekeysdifferentfrom those used by other libraries,to avoid collisions.Typically,you should use as key a string containingyourlibrarynameoralightuserdatawiththeaddressofaCobjectinyourcode. The integer keys in the registry are used by the reference mechanism,implemented by the auxiliarylibrary,andthereforeshouldnotbeusedforotherpurposes.

3.6 - Error Handling in C


Internally, Lua uses the C longjmp facility to handle errors. (You can also choose to use exceptionsifyou use C++;see file luaconf.h.)When Lua facesanyerror(such asmemory allocationerrors,typeerrors,syntaxerrors,andruntimeerrors)itraisesanerror;thatis,itdoesa longjump.Aprotectedenvironmentusessetjmptosetarecoverpoint;anyerrorjumpstothe mostrecentactiverecoverpoint. MostfunctionsintheAPIcanthrowanerror,forinstanceduetoamemoryallocationerror.The documentationforeachfunctionindicateswhetheritcanthrowerrors. InsideaCfunctionyoucanthrowanerrorbycallinglua_error.

3.7 - Functions and Types


HerewelistallfunctionsandtypesfromtheCAPIinalphabeticalorder.Eachfunctionhasan [-o,+p,x] indicatorlikethis:

28 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Thefirstfield,o,ishowmanyelementsthefunctionpopsfromthestack.Thesecondfield,p,is howmanyelementsthefunctionpushesontothestack.(Anyfunctionalwayspushesitsresults afterpoppingitsarguments.)Afieldintheformx|ymeansthefunctioncanpush(orpop)xory elements,dependingonthesituation;aninterrogationmark'?'meansthatwecannotknowhow manyelementsthefunctionpops/pushesbylookingonlyatitsarguments(e.g.,theymaydepend onwhatisonthestack).Thethirdfield,x,tellswhetherthefunctionmaythrowerrors:'-'means thefunctionneverthrowsanyerror;'m'meansthefunctionmaythrowanerroronlyduetonot enoughmemory;'e'meansthefunctionmaythrowotherkindsoferrors;'v'meansthefunction maythrowanerroronpurpose.

lua_Alloc
typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); The type ofthe memory-allocation function used by Lua states.The allocator function must provide a functionalitysimilarto realloc,butnotexactlythe same.Itsargumentsare ud,an opaquepointerpassedtolua_newstate;ptr,apointertotheblockbeingallocated/reallocated /freed;osize,theoriginalsizeoftheblock;nsize,thenewsizeoftheblock.ptrisNULLifand onlyifosizeiszero.Whennsizeiszero,theallocatormustreturnNULL;ifosizeisnotzero,it shouldfreetheblockpointedtobyptr.Whennsizeisnotzero,theallocatorreturnsNULLifand onlyifitcannotfilltherequest.Whennsizeisnotzeroandosizeiszero,theallocatorshould behavelikemalloc.Whennsizeandosizearenotzero,theallocatorbehaveslikerealloc. Luaassumesthattheallocatorneverfailswhenosize >= nsize. Here isa simple implementation forthe allocatorfunction.Itisused in the auxiliarylibraryby 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); } This code assumes that free(NULL) has no effect and that realloc(NULL, size) is equivalenttomalloc(size).ANSICensuresbothbehaviors.

lua_atpanic
lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);
[-0,+0,-]

29 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Setsanewpanicfunctionandreturnstheoldone. Ifanerrorhappensoutsideanyprotectedenvironment,Luacallsapanicfunctionandthencalls exit(EXIT_FAILURE),thusexitingthehostapplication.Yourpanicfunctioncanavoidthisexit byneverreturning(e.g.,doingalongjump). Thepanicfunctioncanaccesstheerrormessageatthetopofthestack.

lua_call
void lua_call (lua_State *L, int nargs, int nresults); Callsafunction. Tocallafunctionyoumustusethefollowingprotocol:first,thefunctiontobecalledispushed onto the stack;then,the argumentsto the function are pushed in directorder;thatis,the first argumentispushedfirst.Finallyyoucalllua_call;nargsisthenumberofargumentsthatyou pushedontothestack.Allargumentsandthefunctionvaluearepoppedfromthestackwhenthe functioniscalled.Thefunctionresultsarepushedontothestackwhenthefunctionreturns.The numberofresultsisadjustedtonresults,unlessnresultsisLUA_MULTRET.Inthiscase,all resultsfromthe function are pushed.Lua takescare thatthe returned valuesfitinto the stack space.Thefunctionresultsarepushedontothestackindirectorder(thefirstresultispushed first),sothatafterthecallthelastresultisonthetopofthestack. Anyerrorinsidethecalledfunctionispropagatedupwards(withalongjmp). ThefollowingexampleshowshowthehostprogramcandotheequivalenttothisLuacode: a = f("how", t.x, 14) HereitisinC: lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* function to be called lua_pushstring(L, "how"); /* 1st argument lua_getfield(L, LUA_GLOBALSINDEX, "t"); /* table to be indexed lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) lua_remove(L, -2); /* remove 't' from the stack lua_pushinteger(L, 14); /* 3rd argument lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result lua_setfield(L, LUA_GLOBALSINDEX, "a"); /* set global 'a' */ */ */ */ */ */ */ */
[-(nargs+1),+nresults,e]

Notethatthecodeaboveis"balanced":atitsend,thestackisbacktoitsoriginalconfiguration. Thisisconsideredgoodprogrammingpractice.

lua_CFunction
typedef int (*lua_CFunction) (lua_State *L);

30 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

TypeforCfunctions. InordertocommunicateproperlywithLua,aCfunctionmustusethefollowingprotocol,which definesthewayparametersandresultsarepassed:aCfunctionreceivesitsargumentsfromLua in its stack in direct order (the first argument is pushed first). So, when the function starts, lua_gettop(L)returnsthenumberofargumentsreceivedbythefunction.Thefirstargument(if any)isatindex1anditslastargumentisatindexlua_gettop(L).ToreturnvaluestoLua,a Cfunction justpushesthemonto the stack,in directorder(the firstresultispushed first),and returnsthe numberofresults.Anyothervalue in the stackbelow the resultswill be properly discardedbyLua.LikeaLuafunction,aCfunctioncalledbyLuacanalsoreturnmanyresults. Asanexample,thefollowingfunctionreceivesavariablenumberofnumericalargumentsand returnstheiraverageandsum: static int foo (lua_State *L) { int n = lua_gettop(L); /* number of arguments 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); /* first result lua_pushnumber(L, sum); /* second result return 2; /* number of results } */

*/ */ */

lua_checkstack
int lua_checkstack (lua_State *L, int extra);
[-0,+0,m]

Ensuresthatthereareatleastextrafreestackslotsinthestack.Itreturnsfalseifitcannotgrow thestacktothatsize.Thisfunctionnevershrinksthestack;ifthestackisalreadylargerthanthe newsize,itisleftunchanged.

lua_close
void lua_close (lua_State *L);
[-0,+0,-]

Destroys all objects in the given Lua state (calling the corresponding garbage-collection metamethods,ifany)andfreesalldynamicmemoryusedbythisstate.Onseveralplatforms,you maynotneedtocallthisfunction,becauseallresourcesarenaturallyreleasedwhenthehost programends.Ontheotherhand,long-runningprograms,suchasadaemonorawebserver, mightneedtoreleasestatesassoonastheyarenotneeded,toavoidgrowingtoolarge.

31 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

lua_concat
void lua_concat (lua_State *L, int n);
[-n,+1,e]

Concatenatesthenvaluesatthetopofthestack,popsthem,andleavestheresultatthetop.If nis1,theresultisthesinglevalueonthestack(thatis,thefunctiondoesnothing);ifnis0,the resultistheemptystring.ConcatenationisperformedfollowingtheusualsemanticsofLua(see 2.5.4).

lua_cpcall
int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);
[-0,+(0|1),-]

CallstheCfunctionfuncinprotectedmode.funcstartswithonlyoneelementinitsstack,alight userdata containing ud. In case of errors, lua_cpcall returns the same error codes as lua_pcall,plustheerrorobjectonthetopofthestack;otherwise,itreturnszero,anddoesnot changethestack.Allvaluesreturnedbyfuncarediscarded.

lua_createtable
void lua_createtable (lua_State *L, int narr, int nrec);
[-0,+1,m]

Createsanewemptytableandpushesitontothestack.Thenewtablehasspacepre-allocated fornarrarrayelementsand nrecnon-arrayelements.Thispre-allocation isuseful whenyou know exactly how many elements the table will have. Otherwise you can use the function lua_newtable.

lua_dump
int lua_dump (lua_State *L, lua_Writer writer, void *data);
[-0,+0,m]

Dumps a function as a binary chunk.Receives a Lua function on the top ofthe stack and producesabinarychunkthat,ifloadedagain,resultsinafunctionequivalenttotheonedumped. Asitproducespartsofthechunk,lua_dumpcallsfunctionwriter(seelua_Writer)withthe givendatatowritethem. Thevaluereturnedistheerrorcodereturnedbythelastcalltothewriter;0meansnoerrors. ThisfunctiondoesnotpoptheLuafunctionfromthestack.

lua_equal
int lua_equal (lua_State *L, int index1, int index2);
[-0,+0,e]

Returns1ifthetwovaluesinacceptableindicesindex1andindex2areequal,followingthe semantics ofthe Lua ==operator (thatis,may call metamethods).Otherwise returns0.Also

32 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

returns0ifanyoftheindicesisnonvalid.

lua_error
int lua_error (lua_State *L);
[-1,+0,v]

GeneratesaLuaerror.Theerrormessage(whichcanactuallybeaLuavalueofanytype)must be on the stack top. This function does a long jump, and therefore never returns. (see luaL_error).

lua_gc
int lua_gc (lua_State *L, int what, int data); Controlsthegarbagecollector. Thisfunctionperformsseveraltasks,accordingtothevalueoftheparameterwhat: LUA_GCSTOP:stopsthegarbagecollector. LUA_GCRESTART:restartsthegarbagecollector. LUA_GCCOLLECT:performsafullgarbage-collectioncycle. LUA_GCCOUNT:returnsthecurrentamountofmemory(inKbytes)inusebyLua. LUA_GCCOUNTB:returnstheremainderofdividingthecurrentamountofbytesofmemoryin usebyLuaby1024. LUA_GCSTEP: performs an incremental step of garbage collection. The step "size" is controlledbydata(largervaluesmeanmoresteps)inanon-specifiedway.Ifyouwantto controlthestepsizeyoumustexperimentallytunethevalueofdata.Thefunctionreturns1 ifthestepfinishedagarbage-collectioncycle. LUA_GCSETPAUSE:setsdataasthenewvalueforthepauseofthecollector(see2.10). Thefunctionreturnsthepreviousvalueofthepause. LUA_GCSETSTEPMUL:setsdataasthenewvalueforthestepmultiplierofthecollector(see 2.10).Thefunctionreturnsthepreviousvalueofthestepmultiplier.
[-0,+0,e]

lua_getallocf
lua_Alloc lua_getallocf (lua_State *L, void **ud);
[-0,+0,-]

Returnsthememory-allocationfunctionofagivenstate.IfudisnotNULL,Luastoresin*udthe opaquepointerpassedtolua_newstate.

lua_getfenv
void lua_getfenv (lua_State *L, int index); Pushesontothestacktheenvironmenttableofthevalueatthegivenindex.
[-0,+1,-]

33 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

lua_getfield
void lua_getfield (lua_State *L, int index, const char *k);
[-0,+1,e]

Pushesontothestackthevaluet[k],wheretisthevalueatthegivenvalidindex.AsinLua, thisfunctionmaytriggerametamethodforthe"index"event(see2.8).

lua_getglobal
void lua_getglobal (lua_State *L, const char *name); Pushesontothestackthevalueoftheglobalname.Itisdefinedasamacro: #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s)
[-0,+1,e]

lua_getmetatable
int lua_getmetatable (lua_State *L, int index);
[-0,+(0|1),-]

Pushesontothestackthemetatableofthevalueatthegivenacceptableindex.Iftheindexisnot valid,orifthevaluedoesnothaveametatable,thefunctionreturns0andpushesnothingonthe stack.

lua_gettable
void lua_gettable (lua_State *L, int index);
[-1,+1,e]

Pushesontothestackthevaluet[k],wheretisthevalueatthegivenvalidindexandkisthe valueatthetopofthestack. Thisfunctionpopsthekeyfromthestack(puttingtheresultingvalueinitsplace).AsinLua,this functionmaytriggerametamethodforthe"index"event(see2.8).

lua_gettop
int lua_gettop (lua_State *L);
[-0,+0,-]

Returnstheindexofthetopelementinthestack.Becauseindicesstartat1,thisresultisequalto thenumberofelementsinthestack(andso0meansanemptystack).

lua_insert
void lua_insert (lua_State *L, int index);
[-1,+1,-]

Movesthetopelementintothegivenvalidindex,shiftinguptheelementsabovethisindexto

34 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

open space.Cannotbe called with a pseudo-index,because a pseudo-indexisnotan actual stackposition.

lua_Integer
typedef ptrdiff_t lua_Integer; ThetypeusedbytheLuaAPItorepresentintegralvalues. By defaultitis a ptrdiff_t,which is usually the largestsigned integral type the machine handles"comfortably".

lua_isboolean
int lua_isboolean (lua_State *L, int index); Returns1ifthevalueatthegivenacceptableindexhastypeboolean,and0otherwise.
[-0,+0,-]

lua_iscfunction
int lua_iscfunction (lua_State *L, int index); Returns1ifthevalueatthegivenacceptableindexisaCfunction,and0otherwise.
[-0,+0,-]

lua_isfunction
int lua_isfunction (lua_State *L, int index);
[-0,+0,-]

Returns 1 if the value at the given acceptable index is a function (either C or Lua), and 0otherwise.

lua_islightuserdata
int lua_islightuserdata (lua_State *L, int index); Returns1ifthevalueatthegivenacceptableindexisalightuserdata,and0otherwise.
[-0,+0,-]

lua_isnil
int lua_isnil (lua_State *L, int index); Returns1ifthevalueatthegivenacceptableindexisnil,and0otherwise.
[-0,+0,-]

lua_isnone
[-0,+0,-]

35 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

int lua_isnone (lua_State *L, int index); Returns1ifthegivenacceptableindexisnotvalid(thatis,itreferstoanelementoutsidethe currentstack),and0otherwise.

lua_isnoneornil
int lua_isnoneornil (lua_State *L, int index);
[-0,+0,-]

Returns1ifthegivenacceptableindexisnotvalid(thatis,itreferstoanelementoutsidethe currentstack)orifthevalueatthisindexisnil,and0otherwise.

lua_isnumber
int lua_isnumber (lua_State *L, int index);
[-0,+0,-]

Returns1 ifthe value atthe given acceptable indexisa numberora string convertible to a number,and0otherwise.

lua_isstring
int lua_isstring (lua_State *L, int index);
[-0,+0,-]

Returns1 ifthe value atthe given acceptable indexisa string ora number(which isalways convertibletoastring),and0otherwise.

lua_istable
int lua_istable (lua_State *L, int index); Returns1ifthevalueatthegivenacceptableindexisatable,and0otherwise.
[-0,+0,-]

lua_isthread
int lua_isthread (lua_State *L, int index); Returns1ifthevalueatthegivenacceptableindexisathread,and0otherwise.
[-0,+0,-]

lua_isuserdata
int lua_isuserdata (lua_State *L, int index);
[-0,+0,-]

Returns 1 ifthe value atthe given acceptable index is a userdata (either full or light),and 0otherwise.

36 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

lua_lessthan
int lua_lessthan (lua_State *L, int index1, int index2);
[-0,+0,e]

Returns1ifthevalueatacceptableindexindex1issmallerthanthevalueatacceptableindex index2,followingthesemanticsoftheLua<operator(thatis,maycallmetamethods).Otherwise returns0.Alsoreturns0ifanyoftheindicesisnonvalid.

lua_load
int lua_load (lua_State *L, lua_Reader reader, void *data, const char *chunkname);
[-0,+1,-]

Loads a Lua chunk.Ifthere are no errors,lua_loadpushes the compiled chunk as a Lua function on top of the stack. Otherwise, it pushes an error message. The return values of lua_loadare: 0:noerrors; LUA_ERRSYNTAX:syntaxerrorduringpre-compilation; LUA_ERRMEM:memoryallocationerror. Thisfunctiononlyloadsachunk;itdoesnotrunit. lua_loadautomaticallydetectswhetherthechunkistextorbinary,andloadsitaccordingly(see programluac). The lua_load function uses a user-supplied reader function to read the chunk (see lua_Reader).Thedataargumentisanopaquevaluepassedtothereaderfunction. Thechunknameargumentgivesanametothechunk,whichisusedforerrormessagesandin debuginformation(see3.8).

lua_newstate
lua_State *lua_newstate (lua_Alloc f, void *ud);
[-0,+0,-]

Creates a new, independent state. Returns NULL if cannot create the state (due to lack of memory).Theargumentfistheallocatorfunction;Luadoesallmemoryallocationforthisstate throughthisfunction.Thesecondargument,ud,isanopaquepointerthatLuasimplypassesto theallocatorineverycall.

lua_newtable
void lua_newtable (lua_State *L);
[-0,+1,m]

37 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Createsanewemptytableandpushesitontothestack.Itisequivalenttolua_createtable(L, 0, 0).

lua_newthread
lua_State *lua_newthread (lua_State *L);
[-0,+1,m]

Creates a new thread, pushes it on the stack, and returns a pointer to a lua_State that representsthisnewthread.Thenewstatereturnedbythisfunctionshareswiththeoriginalstate allglobalobjects(suchastables),buthasanindependentexecutionstack. There is no explicitfunction to close or to destroy a thread.Threads are subjectto garbage collection,likeanyLuaobject.

lua_newuserdata
void *lua_newuserdata (lua_State *L, size_t size);
[-0,+1,m]

Thisfunctionallocatesanewblockofmemorywiththegivensize,pushesontothestackanew fulluserdatawiththeblockaddress,andreturnsthisaddress. UserdatarepresentCvaluesinLua.Afulluserdatarepresentsablockofmemory.Itisanobject (likeatable):youmustcreateit,itcanhaveitsownmetatable,andyoucandetectwhenitis beingcollected.Afulluserdataisonlyequaltoitself(underrawequality). WhenLuacollectsafulluserdatawithagcmetamethod,Luacallsthemetamethodandmarks theuserdataasfinalized.WhenthisuserdataiscollectedagainthenLuafreesitscorresponding memory.

lua_next
int lua_next (lua_State *L, int index);
[-1,+(2|0),e]

Popsakeyfromthestack,andpushesakey-valuepairfromthetableatthegivenindex(the "next"pairafterthegivenkey).Iftherearenomoreelementsinthetable,thenlua_nextreturns 0(andpushesnothing). Atypicaltraversallookslikethis: /* table is in the stack at index 't' */ lua_pushnil(L); /* first key */ while (lua_next(L, t) != 0) { /* uses 'key' (at index -2) and 'value' (at index -1) */ printf("%s - %s\n", lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1))); /* removes 'value'; keeps 'key' for next iteration */

38 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

lua_pop(L, 1); } Whiletraversingatable,donotcalllua_tolstringdirectlyonakey,unlessyouknowthatthe keyisactuallyastring.Recallthatlua_tolstringchangesthevalueatthegivenindex;this confusesthenextcalltolua_next.

lua_Number
typedef double lua_Number; ThetypeofnumbersinLua.Bydefault,itisdouble,butthatcanbechangedinluaconf.h. ThroughtheconfigurationfileyoucanchangeLuatooperatewithanothertypefornumbers(e.g., floatorlong).

lua_objlen
size_t lua_objlen (lua_State *L, int index);
[-0,+0,-]

Returnsthe"length"ofthevalueatthegivenacceptableindex:forstrings,thisisthestringlength; fortables,thisistheresultofthelengthoperator('#');foruserdata,thisisthesizeoftheblockof memoryallocatedfortheuserdata;forothervalues,itis0.

lua_pcall
int lua_pcall (lua_State *L, int nargs, int nresults, int [-(nargs+1),+(nresults|1),-] errfunc); Callsafunctioninprotectedmode. Bothnargsandnresultshavethesamemeaningasinlua_call.Iftherearenoerrorsduring thecall,lua_pcallbehavesexactlylikelua_call.However,ifthereisanyerror,lua_pcall catchesit,pushesasinglevalueonthestack(theerrormessage),andreturnsanerrorcode. Likelua_call,lua_pcallalwaysremovesthefunctionanditsargumentsfromthestack. If errfunc is 0, then the error message returned on the stack is exactly the original error message.Otherwise,errfuncis the stack index ofan error handler function.(In the current implementation,thisindexcannotbeapseudo-index.)Incaseofruntimeerrors,thisfunctionwill becalledwiththeerrormessageanditsreturnvaluewillbethemessagereturnedonthestack bylua_pcall. Typically,theerrorhandlerfunctionisusedtoaddmoredebuginformationtotheerrormessage, suchasastacktraceback.Suchinformationcannotbegatheredafterthereturnoflua_pcall, sincebythenthestackhasunwound. Thelua_pcallfunctionreturns0incaseofsuccessoroneofthefollowingerrorcodes(defined inlua.h):

39 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

LUA_ERRRUN:aruntimeerror. LUA_ERRMEM:memoryallocationerror.Forsucherrors,Luadoesnotcalltheerrorhandler function. LUA_ERRERR:errorwhilerunningtheerrorhandlerfunction.

lua_pop
void lua_pop (lua_State *L, int n); Popsnelementsfromthestack.
[-n,+0,-]

lua_pushboolean
void lua_pushboolean (lua_State *L, int b); Pushesabooleanvaluewithvaluebontothestack.
[-0,+1,-]

lua_pushcclosure
void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n); PushesanewCclosureontothestack. When a Cfunction iscreated,itispossible to associate some valueswith it,thuscreating a Cclosure(see3.4);thesevaluesarethenaccessibletothefunctionwheneveritiscalled.To associate valueswith a Cfunction,firstthese valuesshould be pushed onto the stack(when therearemultiplevalues,thefirstvalueispushedfirst).Thenlua_pushcclosureiscalledto create and push the Cfunction onto the stack,with the argumentntelling how manyvalues should be associated with the function.lua_pushcclosurealso popsthese valuesfromthe stack. Themaximumvaluefornis255.
[-n,+1,m]

lua_pushcfunction
void lua_pushcfunction (lua_State *L, lua_CFunction f);
[-0,+1,m]

PushesaCfunctionontothestack.ThisfunctionreceivesapointertoaCfunctionandpushes onto the stack a Lua value oftype function that,when called,invokes the corresponding Cfunction. AnyfunctiontoberegisteredinLuamustfollowthecorrectprotocoltoreceiveitsparametersand returnitsresults(seelua_CFunction). lua_pushcfunctionisdefinedasamacro:

40 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

#define lua_pushcfunction(L,f)

lua_pushcclosure(L,f,0)

lua_pushfstring
const char *lua_pushfstring (lua_State *L, const char *fmt, ...);
[-0,+1,m]

Pushesontothestackaformattedstringandreturnsapointertothisstring.Itissimilartothe Cfunctionsprintf,buthassomeimportantdifferences: Youdonothavetoallocatespacefortheresult:theresultisaLuastringandLuatakescare ofmemoryallocation(anddeallocation,throughgarbagecollection). Theconversionspecifiersarequiterestricted.Therearenoflags,widths,orprecisions.The conversion specifiers can only be '%%' (inserts a '%' in the string), '%s' (inserts a zero-terminatedstring,withnosizerestrictions),'%f'(insertsalua_Number),'%p'(insertsa pointer as a hexadecimal numeral),'%d'(inserts an int),and '%c'(inserts an intas a character).

lua_pushinteger
void lua_pushinteger (lua_State *L, lua_Integer n); Pushesanumberwithvaluenontothestack.
[-0,+1,-]

lua_pushlightuserdata
void lua_pushlightuserdata (lua_State *L, void *p); Pushesalightuserdataontothestack. UserdatarepresentCvaluesinLua.Alightuserdata representsa pointer.Itisa value(likea number):you do notcreate it,ithasno individual metatable,and itisnotcollected (asitwas nevercreated).Alightuserdataisequalto"any"lightuserdatawiththesameCaddress.
[-0,+1,-]

lua_pushliteral
void lua_pushliteral (lua_State *L, const char *s);
[-0,+1,m]

Thismacroisequivalenttolua_pushlstring,butcanbeusedonlywhensisaliteralstring.In thesecases,itautomaticallyprovidesthestringlength.

lua_pushlstring
void lua_pushlstring (lua_State *L, const char *s, size_t len);
[-0,+1,m]

Pushesthestringpointedtobyswithsizelenontothestack.Luamakes(orreuses)aninternal

41 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

copyofthegivenstring,sothememoryatscanbefreedorreusedimmediatelyafterthefunction returns.Thestringcancontainembeddedzeros.

lua_pushnil
void lua_pushnil (lua_State *L); Pushesanilvalueontothestack.
[-0,+1,-]

lua_pushnumber
void lua_pushnumber (lua_State *L, lua_Number n); Pushesanumberwithvaluenontothestack.
[-0,+1,-]

lua_pushstring
void lua_pushstring (lua_State *L, const char *s);
[-0,+1,m]

Pushes the zero-terminated string pointed to by sonto the stack.Lua makes (or reuses) an internalcopyofthegivenstring,sothememoryatscanbefreedorreusedimmediatelyafterthe functionreturns.Thestringcannotcontainembeddedzeros;itisassumedtoendatthefirstzero.

lua_pushthread
int lua_pushthread (lua_State *L);
[-0,+1,-]

PushesthethreadrepresentedbyLontothestack.Returns1ifthisthreadisthemainthreadof itsstate.

lua_pushvalue
void lua_pushvalue (lua_State *L, int index); Pushesacopyoftheelementatthegivenvalidindexontothestack.
[-0,+1,-]

lua_pushvfstring
const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp);
[-0,+1,m]

Equivalenttolua_pushfstring,exceptthatitreceivesava_listinsteadofavariablenumber ofarguments.

42 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

lua_rawequal
int lua_rawequal (lua_State *L, int index1, int index2);
[-0,+0,-]

Returns1ifthetwovaluesinacceptableindicesindex1andindex2areprimitivelyequal(that is,withoutcallingmetamethods).Otherwisereturns0.Alsoreturns0ifanyoftheindicesarenon valid.

lua_rawget
void lua_rawget (lua_State *L, int index); Similartolua_gettable,butdoesarawaccess(i.e.,withoutmetamethods).
[-1,+1,-]

lua_rawgeti
void lua_rawgeti (lua_State *L, int index, int n);
[-0,+1,-]

Pushesontothestackthevaluet[n],wheretisthevalueatthegivenvalidindex.Theaccessis raw;thatis,itdoesnotinvokemetamethods.

lua_rawset
void lua_rawset (lua_State *L, int index); Similartolua_settable,butdoesarawassignment(i.e.,withoutmetamethods).
[-2,+0,m]

lua_rawseti
void lua_rawseti (lua_State *L, int index, int n);
[-1,+0,m]

Doestheequivalentoft[n] = v,wheretisthevalueatthegivenvalidindexandvisthevalue atthetopofthestack. Thisfunction popsthevalue fromthe stack.The assignmentisraw;thatis,itdoesnotinvoke metamethods.

lua_Reader
typedef const char * (*lua_Reader) (lua_State *L, void *data, size_t *size); The reader function used by lua_load. Every time it needs another piece of the chunk, lua_loadcallsthereader,passingalongitsdataparameter.Thereadermustreturnapointerto

43 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

ablockofmemorywithanewpieceofthechunkandsetsizetotheblocksize.Theblockmust existuntilthereaderfunctioniscalledagain.Tosignaltheendofthechunk,thereadermust returnNULLorsetsizetozero.Thereaderfunctionmayreturnpiecesofanysizegreaterthan zero.

lua_register
void lua_register (lua_State *L, const char *name, lua_CFunction f); SetstheCfunctionfasthenewvalueofglobalname.Itisdefinedasamacro: #define lua_register(L,n,f) \ (lua_pushcfunction(L, f), lua_setglobal(L, n))
[-0,+0,e]

lua_remove
void lua_remove (lua_State *L, int index);
[-1,+0,-]

Removestheelementatthegivenvalidindex,shiftingdowntheelementsabovethisindextofill thegap.Cannotbecalledwithapseudo-index,becauseapseudo-indexisnotanactualstack position.

lua_replace
void lua_replace (lua_State *L, int index);
[-1,+0,-]

Moves the top element into the given position (and pops it), without shifting any element (thereforereplacingthevalueatthegivenposition).

lua_resume
int lua_resume (lua_State *L, int narg); Startsandresumesacoroutineinagiventhread. Tostartacoroutine,youfirstcreateanewthread(seelua_newthread);thenyoupushontoits stackthe main function plusanyarguments;then you call lua_resume,with nargbeing the numberofarguments.Thiscall returnswhen the coroutine suspendsorfinishesitsexecution. Whenitreturns,thestackcontainsallvaluespassedtolua_yield,orallvaluesreturnedbythe bodyfunction.lua_resumereturnsLUA_YIELDifthecoroutineyields,0ifthecoroutinefinishes itsexecutionwithouterrors,oranerrorcodeincaseoferrors(seelua_pcall).Incaseoferrors, thestackisnotunwound,soyoucanusethedebugAPIoverit.Theerrormessageisonthetop ofthestack.Torestartacoroutine,youputonitsstackonlythevaluestobepassedasresults fromyield,andthencalllua_resume.
[-?,+?,-]

44 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

lua_setallocf
void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); Changestheallocatorfunctionofagivenstatetofwithuserdataud.
[-0,+0,-]

lua_setfenv
int lua_setfenv (lua_State *L, int index);
[-1,+0,-]

Popsatablefromthestackandsetsitasthenewenvironmentforthevalueatthegivenindex.If the value atthe given indexisneithera function nora thread nora userdata,lua_setfenv returns0.Otherwiseitreturns1.

lua_setfield
void lua_setfield (lua_State *L, int index, const char *k);
[-1,+0,e]

Doestheequivalenttot[k] = v,wheretisthevalueatthegivenvalidindexandvisthevalue atthetopofthestack. Thisfunctionpopsthevaluefromthestack.AsinLua,thisfunctionmaytriggerametamethodfor the"newindex"event(see2.8).

lua_setglobal
void lua_setglobal (lua_State *L, const char *name);
[-1,+0,e]

Popsavaluefromthestackandsetsitasthenewvalueofglobalname.Itisdefinedasamacro: #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s)

lua_setmetatable
int lua_setmetatable (lua_State *L, int index);
[-1,+0,-]

Popsatablefromthestackandsetsitasthenewmetatableforthevalueatthegivenacceptable index.

lua_settable
void lua_settable (lua_State *L, int index);
[-2,+0,e]

Doestheequivalenttot[k] = v,wheretisthevalueatthegivenvalidindex,visthevalueat thetopofthestack,andkisthevaluejustbelowthetop.


45 of 96 05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Thisfunctionpopsboththekeyandthevaluefromthestack.AsinLua,thisfunctionmaytriggera metamethodforthe"newindex"event(see2.8).

lua_settop
void lua_settop (lua_State *L, int index);
[-?,+?,-]

Acceptsanyacceptableindex,or0,andsetsthestacktoptothisindex.Ifthenewtopislarger thantheoldone,thenthenewelementsarefilledwithnil.Ifindexis0,thenallstackelements areremoved.

lua_State
typedef struct lua_State lua_State; OpaquestructurethatkeepsthewholestateofaLuainterpreter.TheLualibraryisfullyreentrant: ithasnoglobalvariables.Allinformationaboutastateiskeptinthisstructure. Apointertothisstatemustbepassedasthefirstargumenttoeveryfunctioninthelibrary,except tolua_newstate,whichcreatesaLuastatefromscratch.

lua_status
int lua_status (lua_State *L); ReturnsthestatusofthethreadL. Thestatuscanbe0foranormalthread,anerrorcodeifthethreadfinisheditsexecutionwithan error,orLUA_YIELDifthethreadissuspended.
[-0,+0,-]

lua_toboolean
int lua_toboolean (lua_State *L, int index);
[-0,+0,-]

ConvertstheLuavalueatthegivenacceptableindextoaCbooleanvalue(0or1).Likealltests in Lua,lua_tobooleanreturns1 foranyLua value differentfromfalse and nil;otherwise it returns0.Italsoreturns0whencalledwithanon-validindex.(Ifyouwanttoacceptonlyactual booleanvalues,uselua_isbooleantotestthevalue'stype.)

lua_tocfunction
lua_CFunction lua_tocfunction (lua_State *L, int index);
[-0,+0,-]

ConvertsavalueatthegivenacceptableindextoaCfunction.ThatvaluemustbeaCfunction; otherwise,returnsNULL.

46 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

lua_tointeger
lua_Integer lua_tointeger (lua_State *L, int index);
[-0,+0,-]

ConvertstheLuavalueatthegivenacceptableindextothesignedintegraltypelua_Integer. The Lua value mustbe a numberora string convertible to a number(see 2.2.1);otherwise, lua_tointegerreturns0. Ifthenumberisnotaninteger,itistruncatedinsomenon-specifiedway.

lua_tolstring
const char *lua_tolstring (lua_State *L, int index, size_t *len);
[-0,+0,m]

ConvertstheLuavalueatthegivenacceptableindextoaCstring.IflenisnotNULL,italsosets *lenwiththestringlength.TheLuavaluemustbeastringoranumber;otherwise,thefunction returnsNULL.Ifthevalueisanumber,thenlua_tolstringalsochangestheactualvalueinthe stackto a string.(Thischange confuseslua_nextwhen lua_tolstringisapplied to keys duringatabletraversal.) lua_tolstringreturnsafullyalignedpointertoastringinsidetheLuastate.Thisstringalways hasazero('\0')afteritslastcharacter(asinC),butcancontainotherzerosinitsbody.Because Luahasgarbagecollection,thereisnoguaranteethatthepointerreturnedbylua_tolstring willbevalidafterthecorrespondingvalueisremovedfromthestack.

lua_tonumber
lua_Number lua_tonumber (lua_State *L, int index);
[-0,+0,-]

Converts the Lua value at the given acceptable index to the Ctype lua_Number (see lua_Number).TheLuavaluemustbeanumberorastringconvertibletoanumber(see2.2.1); otherwise,lua_tonumberreturns0.

lua_topointer
const void *lua_topointer (lua_State *L, int index);
[-0,+0,-]

ConvertsthevalueatthegivenacceptableindextoagenericCpointer(void*).Thevaluecan beauserdata,atable,athread,orafunction;otherwise,lua_topointerreturnsNULL.Different objectswillgivedifferentpointers.Thereisnowaytoconvertthepointerbacktoitsoriginalvalue. Typicallythisfunctionisusedonlyfordebuginformation.

lua_tostring
[-0,+0,m]

47 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

const char *lua_tostring (lua_State *L, int index); Equivalenttolua_tolstringwithlenequaltoNULL.

lua_tothread
lua_State *lua_tothread (lua_State *L, int index);
[-0,+0,-]

ConvertsthevalueatthegivenacceptableindextoaLuathread(representedaslua_State*). Thisvaluemustbeathread;otherwise,thefunctionreturnsNULL.

lua_touserdata
void *lua_touserdata (lua_State *L, int index);
[-0,+0,-]

Ifthevalueatthegivenacceptableindexisafulluserdata,returnsitsblockaddress.Ifthevalue isalightuserdata,returnsitspointer.Otherwise,returnsNULL.

lua_type
int lua_type (lua_State *L, int index);
[-0,+0,-]

Returnsthetypeofthevalueinthegivenacceptableindex,orLUA_TNONEforanon-validindex (thatis,anindextoan"empty"stackposition).Thetypesreturnedbylua_typearecodedbythe followingconstantsdefinedinlua.h:LUA_TNIL,LUA_TNUMBER,LUA_TBOOLEAN,LUA_TSTRING, LUA_TTABLE,LUA_TFUNCTION,LUA_TUSERDATA,LUA_TTHREAD,andLUA_TLIGHTUSERDATA.

lua_typename
const char *lua_typename (lua_State *L, int tp);
[-0,+0,-]

Returnsthenameofthetypeencodedbythevaluetp,whichmustbeonethevaluesreturnedby lua_type.

lua_Writer
typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud); Thetypeofthewriterfunctionusedbylua_dump.Everytimeitproducesanotherpieceofchunk, lua_dumpcallsthewriter,passingalongthebuffertobewritten(p),itssize(sz),andthedata parametersuppliedtolua_dump.

48 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Thewriterreturnsanerrorcode:0meansnoerrors;anyothervaluemeansanerrorandstops lua_dumpfromcallingthewriteragain.

lua_xmove
void lua_xmove (lua_State *from, lua_State *to, int n); Exchangevaluesbetweendifferentthreadsofthesameglobalstate. Thisfunctionpopsnvaluesfromthestackfrom,andpushesthemontothestackto.
[-?,+?,-]

lua_yield
int lua_yield Yieldsacoroutine. ThisfunctionshouldonlybecalledasthereturnexpressionofaCfunction,asfollows: return lua_yield (L, nresults); WhenaCfunctioncallslua_yieldinthatway,therunningcoroutinesuspendsitsexecution, andthecalltolua_resumethatstartedthiscoroutinereturns.Theparameternresultsisthe numberofvaluesfromthestackthatarepassedasresultstolua_resume. (lua_State *L, int nresults);
[-?,+?,-]

3.8 - The Debug Interface


Luahasnobuilt-indebuggingfacilities.Instead,itoffersaspecialinterfacebymeansoffunctions andhooks.Thisinterfaceallowstheconstructionofdifferentkindsofdebuggers,profilers,and othertoolsthatneed"insideinformation"fromtheinterpreter.

lua_Debug
typedef struct lua_Debug { int event; const char *name; const char *namewhat; const char *what; const char *source; int currentline; int nups; int linedefined; int lastlinedefined; char short_src[LUA_IDSIZE]; /* private part */ other fields

/* /* /* /* /* /* /* /* /*

(n) (n) (S) (S) (l) (u) (S) (S) (S)

*/ */ */ */ */ number of upvalues */ */ */ */

49 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

} lua_Debug; Astructureusedtocarrydifferentpiecesofinformationaboutanactivefunction.lua_getstack fillsonlytheprivatepartofthisstructure,forlateruse.Tofilltheotherfieldsoflua_Debugwith usefulinformation,calllua_getinfo. Thefieldsoflua_Debughavethefollowingmeaning: source:Ifthefunctionwasdefinedinastring,thensourceisthatstring.Ifthefunctionwas definedinafile,thensourcestartswitha'@'followedbythefilename. short_src:a"printable"versionofsource,tobeusedinerrormessages. linedefined:thelinenumberwherethedefinitionofthefunctionstarts. lastlinedefined:thelinenumberwherethedefinitionofthefunctionends. what:thestring"Lua"ifthefunctionisaLuafunction,"C"ifitisaCfunction,"main"ifitis themainpartofachunk,and"tail"ifitwasafunctionthatdidatailcall.Inthelattercase, Luahasnootherinformationaboutthefunction. currentline: the current line where the given function is executing. When no line informationisavailable,currentlineissetto-1. name:areasonablenameforthegivenfunction.BecausefunctionsinLuaarefirst-class values,theydonothaveafixedname:somefunctionscanbethevalueofmultipleglobal variables, while others can be stored only in a table field. The lua_getinfo function checkshowthefunctionwascalledtofindasuitablename.Ifitcannotfindaname,then nameissettoNULL. namewhat:explainsthe namefield.The value ofnamewhatcan be "global","local", "method","field","upvalue",or""(theemptystring),accordingtohow thefunction wascalled.(Luausestheemptystringwhennootheroptionseemstoapply.) nups:thenumberofupvaluesofthefunction.

lua_gethook
lua_Hook lua_gethook (lua_State *L); Returnsthecurrenthookfunction.
[-0,+0,-]

lua_gethookcount
int lua_gethookcount (lua_State *L); Returnsthecurrenthookcount.
[-0,+0,-]

lua_gethookmask
int lua_gethookmask (lua_State *L); Returnsthecurrenthookmask.
[-0,+0,-]

50 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

lua_getinfo
[-(0|1),+(0|1|2),m] int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);

Returnsinformationaboutaspecificfunctionorfunctioninvocation. Togetinformationaboutafunctioninvocation,theparameterarmustbeavalidactivationrecord that was filled by a previous call to lua_getstack or given as argument to a hook (see lua_Hook). Togetinformationaboutafunctionyoupushitontothestackandstartthewhatstringwiththe character'>'.(Inthatcase,lua_getinfopopsthefunctioninthetopofthestack.)Forinstance,to knowinwhichlineafunctionfwasdefined,youcanwritethefollowingcode: lua_Debug ar; lua_getfield(L, LUA_GLOBALSINDEX, "f"); lua_getinfo(L, ">S", &ar); printf("%d\n", ar.linedefined); /* get global 'f' */

Eachcharacterinthestringwhatselectssomefieldsofthestructureartobefilledoravalueto bepushedonthestack: 'n':fillsinthefieldnameandnamewhat; 'S':fillsinthefieldssource,short_src,linedefined,lastlinedefined,andwhat; 'l':fillsinthefieldcurrentline; 'u':fillsinthefieldnups; 'f':pushesontothestackthefunctionthatisrunningatthegivenlevel; 'L':pushesontothestackatablewhoseindicesarethenumbersofthelinesthatarevalid onthefunction.(Avalidlineisalinewithsomeassociatedcode,thatis,alinewhereyou canputabreakpoint.Non-validlinesincludeemptylinesandcomments.) Thisfunctionreturns0onerror(forinstance,aninvalidoptioninwhat).

lua_getlocal
const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);
[-0,+(0|1),-]

Getsinformationaboutalocalvariableofagivenactivationrecord.Theparameterarmustbea validactivationrecordthatwasfilledbyapreviouscalltolua_getstackorgivenasargumentto a hook (see lua_Hook). The index n selects which local variable to inspect (1 is the first parameteroractivelocalvariable,andsoon,untilthelastactivelocalvariable).lua_getlocal pushesthevariable'svalueontothestackandreturnsitsname. Variable namesstarting with '('(open parentheses)representinternal variables(loop control variables,temporaries,andCfunctionlocals). ReturnsNULL(andpushesnothing)whentheindexisgreaterthanthenumberofactivelocal variables.

51 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

lua_getstack
int lua_getstack (lua_State *L, int level, lua_Debug *ar); Getinformationabouttheinterpreterruntimestack. Thisfunctionfillspartsofalua_Debugstructurewithanidentificationoftheactivationrecordof thefunctionexecutingatagivenlevel.Level0isthecurrentrunningfunction,whereasleveln+1 isthefunctionthathascalledleveln.Whentherearenoerrors,lua_getstackreturns1;when calledwithalevelgreaterthanthestackdepth,itreturns0.
[-0,+0,-]

lua_getupvalue
const char *lua_getupvalue (lua_State *L, int funcindex, int n);
[-0,+(0|1),-]

Getsinformationaboutaclosure'supvalue.(ForLuafunctions,upvaluesaretheexternallocal variables that the function uses, and that are consequently included in its closure.) lua_getupvaluegetstheindexnofanupvalue,pushestheupvalue'svalueontothestack,and returnsitsname.funcindexpointsto the closure in the stack.(Upvalueshave no particular order,astheyareactivethroughthewholefunction.So,theyarenumberedinanarbitraryorder.) ReturnsNULL(andpushesnothing)whentheindexisgreaterthanthenumberofupvalues.For Cfunctions,thisfunctionusestheemptystring""asanameforallupvalues.

lua_Hook
typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); Typefordebugginghookfunctions. Whenevera hookiscalled,itsarargumenthasitsfield eventsetto the specificeventthat triggered the hook.Lua identifies these events with the following constants:LUA_HOOKCALL, LUA_HOOKRET, LUA_HOOKTAILRET, LUA_HOOKLINE, and LUA_HOOKCOUNT. Moreover, for line events,thefieldcurrentlineisalsoset.Togetthevalueofanyotherfieldinar,thehookmust call lua_getinfo. For return events, event can be LUA_HOOKRET, the normal value, or LUA_HOOKTAILRET.Inthelattercase,Luaissimulatingareturnfromafunctionthatdidatailcall; inthiscase,itisuselesstocalllua_getinfo. WhileLuaisrunningahook,itdisablesothercallstohooks.Therefore,ifahookcallsbackLuato executeafunctionorachunk,thisexecutionoccurswithoutanycallstohooks.

lua_sethook
int lua_sethook (lua_State *L, lua_Hook f, int mask, int count); Setsthedebugginghookfunction.
[-0,+0,-]

52 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Argumentfisthe hookfunction.maskspecifieson which eventsthe hookwill be called:itis formed by a bitwise or ofthe constants LUA_MASKCALL,LUA_MASKRET,LUA_MASKLINE,and LUA_MASKCOUNT. The count argument is only meaningful when the mask includes LUA_MASKCOUNT.Foreachevent,thehookiscalledasexplainedbelow: Thecallhook:iscalledwhentheinterpretercallsafunction.Thehookiscalledjustafter Luaentersthenewfunction,beforethefunctiongetsitsarguments. Thereturnhook:iscalledwhentheinterpreterreturnsfromafunction.Thehookiscalled justbeforeLualeavesthefunction.Youhavenoaccesstothevaluestobereturnedbythe function. Thelinehook:iscalledwhentheinterpreterisabouttostarttheexecutionofanewlineof code,orwhenitjumpsbackinthecode(eventothesameline).(Thiseventonlyhappens whileLuaisexecutingaLuafunction.) The count hook: is called after the interpreter executes every countinstructions.(This eventonlyhappenswhileLuaisexecutingaLuafunction.) Ahookisdisabledbysettingmasktozero.

lua_setlocal
const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);
[-(0|1),+0,-]

Setsthe value ofa local variable ofa given activation record.Parametersarand nare asin lua_getlocal(seelua_getlocal).lua_setlocalassignsthevalueatthetopofthestackto thevariableandreturnsitsname.Italsopopsthevaluefromthestack. Returns NULL(and pops nothing) when the index is greater than the number ofactive local variables.

lua_setupvalue
const char *lua_setupvalue (lua_State *L, int funcindex, int n);
[-(0|1),+0,-]

Setsthevalueofaclosure'supvalue.Itassignsthevalueatthetopofthestacktotheupvalue andreturnsitsname.Italsopopsthevaluefromthestack.Parametersfuncindexandnareas inthelua_getupvalue(seelua_getupvalue). ReturnsNULL(andpopsnothing)whentheindexisgreaterthanthenumberofupvalues.

4 - The Auxiliary Library


The auxiliarylibraryprovidesseveral convenientfunctionsto interface C with Lua.While the basicAPIprovidestheprimitivefunctionsforallinteractionsbetweenCandLua,theauxiliary libraryprovideshigher-levelfunctionsforsomecommontasks.

53 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Allfunctionsfromtheauxiliarylibraryaredefinedinheaderfilelauxlib.handhaveaprefix luaL_. AllfunctionsintheauxiliarylibraryarebuiltontopofthebasicAPI,andsotheyprovidenothing thatcannotbedonewiththisAPI. SeveralfunctionsintheauxiliarylibraryareusedtocheckCfunctionarguments.Theirnamesare alwaysluaL_check*orluaL_opt*.All ofthese functionsthrow an error ifthe checkisnot satisfied.Becausetheerrormessageisformattedforarguments(e.g.,"bad argument #1"),you shouldnotusethesefunctionsforotherstackvalues.

4.1 - Functions and Types


Herewelistallfunctionsandtypesfromtheauxiliarylibraryinalphabeticalorder.

luaL_addchar
void luaL_addchar (luaL_Buffer *B, char c); AddsthecharacterctothebufferB(seeluaL_Buffer).
[-0,+0,m]

luaL_addlstring
void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);
[-0,+0,m]

AddsthestringpointedtobyswithlengthltothebufferB(seeluaL_Buffer).Thestringmay containembeddedzeros.

luaL_addsize
void luaL_addsize (luaL_Buffer *B, size_t n);
[-0,+0,m]

AddstothebufferB(seeluaL_Buffer)astringoflengthnpreviouslycopiedtothebufferarea (seeluaL_prepbuffer).

luaL_addstring
void luaL_addstring (luaL_Buffer *B, const char *s);
[-0,+0,m]

Addsthezero-terminatedstringpointedtobystothebufferB(seeluaL_Buffer).Thestring maynotcontainembeddedzeros.

luaL_addvalue
[-1,+0,m]

54 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

void luaL_addvalue (luaL_Buffer *B); AddsthevalueatthetopofthestacktothebufferB(seeluaL_Buffer).Popsthevalue. Thisistheonlyfunctiononstringbuffersthatcan(andmust)becalledwithanextraelementon thestack,whichisthevaluetobeaddedtothebuffer.

luaL_argcheck
void luaL_argcheck (lua_State *L, int cond, int narg, const char *extramsg);
[-0,+0,v]

Checkswhethercondistrue.Ifnot,raisesanerrorwiththefollowingmessage,wherefuncis retrievedfromthecallstack: bad argument #<narg> to <func> (<extramsg>)

luaL_argerror
int luaL_argerror (lua_State *L, int narg, const char *extramsg); Raisesanerrorwiththefollowingmessage,wherefuncisretrievedfromthecallstack: bad argument #<narg> to <func> (<extramsg>) This function never returns, but it is an idiom to use it in Cfunctions as return luaL_argerror(args).
[-0,+0,v]

luaL_Buffer
typedef struct luaL_Buffer luaL_Buffer; Typeforastringbuffer. AstringbufferallowsCcodetobuildLuastringspiecemeal.Itspatternofuseisasfollows: FirstyoudeclareavariableboftypeluaL_Buffer. ThenyouinitializeitwithacallluaL_buffinit(L, &b). ThenyouaddstringpiecestothebuffercallinganyoftheluaL_add*functions. YoufinishbycallingluaL_pushresult(&b).Thiscallleavesthefinalstringonthetopof thestack. Duringitsnormaloperation,astringbufferusesavariablenumberofstackslots.So,whileusing abuffer,youcannotassumethatyouknowwherethetopofthestackis.Youcanusethestack betweensuccessivecallstobufferoperationsaslongasthatuseisbalanced;thatis,whenyou callabufferoperation,thestackisatthesamelevelitwasimmediatelyafterthepreviousbuffer

55 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

operation.(TheonlyexceptiontothisruleisluaL_addvalue.)AftercallingluaL_pushresult thestackisbacktoitslevelwhenthebufferwasinitialized,plusthefinalstringonitstop.

luaL_buffinit
void luaL_buffinit (lua_State *L, luaL_Buffer *B);
[-0,+0,-]

InitializesabufferB.Thisfunctiondoesnotallocateanyspace;thebuffermustbedeclaredasa variable(seeluaL_Buffer).

luaL_callmeta
int luaL_callmeta (lua_State *L, int obj, const char *e); Callsametamethod. Iftheobjectatindexobjhasametatableandthismetatablehasafielde,thisfunctioncallsthis fieldandpassestheobjectasitsonlyargument.Inthiscasethisfunctionreturns1andpushes onto the stackthe value returned bythe call.Ifthere isno metatable orno metamethod,this functionreturns0(withoutpushinganyvalueonthestack).
[-0,+(0|1),e]

luaL_checkany
void luaL_checkany (lua_State *L, int narg); Checkswhetherthefunctionhasanargumentofanytype(includingnil)atpositionnarg.
[-0,+0,v]

luaL_checkint
int luaL_checkint (lua_State *L, int narg);
[-0,+0,v]

Checkswhetherthefunctionargumentnargisanumberandreturnsthisnumbercasttoanint.

luaL_checkinteger
lua_Integer luaL_checkinteger (lua_State *L, int narg);
[-0,+0,v]

Checks whether the function argumentnargis a number and returns this number castto a lua_Integer.

luaL_checklong
long luaL_checklong (lua_State *L, int narg);
[-0,+0,v]

56 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Checkswhetherthefunctionargumentnargisanumberandreturnsthisnumbercasttoalong.

luaL_checklstring
const char *luaL_checklstring (lua_State *L, int narg, size_t *l);
[-0,+0,v]

Checkswhetherthefunctionargumentnargisastringandreturnsthisstring;iflisnotNULLfills *lwiththestring'slength. This function uses lua_tolstring to get its result, so all conversions and caveats of that functionapplyhere.

luaL_checknumber
lua_Number luaL_checknumber (lua_State *L, int narg); Checkswhetherthefunctionargumentnargisanumberandreturnsthisnumber.
[-0,+0,v]

luaL_checkoption
int luaL_checkoption (lua_State *L, int narg, const char *def, const char *const lst[]);
[-0,+0,v]

Checkswhetherthefunctionargumentnargisastringandsearchesforthisstringinthearray lst(whichmustbeNULL-terminated).Returnstheindexinthearraywherethestringwasfound. Raisesanerroriftheargumentisnotastringorifthestringcannotbefound. IfdefisnotNULL,thefunctionusesdefasadefaultvaluewhenthereisnoargumentnargorif thisargumentisnil. ThisisausefulfunctionformappingstringstoCenums.(TheusualconventioninLualibrariesis tousestringsinsteadofnumberstoselectoptions.)

luaL_checkstack
void luaL_checkstack (lua_State *L, int sz, const char *msg);
[-0,+0,v]

Growsthestacksizetotop + szelements,raisinganerrorifthestackcannotgrowtothatsize. msgisanadditionaltexttogointotheerrormessage.

luaL_checkstring
const char *luaL_checkstring (lua_State *L, int narg);
[-0,+0,v]

57 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Checkswhetherthefunctionargumentnargisastringandreturnsthisstring. This function uses lua_tolstring to get its result, so all conversions and caveats of that functionapplyhere.

luaL_checktype
void luaL_checktype (lua_State *L, int narg, int t);
[-0,+0,v]

Checkswhetherthefunctionargumentnarghastypet.Seelua_typefortheencodingoftypes fort.

luaL_checkudata
void *luaL_checkudata (lua_State *L, int narg, const char *tname);
[-0,+0,v]

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); Loadsandrunsthegivenfile.Itisdefinedasthefollowingmacro: (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0)) Itreturns0iftherearenoerrorsor1incaseoferrors.
[-0,+?,m]

luaL_dostring
int luaL_dostring (lua_State *L, const char *str); Loadsandrunsthegivenstring.Itisdefinedasthefollowingmacro: (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0)) Itreturns0iftherearenoerrorsor1incaseoferrors.
[-0,+?,m]

luaL_error
int luaL_error (lua_State *L, const char *fmt, ...);
[-0,+0,v]

Raisesanerror.Theerrormessageformatisgivenbyfmtplusanyextraarguments,following thesamerulesoflua_pushfstring.Italsoaddsatthebeginningofthemessagethefilename andthelinenumberwheretheerroroccurred,ifthisinformationisavailable.

58 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

This function never returns, but it is an idiom to use it in Cfunctions as return luaL_error(args).

luaL_getmetafield
int luaL_getmetafield (lua_State *L, int obj, const char *e);
[-0,+(0|1),m]

Pushesontothestackthefieldefromthemetatableoftheobjectatindexobj.Iftheobjectdoes nothaveametatable,orifthemetatabledoesnothavethisfield,returns0andpushesnothing.

luaL_getmetatable
void luaL_getmetatable (lua_State *L, const char *tname);
[-0,+1,-]

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);
[-0,+1,m]

Createsacopyofstringsbyreplacinganyoccurrenceofthestringpwiththestringr.Pushesthe resultingstringonthestackandreturnsit.

luaL_loadbuffer
int luaL_loadbuffer (lua_State *L, const char *buff, size_t sz, const char *name);
[-0,+1,m]

Loadsa bufferasa Lua chunk.Thisfunction useslua_loadto load the chunkin the buffer pointedtobybuffwithsizesz. Thisfunctionreturnsthesameresultsaslua_load.nameisthechunkname,usedfordebug informationanderrormessages.

luaL_loadfile
int luaL_loadfile (lua_State *L, const char *filename);
[-0,+1,m]

LoadsafileasaLuachunk.Thisfunctionuseslua_loadtoloadthechunkinthefilenamed

59 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

filename.IffilenameisNULL,thenitloadsfromthestandardinput.Thefirstlineinthefileis ignoredifitstartswitha#. Thisfunctionreturnsthesameresultsaslua_load,butithasanextraerrorcodeLUA_ERRFILE ifitcannotopen/readthefile. Aslua_load,thisfunctiononlyloadsthechunk;itdoesnotrunit.

luaL_loadstring
int luaL_loadstring (lua_State *L, const char *s);
[-0,+1,m]

Loads a string as a Lua chunk. This function uses lua_load to load the chunk in the zero-terminatedstrings. Thisfunctionreturnsthesameresultsaslua_load. Alsoaslua_load,thisfunctiononlyloadsthechunk;itdoesnotrunit.

luaL_newmetatable
int luaL_newmetatable (lua_State *L, const char *tname);
[-0,+1,m]

Iftheregistryalreadyhasthekeytname,returns0.Otherwise,createsanewtabletobeusedas ametatableforuserdata,addsittotheregistrywithkeytname,andreturns1. Inbothcasespushesontothestackthefinalvalueassociatedwithtnameintheregistry.

luaL_newstate
lua_State *luaL_newstate (void);
[-0,+0,-]

Creates a new Lua state.Itcalls lua_newstatewith an allocator based on the standardC reallocfunctionandthensetsapanicfunction(seelua_atpanic)thatprintsanerrormessage tothestandarderroroutputincaseoffatalerrors. Returnsthenewstate,orNULLifthereisamemoryallocationerror.

luaL_openlibs
void luaL_openlibs (lua_State *L); OpensallstandardLualibrariesintothegivenstate.
[-0,+0,m]

luaL_optint
[-0,+0,v]

60 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

int luaL_optint (lua_State *L, int narg, int d); Ifthefunctionargumentnargisanumber,returnsthisnumbercasttoanint.Ifthisargumentis absentorisnil,returnsd.Otherwise,raisesanerror.

luaL_optinteger
lua_Integer luaL_optinteger (lua_State *L, int narg, lua_Integer d);
[-0,+0,v]

Ifthe function argumentnargisa number,returnsthisnumbercastto a lua_Integer.Ifthis argumentisabsentorisnil,returnsd.Otherwise,raisesanerror.

luaL_optlong
long luaL_optlong (lua_State *L, int narg, long d);
[-0,+0,v]

Ifthefunctionargumentnargisanumber,returnsthisnumbercasttoalong.Ifthisargumentis absentorisnil,returnsd.Otherwise,raisesanerror.

luaL_optlstring
const char *luaL_optlstring (lua_State *L, int narg, const char *d, size_t *l);
[-0,+0,v]

Ifthefunctionargumentnargisastring,returnsthisstring.Ifthisargumentisabsentorisnil, returnsd.Otherwise,raisesanerror. IflisnotNULL,fillstheposition*lwiththeresults'slength.

luaL_optnumber
lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);
[-0,+0,v]

Ifthefunctionargumentnargisanumber,returnsthisnumber.Ifthisargumentisabsentorisnil, returnsd.Otherwise,raisesanerror.

luaL_optstring
const char *luaL_optstring (lua_State *L, int narg, const char *d);
[-0,+0,v]

61 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Ifthefunctionargumentnargisastring,returnsthisstring.Ifthisargumentisabsentorisnil, returnsd.Otherwise,raisesanerror.

luaL_prepbuffer
char *luaL_prepbuffer (luaL_Buffer *B);
[-0,+0,-]

Returnsan addressto a space ofsize LUAL_BUFFERSIZEwhere you can copya string to be added to buffer B(see luaL_Buffer).After copying the string into this space you mustcall luaL_addsizewiththesizeofthestringtoactuallyaddittothebuffer.

luaL_pushresult
void luaL_pushresult (luaL_Buffer *B); FinishestheuseofbufferBleavingthefinalstringonthetopofthestack.
[-?,+1,m]

luaL_ref
int luaL_ref (lua_State *L, int t);
[-1,+0,m]

Createsandreturnsareference,inthetableatindext,fortheobjectatthetopofthestack(and popstheobject). Areferenceisauniqueintegerkey.Aslongasyoudonotmanuallyaddintegerkeysintotablet, luaL_refensurestheuniquenessofthekeyitreturns.Youcanretrieveanobjectreferredby referencerbycallinglua_rawgeti(L, t, r).FunctionluaL_unreffreesareferenceandits associatedobject. Ifthe objectatthe top ofthe stack is nil,luaL_ref returns the constantLUA_REFNIL.The constantLUA_NOREFisguaranteedtobedifferentfromanyreferencereturnedbyluaL_ref.

luaL_Reg
typedef struct luaL_Reg { const char *name; lua_CFunction func; } luaL_Reg; TypeforarraysoffunctionstoberegisteredbyluaL_register.nameisthefunctionnameand funcisapointertothefunction.AnyarrayofluaL_Regmustendwithansentinelentryinwhich bothnameandfuncareNULL.

luaL_register
[-(0|1),+1,m]

62 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

void luaL_register (lua_State *L, const char *libname, const luaL_Reg *l); Opensalibrary. When called with libname equal to NULL,itsimply registers all functions in the listl (see luaL_Reg)intothetableonthetopofthestack. Whencalledwithanon-nulllibname,luaL_registercreatesanewtablet,setsitasthevalue oftheglobalvariablelibname,setsitasthevalueofpackage.loaded[libname],andregisters onitallfunctionsinthelistl.Ifthereisatableinpackage.loaded[libname]orinvariable libname,reusesthistableinsteadofcreatinganewone. Inanycasethefunctionleavesthetableonthetopofthestack.

luaL_typename
const char *luaL_typename (lua_State *L, int index); Returnsthenameofthetypeofthevalueatthegivenindex.
[-0,+0,-]

luaL_typerror
int luaL_typerror (lua_State *L, int narg, const char *tname); Generatesanerrorwithamessagelikethefollowing: location: bad argument narg to 'func' (tname expected, got rt) wherelocationisproducedbyluaL_where,funcisthenameofthecurrentfunction,andrtis thetypenameoftheactualargument.
[-0,+0,v]

luaL_unref
void luaL_unref (lua_State *L, int t, int ref);
[-0,+0,-]

Releasesreferencereffromthetableatindext(seeluaL_ref).Theentryisremovedfromthe table,sothatthereferredobjectcanbecollected.Thereferencerefisalsofreedtobeused again. IfrefisLUA_NOREForLUA_REFNIL,luaL_unrefdoesnothing.

luaL_where
void luaL_where (lua_State *L, int lvl);
[-0,+1,m]

63 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Pushesontothestackastringidentifyingthecurrentpositionofthecontrolatlevellvlinthecall stack.Typicallythisstringhasthefollowingformat: chunkname:currentline: Level0istherunningfunction,level1isthefunctionthatcalledtherunningfunction,etc. Thisfunctionisusedtobuildaprefixforerrormessages.

5 - Standard Libraries
The standard Lua librariesprovide useful functionsthatare implemented directlythrough the CAPI. 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,butare quite useful orhave critical performance requirementsthat deserveanimplementationinC(e.g.,table.sort). AlllibrariesareimplementedthroughtheofficialCAPIandareprovidedasseparateCmodules. Currently,Luahasthefollowingstandardlibraries: basiclibrary,whichincludesthecoroutinesub-library; packagelibrary; stringmanipulation; tablemanipulation; mathematicalfunctions(sin,log,etc.); inputandoutput; operatingsystemfacilities; debugfacilities. Exceptforthebasicandpackagelibraries,eachlibraryprovidesallitsfunctionsasfieldsofa globaltableorasmethodsofitsobjects. Tohaveaccesstotheselibraries,theChostprogramshouldcalltheluaL_openlibsfunction, 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(forthestringlibrary),luaopen_table(forthetablelibrary),luaopen_math (forthe mathematical library),luaopen_io(forthe I/Olibrary),luaopen_os(forthe Operating Systemlibrary),and luaopen_debug(forthe debug library).These functionsare declared in lualib.handshouldnotbecalleddirectly:youmustcallthemlikeanyotherLuaCfunction, e.g.,byusinglua_call.

5.1 - Basic Functions


ThebasiclibraryprovidessomecorefunctionstoLua.Ifyoudonotincludethislibraryinyour application,youshouldcheckcarefullywhetheryouneedtoprovideimplementationsforsomeof

64 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

itsfacilities.

assert (v [, message])
Issuesanerrorwhenthevalueofitsargumentvisfalse(i.e.,nilorfalse);otherwise,returnsallits arguments.messageisanerrormessage;whenabsent,itdefaultsto"assertionfailed!"

collectgarbage ([opt [, arg]])


This function is a generic interface to the garbage collector. It performs different functions accordingtoitsfirstargument,opt: "collect":performsafullgarbage-collectioncycle.Thisisthedefaultoption. "stop":stopsthegarbagecollector. "restart":restartsthegarbagecollector. "count":returnsthetotalmemoryinusebyLua(inKbytes). "step": performs a garbage-collection step.The step "size"is controlled by arg(larger valuesmeanmoresteps)inanon-specifiedway.Ifyouwanttocontrolthestepsizeyou mustexperimentallytune the value ofarg.Returnstrue ifthe step finished a collection cycle. "setpause":setsargasthenewvalueforthepauseofthecollector(see2.10).Returns thepreviousvalueforpause. "setstepmul":setsargasthenewvalueforthestepmultiplierofthecollector(see2.10). Returnsthepreviousvalueforstep.

dofile ([filename])
OpensthenamedfileandexecutesitscontentsasaLuachunk.Whencalledwithoutarguments, dofileexecutesthecontentsofthestandardinput(stdin).Returnsallvaluesreturnedbythe chunk.Incaseoferrors,dofilepropagatestheerrortoitscaller(thatis,dofiledoesnotrunin protectedmode).

error (message [, level])


Terminates the last protected function called and returns message as the error message. Functionerrorneverreturns. Usually,erroraddssomeinformationabouttheerrorpositionatthebeginningofthemessage. Thelevelargumentspecifieshowtogettheerrorposition.Withlevel1(thedefault),theerror positioniswheretheerrorfunctionwascalled.Level2pointstheerrortowherethefunction thatcallederrorwascalled;andsoon.Passingalevel0avoidstheadditionoferrorposition informationtothemessage.

65 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

_G
Aglobalvariable(notafunction)thatholdstheglobalenvironment(thatis,_G._G = _G).Lua itself does not use this variable; changing its value does not affect any environment, nor vice-versa.(Usesetfenvtochangeenvironments.)

getfenv ([f])
Returnsthecurrentenvironmentinusebythefunction.fcanbeaLuafunctionoranumberthat specifies the function atthatstack level:Level1 is the function calling getfenv.Ifthe given functionisnotaLuafunction,oriffis0,getfenvreturnstheglobalenvironment.Thedefaultfor fis1.

getmetatable (object)
Ifobjectdoes nothave a metatable,returns nil.Otherwise,ifthe object's metatable has a "__metatable"field,returnstheassociatedvalue.Otherwise,returnsthemetatableofthegiven object.

ipairs (t)
Returnsthreevalues:aniteratorfunction,thetablet,and0,sothattheconstruction for i,v in ipairs(t) do body end williterateoverthepairs(1,t[1]),(2,t[2]),,uptothefirstintegerkeyabsentfromthetable.

load (func [, chunkname])


Loadsachunkusingfunctionfunctogetitspieces.Eachcalltofuncmustreturnastringthat concatenateswithpreviousresults.Areturnofanemptystring,nil,ornovaluesignalstheendof thechunk. Iftherearenoerrors,returnsthecompiledchunkasafunction;otherwise,returnsnilplusthe errormessage.Theenvironmentofthereturnedfunctionistheglobalenvironment. chunknameisusedasthechunknameforerrormessagesanddebuginformation.Whenabsent, itdefaultsto"=(load)".

loadfile ([filename])
Similartoload,butgetsthechunkfromfilefilenameorfromthestandardinput,ifnofilename isgiven.

66 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

loadstring (string [, chunkname])


Similartoload,butgetsthechunkfromthegivenstring. Toloadandrunagivenstring,usetheidiom assert(loadstring(s))() Whenabsent,chunknamedefaultstothegivenstring.

next (table [, index])


Allowsa programto traverse all fieldsofa table.Itsfirstargumentisa table and itssecond argumentisan indexin thistable.nextreturnsthe nextindexofthe table and itsassociated value. When called with nil as its second argument, next returns an initial index and its associatedvalue.Whencalledwiththelastindex,orwithnilinanemptytable,nextreturnsnil.If thesecondargumentisabsent,thenitisinterpretedasnil.Inparticular,youcanusenext(t)to checkwhetheratableisempty. The orderin which the indicesare enumerated isnotspecified,even fornumericindices.(To traverseatableinnumericorder,useanumericalforortheipairsfunction.) Thebehaviorofnextisundefinedif,duringthetraversal,youassignanyvaluetoanon-existent fieldinthetable.Youmayhowevermodifyexistingfields.Inparticular,youmayclearexisting fields.

pairs (t)
Returnsthreevalues:thenextfunction,thetablet,andnil,sothattheconstruction for k,v in pairs(t) do body end williterateoverallkeyvaluepairsoftablet. Seefunctionnextforthecaveatsofmodifyingthetableduringitstraversal.

pcall (f, arg1, )


Callsfunctionfwiththegivenargumentsinprotectedmode.Thismeansthatanyerrorinsidefis notpropagated;instead,pcallcatchestheerrorandreturnsastatuscode.Itsfirstresultisthe statuscode(aboolean),whichistrueifthecallsucceedswithouterrors.Insuchcase,pcallalso returnsallresultsfromthecall,afterthisfirstresult.Incaseofanyerror,pcallreturnsfalseplus theerrormessage.

print ()

67 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Receives any number ofarguments,and prints their values to stdout,using the tostring functiontoconvertthemtostrings.printisnotintendedforformattedoutput,butonlyasaquick waytoshowavalue,typicallyfordebugging.Forformattedoutput,usestring.format.

rawequal (v1, v2)


Checkswhetherv1isequaltov2,withoutinvokinganymetamethod.Returnsaboolean.

rawget (table, index)


Getstherealvalueoftable[index],withoutinvokinganymetamethod.tablemustbeatable; indexmaybeanyvalue.

rawset (table, index, value)


Setstherealvalueoftable[index]tovalue,withoutinvokinganymetamethod.tablemust beatable,indexanyvaluedifferentfromnil,andvalueanyLuavalue. Thisfunctionreturnstable.

select (index, )
Ifindexisa number,returnsall argumentsafterargumentnumberindex.Otherwise,index mustbethestring"#",andselectreturnsthetotalnumberofextraargumentsitreceived.

setfenv (f, table)


Setstheenvironmenttobeusedbythegivenfunction.fcanbeaLuafunctionoranumberthat specifiesthefunctionatthatstacklevel:Level1isthefunctioncallingsetfenv.setfenvreturns thegivenfunction. Asaspecialcase,whenfis0setfenvchangestheenvironmentoftherunningthread.Inthis case,setfenvreturnsnovalues.

setmetatable (table, metatable)


Setsthemetatableforthegiventable.(YoucannotchangethemetatableofothertypesfromLua, only fromC.) If metatable is nil, removes the metatable of the given table. If the original metatablehasa"__metatable"field,raisesanerror. Thisfunctionreturnstable.

68 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

tonumber (e [, base])
Tries to convertits argumentto a number.Ifthe argumentis already a number or a string convertibletoanumber,thentonumberreturnsthisnumber;otherwise,itreturnsnil. Anoptionalargumentspecifiesthebasetointerpretthenumeral.Thebasemaybeanyinteger between 2 and 36,inclusive.In basesabove10,the letter'A'(in eitherupperorlowercase) represents10,'B'represents11,andsoforth,with'Z'representing35.Inbase10(thedefault),the numbercanhaveadecimalpart,aswellasanoptionalexponentpart(see2.1).Inotherbases, onlyunsignedintegersareaccepted.

tostring (e)
Receivesanargumentofanytypeandconvertsittoastringinareasonableformat.Forcomplete controlofhownumbersareconverted,usestring.format. Ifthemetatableofehasa"__tostring"field,thentostringcallsthecorrespondingvalue witheasargument,andusestheresultofthecallasitsresult.

type (v)
Returnsthetypeofitsonlyargument,codedasastring.Thepossibleresultsofthisfunctionare "nil"(astring,notthevaluenil),"number","string","boolean","table","function","thread", and"userdata".

unpack (list [, i [, j]])


Returnstheelementsfromthegiventable.Thisfunctionisequivalentto return list[i], list[i+1], , list[j] exceptthattheabovecodecanbewrittenonlyforafixednumberofelements.Bydefault,iis1 andjisthelengthofthelist,asdefinedbythelengthoperator(see2.5.5).

_VERSION
Aglobalvariable(notafunction)thatholdsastringcontainingthecurrentinterpreterversion.The currentcontentsofthisvariableis"Lua 5.1".

xpcall (f, err)


Thisfunctionissimilartopcall,exceptthatyoucansetanewerrorhandler. xpcallcallsfunctionfinprotectedmode,usingerrastheerrorhandler.Anyerrorinsidefis

69 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

notpropagated;instead,xpcallcatchestheerror,callstheerrfunctionwiththeoriginalerror object,andreturnsastatuscode.Itsfirstresultisthestatuscode(aboolean),whichistrueifthe callsucceedswithouterrors.Inthiscase,xpcallalsoreturnsallresultsfromthecall,afterthis firstresult.Incaseofanyerror,xpcallreturnsfalseplustheresultfromerr.

5.2 - Coroutine Manipulation


Theoperationsrelatedtocoroutinescompriseasub-libraryofthebasiclibraryandcomeinside thetablecoroutine.See2.11forageneraldescriptionofcoroutines.

coroutine.create (f)
Createsanewcoroutine,withbodyf.fmustbeaLuafunction.Returnsthisnewcoroutine,an objectwithtype"thread".

coroutine.resume (co [, val1, ])


Startsorcontinuestheexecutionofcoroutineco.Thefirsttimeyouresumeacoroutine,itstarts runningitsbody.Thevaluesval1,arepassedastheargumentstothebodyfunction.Ifthe coroutinehasyielded,resumerestartsit;thevaluesval1,arepassedastheresultsfromthe yield. Ifthecoroutinerunswithoutanyerrors,resumereturnstrueplusanyvaluespassedtoyield(if thecoroutineyields)oranyvaluesreturnedbythebodyfunction(ifthecoroutineterminates).If thereisanyerror,resumereturnsfalseplustheerrormessage.

coroutine.running ()
Returnstherunningcoroutine,ornilwhencalledbythemainthread.

coroutine.status (co)
Returnsthestatusofcoroutineco,asastring:"running",ifthecoroutineisrunning(thatis,it calledstatus);"suspended",ifthecoroutineissuspendedinacalltoyield,orifithasnot startedrunningyet;"normal"ifthecoroutineisactivebutnotrunning(thatis,ithasresumed anothercoroutine);and"dead"ifthecoroutinehasfinisheditsbodyfunction,orifithasstopped withanerror.

coroutine.wrap (f)
Createsanewcoroutine,withbodyf.fmustbeaLuafunction.Returnsafunctionthatresumes thecoroutineeachtimeitiscalled.Anyargumentspassedtothefunctionbehaveastheextra

70 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

argumentstoresume.Returnsthesamevaluesreturnedbyresume,exceptthefirstboolean.In caseoferror,propagatestheerror.

coroutine.yield ()
Suspendstheexecutionofthecallingcoroutine.ThecoroutinecannotberunningaCfunction,a metamethod,oraniterator.Anyargumentstoyieldarepassedasextraresultstoresume.

5.3 - Modules
ThepackagelibraryprovidesbasicfacilitiesforloadingandbuildingmodulesinLua.Itexports twoofitsfunctionsdirectlyintheglobalenvironment:requireandmodule.Everythingelseis exportedinatablepackage.

module (name [, ])
Creates a module. If there is a table in package.loaded[name], this table is the module. Otherwise,ifthereisaglobaltabletwiththegivenname,thistableisthemodule.Otherwise creates a new table t and sets it as the value of the global name and the value of package.loaded[name].Thisfunctionalsoinitializest._NAMEwiththegivenname,t._Mwith themodule(titself),andt._PACKAGEwiththepackagename(thefullmodulenameminuslast component;seebelow).Finally,modulesetstasthenewenvironmentofthecurrentfunction andthenewvalueofpackage.loaded[name],sothatrequirereturnst. Ifnameisacompoundname(thatis,onewithcomponentsseparatedbydots),modulecreates (orreuses,iftheyalreadyexist)tablesforeachcomponent.Forinstance,ifnameisa.b.c,then modulestoresthemoduletableinfieldcoffieldbofglobala. Thisfunctioncanreceiveoptionaloptionsafterthemodulename,whereeachoptionisafunction tobeappliedoverthemodule.

require (modname)
Loads the given module. The function starts by looking into the package.loaded table to determinewhethermodnameisalreadyloaded.Ifitis,thenrequirereturnsthevaluestoredat package.loaded[modname].Otherwise,ittriestofindaloaderforthemodule. Tofindaloader,requireisguidedbythepackage.loadersarray.Bychangingthisarray,we canchangehowrequirelooksforamodule.Thefollowingexplanationisbasedonthedefault configurationforpackage.loaders. Firstrequirequeriespackage.preload[modname].Ifithasavalue,thisvalue(whichshould beafunction)istheloader.OtherwiserequiresearchesforaLualoaderusingthepathstored in package.path. If that also fails, it searches for a Cloader using the path stored in

71 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

package.cpath.Ifthatalsofails,ittriesanall-in-oneloader(seepackage.loaders). Oncealoaderisfound,requirecallstheloaderwithasingleargument,modname.Iftheloader returnsanyvalue,requireassignsthe returned value to package.loaded[modname].Ifthe loaderreturnsnovalueandhasnotassignedanyvaluetopackage.loaded[modname],then require assigns true to this entry. In any case, require returns the final value of package.loaded[modname]. Ifthereisanyerrorloadingorrunningthemodule,orifitcannotfindanyloaderforthemodule, thenrequiresignalsanerror.

package.cpath
ThepathusedbyrequiretosearchforaCloader. Lua initializes the Cpath package.cpath in the same way it initializes the Lua path package.path, using the environment variable LUA_CPATH or a default path defined in luaconf.h.

package.loaded
Atable used byrequireto control which modulesare alreadyloaded.When you require a module modname and package.loaded[modname] is not false, require simply returns the valuestoredthere.

package.loaders
Atableusedbyrequiretocontrolhowtoloadmodules. Eachentryinthistableisasearcherfunction.Whenlookingforamodule,requirecallseachof thesesearchersinascendingorder,withthemodulename(theargumentgiventorequire)as its sole parameter.The function can return another function (the module loader) or a string explainingwhyitdidnotfindthatmodule(ornilifithasnothingtosay).Luainitializesthistable withfourfunctions. Thefirstsearchersimplylooksforaloaderinthepackage.preloadtable. ThesecondsearcherlooksforaloaderasaLualibrary,usingthepathstoredatpackage.path. Apathisasequenceoftemplatesseparatedbysemicolons.Foreachtemplate,thesearcherwill changeeachinterrogationmarkinthetemplatebyfilename,whichisthemodulenamewith each dotreplaced bya "directoryseparator"(such as"/"in Unix);then itwill tryto open the resultingfilename.So,forinstance,iftheLuapathisthestring "./?.lua;./?.lc;/usr/local/?/init.lua" the search fora Lua file formodule foowill tryto open the files./foo.lua,./foo.lc,and

72 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

/usr/local/foo/init.lua,inthatorder. The third searcher looks for a loader as a Clibrary, using the path given by the variable package.cpath.Forinstance,iftheCpathisthestring "./?.so;./?.dll;/usr/local/?/init.so" thesearcherformodulefoowilltrytoopenthefiles./foo.so,./foo.dll,and/usr/local /foo/init.so,in thatorder.Once itfindsa Clibrary,thissearcherfirstusesa dynamiclink facilitytolinktheapplicationwiththelibrary.ThenittriestofindaCfunctioninsidethelibraryto beusedastheloader.ThenameofthisCfunctionisthestring"luaopen_"concatenatedwitha copyofthemodulenamewhereeachdotisreplacedbyanunderscore.Moreover,ifthemodule namehasahyphen,itsprefixupto(andincluding)thefirsthyphenisremoved.Forinstance,if themodulenameisa.v1-b.c,thefunctionnamewillbeluaopen_b_c. Thefourthsearchertriesanall-in-oneloader.ItsearchestheCpathforalibraryfortherootname ofthe given module.Forinstance,when requiring a.b.c,itwill search fora Clibraryfora.If found,itlooks into itfor an open function for the submodule;in our example,thatwould be luaopen_a_b_c.With thisfacility,a package can packseveral Csubmodulesinto one single library,witheachsubmodulekeepingitsoriginalopenfunction.

package.loadlib (libname, funcname)


Dynamicallylinksthe hostprogramwith the Clibrarylibname.Inside thislibrary,looksfora function funcnameand returns this function as a Cfunction.(So,funcnamemustfollow the protocol(seelua_CFunction)). This is a low-level function.Itcompletely bypasses the package and module system.Unlike require,itdoesnotperformanypathsearchinganddoesnotautomaticallyaddsextensions. libnamemustbe the complete file name ofthe Clibrary,including ifnecessary a path and extension.funcnamemustbetheexactnameexportedbytheClibrary(whichmaydependon theCcompilerandlinkerused). 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 thatsupportthe dlfcn standard).

package.path
ThepathusedbyrequiretosearchforaLualoader. Atstart-up,LuainitializesthisvariablewiththevalueoftheenvironmentvariableLUA_PATHor withadefaultpathdefinedinluaconf.h,iftheenvironmentvariableisnotdefined.Any";;"in thevalueoftheenvironmentvariableisreplacedbythedefaultpath.

package.preload

73 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Atabletostoreloadersforspecificmodules(seerequire).

package.seeall (module)
Setsametatableformodulewithits__indexfieldreferringtotheglobalenvironment,sothatthis moduleinheritsvaluesfromtheglobalenvironment.Tobeusedasanoptiontofunctionmodule.

5.4 - String Manipulation


Thislibrary provides generic functions for string manipulation,such asfinding and extracting substrings,andpatternmatching.WhenindexingastringinLua,thefirstcharacterisatposition1 (notat0,asinC).Indicesareallowedtobenegativeandareinterpretedasindexingbackwards, fromtheendofthestring.Thus,thelastcharacterisatposition-1,andsoon. Thestringlibraryprovidesallitsfunctionsinsidethetablestring.Italsosetsametatablefor stringswhere the __indexfield pointsto the stringtable.Therefore,you can use the string functions in object-oriented style. For instance, string.byte(s, i) can be written as s:byte(i). Thestringlibraryassumesone-bytecharacterencodings.

string.byte (s [, i [, j]])
Returnstheinternalnumericalcodesofthecharacterss[i],s[i+1],,s[j].Thedefaultvalue foriis1;thedefaultvalueforjisi. Notethatnumericalcodesarenotnecessarilyportableacrossplatforms.

string.char ()
Receiveszeroormoreintegers.Returnsastringwithlengthequaltothenumberofarguments,in whicheachcharacterhastheinternalnumericalcodeequaltoitscorrespondingargument. Notethatnumericalcodesarenotnecessarilyportableacrossplatforms.

string.dump (function)
Returns a string containing a binary representation of the given function, so that a later loadstringon this string returns a copy ofthe function.functionmustbe a Lua function withoutupvalues.

string.find (s, pattern [, init [, plain]])

74 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Looksforthe firstmatch ofpatternin the string s.Ifitfindsa match,then findreturnsthe indices ofswhere this occurrence starts and ends;otherwise,itreturns nil.A third,optional numericalargumentinitspecifieswheretostartthesearch;itsdefaultvalueis1andcanbe negative.Avalue oftrue asa fourth,optional argumentplainturnsoffthe pattern matching facilities,sothefunctiondoesaplain"findsubstring"operation,withnocharactersinpattern beingconsidered"magic".Notethatifplainisgiven,theninitmustbegivenaswell. Ifthepatternhascaptures,theninasuccessfulmatchthecapturedvaluesarealsoreturned,after thetwoindices.

string.format (formatstring, )
Returnsaformattedversionofitsvariablenumberofargumentsfollowingthedescriptiongivenin itsfirstargument(whichmustbeastring).Theformatstringfollowsthesamerulesastheprintf familyofstandardCfunctions.Theonlydifferencesarethattheoptions/modifiers*,l,L,n,p,and harenotsupportedandthatthereisanextraoption,q.Theqoptionformatsastringinaform suitabletobesafelyreadbackbytheLuainterpreter:thestringiswrittenbetweendoublequotes, andalldoublequotes,newlines,embeddedzeros,andbackslashesinthestringarecorrectly escapedwhenwritten.Forinstance,thecall string.format('%q', 'a string with "quotes" and \n new line') willproducethestring: "a string with \"quotes\" and \ new line" Theoptionsc,d,E,e,f,g,G,i,o,u,X,andxallexpectanumberasargument,whereasqands expectastring. Thisfunctiondoesnotacceptstringvaluescontainingembeddedzeros,exceptasargumentsto theqoption.

string.gmatch (s, pattern)


Returnsaniteratorfunctionthat,eachtimeitiscalled,returnsthenextcapturesfrompattern overstrings.Ifpatternspecifiesnocaptures,thenthewholematchisproducedineachcall. Asanexample,thefollowingloop s = "hello world from Lua" for w in string.gmatch(s, "%a+") do print(w) end williterateoverallthewordsfromstrings,printingoneperline.Thenextexamplecollectsall pairskey=valuefromthegivenstringintoatable:

75 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

t = {} s = "from=world, to=Lua" for k, v in string.gmatch(s, "(%w+)=(%w+)") do t[k] = v end Forthisfunction,a'^'atthestartofapatterndoesnotworkasananchor,asthiswouldprevent theiteration.

string.gsub (s, pattern, repl [, n])


Returnsacopyofsinwhichall(orthefirstn,ifgiven)occurrencesofthepatternhavebeen replacedbyareplacementstringspecifiedbyrepl,whichcanbeastring,atable,orafunction. gsubalsoreturns,asitssecondvalue,thetotalnumberofmatchesthatoccurred. Ifreplisastring,thenitsvalueisusedforreplacement.Thecharacter%worksasanescape character:anysequenceinreploftheform%n,withnbetween1and9,standsforthevalueof the n-th captured substring (see below).The sequence %0stands for the whole match.The sequence%%standsforasingle%. Ifreplisatable,thenthetableisqueriedforeverymatch,usingthefirstcaptureasthekey;ifthe patternspecifiesnocaptures,thenthewholematchisusedasthekey. Ifreplisa function,then thisfunction iscalled everytime a match occurs,with all captured substringspassed asarguments,in order;ifthe pattern specifiesno captures,then the whole matchispassedasasoleargument. Ifthevaluereturnedbythetablequeryorbythefunctioncallisastringoranumber,thenitis usedasthereplacementstring;otherwise,ifitisfalseornil,thenthereisnoreplacement(thatis, theoriginalmatchiskeptinthestring). Herearesomeexamples: 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"

76 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

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)
Receivesastringandreturnsitslength.Theemptystring""haslength0.Embeddedzerosare counted,so"a\000bc\000"haslength5.

string.lower (s)
Receives a string and returns a copy of this string with all uppercase letters changed to lowercase.Allothercharactersareleftunchanged.Thedefinitionofwhatanuppercaseletteris dependsonthecurrentlocale.

string.match (s, pattern [, init])


Looksforthefirstmatchofpatterninthestrings.Ifitfindsone,thenmatchreturnsthecaptures fromthepattern;otherwiseitreturnsnil.Ifpatternspecifiesnocaptures,thenthewholematchis returned.Athird,optionalnumericalargumentinitspecifieswheretostartthesearch;itsdefault valueis1andcanbenegative.

string.rep (s, n)
Returnsastringthatistheconcatenationofncopiesofthestrings.

string.reverse (s)
Returnsastringthatisthestringsreversed.

string.sub (s, i [, j])


Returnsthesubstringofsthatstartsatiandcontinuesuntilj;iandjcanbenegative.Ifjis absent,thenitisassumedtobeequalto-1(whichisthesameasthestringlength).Inparticular, the call string.sub(s,1,j) returns a prefix ofs with length j,and string.sub(s, -i) returnsasuffixofswithlengthi.

string.upper (s)
Receives a string and returns a copy of this string with all lowercase letters changed to uppercase.Allothercharactersareleftunchanged.Thedefinitionofwhatalowercaseletteris

77 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

dependsonthecurrentlocale.

5.4.1 - Patterns
Character Class: A character class is used to represent a set of characters. The following combinations are allowedindescribingacharacterclass: x:(wherexisnotoneofthemagiccharacters^$()%.[]*+-?)representsthecharacterx itself. .:(adot)representsallcharacters. %a:representsallletters. %c:representsallcontrolcharacters. %d:representsalldigits. %l:representsalllowercaseletters. %p:representsallpunctuationcharacters. %s:representsallspacecharacters. %u:representsalluppercaseletters. %w:representsallalphanumericcharacters. %x:representsallhexadecimaldigits. %z:representsthecharacterwithrepresentation0. %x:(where xisanynon-alphanumericcharacter)representsthe characterx.Thisisthe standard wayto escape the magiccharacters.Anypunctuation character(even the non magic)canbeprecededbya'%'whenusedtorepresentitselfinapattern. [set]:representstheclasswhichistheunionofallcharactersinset.Arangeofcharacters can be specified byseparating the end charactersofthe range with a '-'.All classes%x described above can also be used as components in set. All other characters in set represent themselves. For example, [%w_] (or [_%w]) represents all alphanumeric characters plus the underscore, [0-7] represents the octal digits, and [0-7%l%-] representstheoctaldigitsplusthelowercaselettersplusthe'-'character. Theinteractionbetweenrangesandclassesisnotdefined.Therefore,patternslike[%a-z] or[a-%%]havenomeaning. [^set]:representsthecomplementofset,wheresetisinterpretedasabove. Forall classesrepresented bysingle letters(%a,%c,etc.),the corresponding uppercase letter representsthecomplementoftheclass.Forinstance,%Srepresentsallnon-spacecharacters. The definitions ofletter,space,and other character groups depend on the currentlocale.In particular,theclass[a-z]maynotbeequivalentto%l. Pattern Item: Apatternitemcanbe asinglecharacterclass,whichmatchesanysinglecharacterintheclass;

78 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

asinglecharacterclassfollowedby'*',whichmatches0ormorerepetitionsofcharactersin theclass.Theserepetitionitemswillalwaysmatchthelongestpossiblesequence; asinglecharacterclassfollowedby'+',whichmatches1ormorerepetitionsofcharactersin theclass.Theserepetitionitemswillalwaysmatchthelongestpossiblesequence; a single character class followed by '-', which also matches 0 or more repetitions of characters in the class.Unlike '*',these repetition items will always match the shortest possiblesequence; asinglecharacterclassfollowedby'?',whichmatches0or1occurrenceofacharacterin theclass; %n,fornbetween1and9;suchitemmatchesasubstringequaltothen-thcapturedstring (seebelow); %bxy,wherexandyaretwodistinctcharacters;suchitemmatchesstringsthatstartwithx, endwithy,andwherethexandyarebalanced.Thismeansthat,ifonereadsthestring fromlefttoright,counting+1foranxand-1foray,theendingyisthefirstywherethecount reaches0.Forinstance,theitem%b()matchesexpressionswithbalancedparentheses. Pattern: Apatternisasequenceofpatternitems.A'^'atthebeginningofapatternanchorsthematchat thebeginningofthesubjectstring.A'$'attheendofapatternanchorsthematchattheendofthe subjectstring.Atotherpositions,'^'and'$'havenospecialmeaningandrepresentthemselves. Captures: Apattern can contain sub-patternsenclosed in parentheses;theydescribe captures.When a matchsucceeds,thesubstringsofthesubjectstringthatmatchcapturesarestored(captured)for future use. Captures are numbered according to their left parentheses. For instance, in the pattern "(a*(.)%w(%s*))",the partofthe string matching "a*(.)%w(%s*)"isstored asthe firstcapture(andthereforehasnumber1);thecharactermatching"."iscapturedwithnumber2, andthepartmatching"%s*"hasnumber3. Asa special case,the emptycapture ()capturesthe currentstring position (a number).For instance,ifweapplythepattern"()aa()"onthestring"flaaap",therewillbetwocaptures: 3and5. Apatterncannotcontainembeddedzeros.Use%zinstead.

5.5 - Table Manipulation


Thislibraryprovidesgenericfunctionsfortablemanipulation.Itprovidesallitsfunctionsinside thetabletable. Mostfunctionsinthetablelibraryassumethatthetablerepresentsanarrayoralist.Forthese functions,whenwetalkaboutthe"length"ofatablewemeantheresultofthelengthoperator.

79 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

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].Thedefaultvalueforsepistheempty string,thedefaultforiis1,andthedefaultforjisthelengthofthetable.Ifiisgreaterthanj, returnstheemptystring.

table.insert (table, [pos,] value)


Insertselementvalueatposition posin table,shifting up otherelementsto open space,if necessary.Thedefaultvalueforposisn+1,wherenisthelengthofthetable(see2.5.5),sothat acalltable.insert(t,x)insertsxattheendoftablet.

table.maxn (table)
Returnsthelargestpositivenumericalindexofthegiventable,orzeroifthetablehasnopositive numericalindices.(Todoitsjobthisfunctiondoesalineartraversalofthewholetable.)

table.remove (table [, pos])


Removesfromtablethe elementatposition pos,shifting down otherelementsto close the space,ifnecessary.Returnsthevalueoftheremovedelement.Thedefaultvalueforposisn, wherenisthelengthofthetable,sothatacalltable.remove(t)removesthelastelementof tablet.

table.sort (table [, comp])


Sortstable elementsin a given order,in-place,fromtable[1]to table[n],where nisthe lengthofthetable.Ifcompisgiven,thenitmustbeafunctionthatreceivestwotableelements, andreturnstruewhenthefirstislessthanthesecond(sothatnot comp(a[i+1],a[i])willbe trueafterthesort).Ifcompisnotgiven,thenthestandardLuaoperator<isusedinstead. Thesortalgorithmisnotstable;thatis,elementsconsideredequalbythegivenordermayhave theirrelativepositionschangedbythesort.

5.6 - Mathematical Functions


ThislibraryisaninterfacetothestandardCmathlibrary.Itprovidesallitsfunctionsinsidethe tablemath.

math.abs (x)

80 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Returnstheabsolutevalueofx.

math.acos (x)
Returnsthearccosineofx(inradians).

math.asin (x)
Returnsthearcsineofx(inradians).

math.atan (x)
Returnsthearctangentofx(inradians).

math.atan2 (y, x)
Returnsthe arctangentofy/x(in radians),butusesthe signsofboth parametersto find the quadrantoftheresult.(Italsohandlescorrectlythecaseofxbeingzero.)

math.ceil (x)
Returnsthesmallestintegerlargerthanorequaltox.

math.cos (x)
Returnsthecosineofx(assumedtobeinradians).

math.cosh (x)
Returnsthehyperboliccosineofx.

math.deg (x)
Returnstheanglex(giveninradians)indegrees.

math.exp (x)
Returnsthevaluee .
x

81 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

math.floor (x)
Returnsthelargestintegersmallerthanorequaltox.

math.fmod (x, y)
Returnstheremainderofthedivisionofxbyythatroundsthequotienttowardszero.

math.frexp (x)
Returnsmandesuchthatx=m2 ,eisanintegerandtheabsolutevalueofmisintherange[0.5, 1)(orzerowhenxiszero).
e

math.huge
ThevalueHUGE_VAL,avaluelargerthanorequaltoanyothernumericalvalue.

math.ldexp (m, e)
Returnsm2 (eshouldbeaninteger).
e

math.log (x)
Returnsthenaturallogarithmofx.

math.log10 (x)
Returnsthebase-10logarithmofx.

math.max (x, )
Returnsthemaximumvalueamongitsarguments.

math.min (x, )
Returnstheminimumvalueamongitsarguments.

math.modf (x)
Returnstwonumbers,theintegralpartofxandthefractionalpartofx.

82 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

math.pi
Thevalueofpi.

math.pow (x, y)
Returnsx .(Youcanalsousetheexpressionx^ytocomputethisvalue.)
y

math.rad (x)
Returnstheanglex(givenindegrees)inradians.

math.random ([m [, n]])


Thisfunctionisaninterfacetothesimplepseudo-randomgeneratorfunctionrandprovidedby ANSIC.(Noguaranteescanbegivenforitsstatisticalproperties.) Whencalledwithoutarguments,returnsauniformpseudo-randomrealnumberintherange[0,1). Whencalledwithanintegernumberm,math.randomreturnsauniformpseudo-randominteger in the range [1,m].When called with two integer numbers mand n,math.randomreturns a uniformpseudo-randomintegerintherange[m,n].

math.randomseed (x)
Setsxasthe"seed"forthepseudo-randomgenerator:equalseedsproduceequalsequencesof numbers.

math.sin (x)
Returnsthesineofx(assumedtobeinradians).

math.sinh (x)
Returnsthehyperbolicsineofx.

math.sqrt (x)
Returnsthesquarerootofx.(Youcanalsousetheexpressionx^0.5tocomputethisvalue.)

math.tan (x)
83 of 96 05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Returnsthetangentofx(assumedtobeinradians).

math.tanh (x)
Returnsthehyperbolictangentofx.

5.7 - Input and Output Facilities


TheI/Olibraryprovidestwodifferentstylesforfilemanipulation.Thefirstoneusesimplicitfile descriptors;thatis,thereareoperationstosetadefaultinputfileandadefaultoutputfile,andall input/outputoperationsareoverthesedefaultfiles.Thesecondstyleusesexplicitfiledescriptors. Whenusingimplicitfiledescriptors,alloperationsaresuppliedbytableio.Whenusingexplicit file descriptors, the operation io.open returns a file descriptor and then all operations are suppliedasmethodsofthefiledescriptor. ThetableioalsoprovidesthreepredefinedfiledescriptorswiththeirusualmeaningsfromC: io.stdin,io.stdout,andio.stderr.TheI/Olibraryneverclosesthesefiles. Unlessotherwisestated,allI/Ofunctionsreturnnilonfailure(plusanerrormessageasasecond resultandasystem-dependenterrorcodeasathirdresult)andsomevaluedifferentfromnilon success.

io.close ([file])
Equivalenttofile:close().Withoutafile,closesthedefaultoutputfile.

io.flush ()
Equivalenttofile:flushoverthedefaultoutputfile.

io.input ([file])
Whencalledwithafilename,itopensthenamedfile(intextmode),andsetsitshandleasthe defaultinputfile.Whencalledwithafilehandle,itsimplysetsthisfilehandleasthedefaultinput file.Whencalledwithoutparameters,itreturnsthecurrentdefaultinputfile. Incaseoferrorsthisfunctionraisestheerror,insteadofreturninganerrorcode.

io.lines ([filename])
Opensthe given file name in read mode and returnsan iteratorfunction that,each time itis called,returnsanewlinefromthefile.Therefore,theconstruction

84 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

for line in io.lines(filename) do body end williterateoveralllinesofthefile.Whentheiteratorfunctiondetectstheendoffile,itreturnsnil (tofinishtheloop)andautomaticallyclosesthefile. Thecallio.lines()(withnofilename)isequivalenttoio.input():lines();thatis,ititerates overthelinesofthedefaultinputfile.Inthiscaseitdoesnotclosethefilewhentheloopends.

io.open (filename [, mode])


Thisfunctionopensafile,inthemodespecifiedinthestringmode.Itreturnsanewfilehandle,or, incaseoferrors,nilplusanerrormessage. Themodestringcanbeanyofthefollowing: "r":readmode(thedefault); "w":writemode; "a":appendmode; "r+":updatemode,allpreviousdataispreserved; "w+":updatemode,allpreviousdataiserased; "a+":appendupdatemode,previousdataispreserved,writingisonlyallowedattheendof file. Themodestringcanalsohavea'b'attheend,whichisneededinsomesystemstoopenthefile inbinarymode.ThisstringisexactlywhatisusedinthestandardCfunctionfopen.

io.output ([file])
Similartoio.input,butoperatesoverthedefaultoutputfile.

io.popen (prog [, mode])


Startsprogramproginaseparatedprocessandreturnsafilehandlethatyoucanusetoread datafromthisprogram(ifmodeis"r",thedefault)ortowritedatatothisprogram(ifmodeis"w"). Thisfunctionissystemdependentandisnotavailableonallplatforms.

io.read ()
Equivalenttoio.input():read.

io.tmpfile ()
Returnsahandleforatemporaryfile.Thisfileisopenedinupdatemodeanditisautomatically removedwhentheprogramends.
85 of 96 05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

io.type (obj)
Checkswhetherobjisavalidfilehandle.Returnsthestring"file"ifobjisanopenfilehandle, "closed file"ifobjisaclosedfilehandle,ornilifobjisnotafilehandle.

io.write ()
Equivalenttoio.output():write.

file:close ()
Closesfile.Notethatfilesareautomaticallyclosedwhentheirhandlesaregarbagecollected, butthattakesanunpredictableamountoftimetohappen.

file:flush ()
Savesanywrittendatatofile.

file:lines ()
Returnsaniteratorfunctionthat,eachtimeitiscalled,returnsanewlinefromthefile.Therefore, theconstruction for line in file:lines() do body end williterateoveralllinesofthefile.(Unlikeio.lines,thisfunctiondoesnotclosethefilewhen theloopends.)

file:read ()
Readsthefilefile,accordingtothegivenformats,whichspecifywhattoread.Foreachformat, thefunctionreturnsastring(oranumber)withthecharactersread,ornilifitcannotreaddata with the specified format.When called withoutformats,itusesa defaultformatthatreadsthe entirenextline(seebelow). Theavailableformatsare "*n":readsanumber;thisistheonlyformatthatreturnsanumberinsteadofastring. "*a":readsthewholefile,startingatthecurrentposition.Onendoffile,itreturnstheempty string. "*l":readsthenextline(skippingtheendofline),returningnilonendoffile.Thisisthe defaultformat. number:readsastringwithuptothisnumberofcharacters,returningnilonendoffile.If

86 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

numberiszero,itreadsnothingandreturnsanemptystring,ornilonendoffile.

file:seek ([whence] [, offset])


Setsandgetsthefileposition,measuredfromthebeginningofthefile,tothepositiongivenby offsetplusabasespecifiedbythestringwhence,asfollows: "set":baseisposition0(beginningofthefile); "cur":baseiscurrentposition; "end":baseisendoffile; In case ofsuccess,function seek returns the final file position,measured in bytes from the beginningofthefile.Ifthisfunctionfails,itreturnsnil,plusastringdescribingtheerror. Thedefaultvalueforwhenceis"cur",andforoffsetis0.Therefore,thecall file:seek() returnsthecurrentfileposition,withoutchangingit;thecallfile:seek("set")setstheposition tothebeginningofthefile(andreturns0);andthecallfile:seek("end")setsthepositionto theendofthefile,andreturnsitssize.

file:setvbuf (mode [, size])


Setsthebufferingmodeforanoutputfile.Therearethreeavailablemodes: "no":nobuffering;theresultofanyoutputoperationappearsimmediately. "full":fullbuffering;outputoperationisperformedonlywhenthebufferisfull(orwhenyou explicitlyflushthefile(seeio.flush)). "line":linebuffering;outputisbuffereduntilanewlineisoutputorthereisanyinputfrom somespecialfiles(suchasaterminaldevice). Forthelasttwocases,sizespecifiesthesizeofthebuffer,inbytes.Thedefaultisanappropriate size.

file:write ()
Writesthevalueofeachofitsargumentstothefile.Theargumentsmustbestringsornumbers. Towriteothervalues,usetostringorstring.formatbeforewrite.

5.8 - Operating System Facilities


Thislibraryisimplementedthroughtableos.

os.clock ()
ReturnsanapproximationoftheamountinsecondsofCPUtimeusedbytheprogram.

87 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

os.date ([format [, time]])


Returns a string or a table containing date and time,formatted according to the given string format. Ifthetimeargumentispresent,thisisthetimetobeformatted(seetheos.timefunctionfora descriptionofthisvalue).Otherwise,dateformatsthecurrenttime. Ifformatstarts with '!',then the date is formatted in Coordinated Universal Time.After this optionalcharacter,ifformatisthestring"*t",thendatereturnsatablewiththefollowingfields: year (four digits), month (1--12), day (1--31), hour (0--23), min (0--59), sec (0--61), wday (weekday,Sundayis1),yday(dayoftheyear),andisdst(daylightsavingflag,aboolean). Ifformatisnot"*t",thendatereturnsthedateasastring,formattedaccordingtothesamerules astheCfunctionstrftime. When called withoutarguments,datereturnsa reasonable date and time representation that depends on the hostsystem and on the currentlocale (thatis,os.date() is equivalentto os.date("%c")).

os.difftime (t2, t1)


Returnsthe numberofsecondsfromtime t1to time t2.In POSIX,Windows,and some other systems,thisvalueisexactlyt2-t1.

os.execute ([command])
Thisfunction isequivalentto the Cfunction system.Itpassescommandto be executed byan operatingsystemshell.Itreturnsastatuscode,whichissystem-dependent.Ifcommandisabsent, thenitreturnsnonzeroifashellisavailableandzerootherwise.

os.exit ([code])
CallstheCfunctionexit,withanoptionalcode,toterminatethehostprogram.Thedefaultvalue forcodeisthesuccesscode.

os.getenv (varname)
Returns the value ofthe process environmentvariable varname,or nilifthe variable is not defined.

os.remove (filename)

88 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Deletesthefileordirectorywiththegivenname.Directoriesmustbeemptytoberemoved.Ifthis functionfails,itreturnsnil,plusastringdescribingtheerror.

os.rename (oldname, newname)


Renamesfileordirectorynamedoldnametonewname.Ifthisfunctionfails,itreturnsnil,plusa stringdescribingtheerror.

os.setlocale (locale [, category])


Setsthecurrentlocaleoftheprogram.localeisastringspecifyingalocale;categoryisan optionalstringdescribingwhichcategorytochange:"all","collate","ctype","monetary", "numeric",or"time";thedefaultcategoryis"all".Thefunctionreturnsthenameofthenew locale,orniliftherequestcannotbehonored. Iflocaleistheemptystring,thecurrentlocaleissettoanimplementation-definednativelocale. Iflocaleisthestring"C",thecurrentlocaleissettothestandardClocale. Whencalledwithnilasthefirstargument,thisfunctiononlyreturnsthenameofthecurrentlocale forthegivencategory.

os.time ([table])
Returnsthecurrenttimewhencalledwithoutarguments,oratimerepresentingthedateandtime specifiedbythegiventable.Thistablemusthavefieldsyear,month,andday,andmayhave fieldshour,min,sec,andisdst(foradescriptionofthesefields,seetheos.datefunction). Thereturnedvalueisanumber,whosemeaningdependsonyoursystem.InPOSIX,Windows, andsomeothersystems,thisnumbercountsthenumberofsecondssincesomegivenstarttime (the"epoch").Inothersystems,themeaningisnotspecified,andthenumberreturnedbytime canbeusedonlyasanargumenttodateanddifftime.

os.tmpname ()
Returnsastringwithafilenamethatcanbeusedforatemporaryfile.Thefilemustbeexplicitly openedbeforeitsuseandexplicitlyremovedwhennolongerneeded. Onsomesystems(POSIX),thisfunctionalsocreatesafilewiththatname,toavoidsecurityrisks. (Someoneelsemightcreatethefilewithwrongpermissionsinthetimebetweengettingthename andcreatingthefile.)Youstillhavetoopenthefiletouseitandtoremoveit(evenifyoudonot useit). Whenpossible,youmayprefertouseio.tmpfile,whichautomaticallyremovesthefilewhen theprogramends.

89 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

5.9 - The Debug Library


ThislibraryprovidesthefunctionalityofthedebuginterfacetoLuaprograms.Youshouldexert care when using this library. The functions provided here should be used exclusively for debugging and similartasks,such asprofiling.Please resistthe temptation to use themasa usualprogrammingtool:theycanbeveryslow.Moreover,severalofthesefunctionsviolatesome assumptionsaboutLua code (e.g.,thatvariableslocal to a function cannotbe accessed from outside or that userdata metatables cannot be changed by Lua code) and therefore can compromiseotherwisesecurecode. Allfunctionsinthislibraryareprovidedinsidethedebugtable.Allfunctionsthatoperateovera threadhaveanoptionalfirstargumentwhichisthethreadtooperateover.Thedefaultisalways thecurrentthread.

debug.debug ()
Entersaninteractivemodewiththeuser,runningeachstringthattheuserenters.Usingsimple commandsandotherdebugfacilities,theusercaninspectglobalandlocalvariables,change theirvalues,evaluateexpressions,andsoon.Alinecontainingonlythewordcontfinishesthis function,sothatthecallercontinuesitsexecution. Notethatcommandsfordebug.debugarenotlexicallynestedwithinanyfunction,andsohave nodirectaccesstolocalvariables.

debug.getfenv (o)
Returnstheenvironmentofobjecto.

debug.gethook ([thread])
Returnsthecurrenthooksettingsofthethread,asthreevalues:thecurrenthookfunction,the currenthookmask,andthecurrenthookcount(assetbythedebug.sethookfunction).

debug.getinfo ([thread,] function [, what])


Returnsatablewithinformationaboutafunction.Youcangivethefunctiondirectly,oryoucan giveanumberasthevalueoffunction,whichmeansthefunctionrunningatlevelfunctionof the call stackofthe given thread:level0 isthe currentfunction (getinfoitself);level1 isthe function thatcalled getinfo;and so on.Iffunctionisa numberlargerthan the numberof activefunctions,thengetinforeturnsnil. The returned table can contain all the fields returned by lua_getinfo,with the string what describingwhichfieldstofillin.Thedefaultforwhatistogetallinformationavailable,exceptthe

90 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

tableofvalidlines.Ifpresent,theoption'f'addsafieldnamedfuncwiththefunctionitself.If present,theoption'L'addsafieldnamedactivelineswiththetableofvalidlines. Forinstance,theexpressiondebug.getinfo(1,"n").namereturnsatablewithanameforthe current function, if a reasonable name can be found, and the expression debug.getinfo(print)returnsatablewithallavailableinformationabouttheprintfunction.

debug.getlocal ([thread,] level, local)


Thisfunctionreturnsthenameandthevalueofthelocalvariablewithindexlocalofthefunction atlevellevelofthestack.(Thefirstparameterorlocalvariablehasindex1,andsoon,untilthe lastactivelocalvariable.)Thefunctionreturnsnilifthereisnolocalvariablewiththegivenindex, and raisesan errorwhen called with a leveloutofrange.(You can call debug.getinfoto checkwhetherthelevelisvalid.) Variable namesstarting with '('(open parentheses)representinternal variables(loop control variables,temporaries,andCfunctionlocals).

debug.getmetatable (object)
Returnsthemetatableofthegivenobjectornilifitdoesnothaveametatable.

debug.getregistry ()
Returnstheregistrytable(see3.5).

debug.getupvalue (func, up)


Thisfunctionreturnsthenameandthevalueoftheupvaluewithindexupofthefunctionfunc. Thefunctionreturnsnilifthereisnoupvaluewiththegivenindex.

debug.setfenv (object, table)


Setstheenvironmentofthegivenobjecttothegiventable.Returnsobject.

debug.sethook ([thread,] hook, mask [, count])


Setsthegivenfunctionasahook.Thestringmaskandthenumbercountdescribewhenthe hookwillbecalled.Thestringmaskmayhavethefollowingcharacters,withthegivenmeaning: "c":thehookiscalledeverytimeLuacallsafunction; "r":thehookiscalledeverytimeLuareturnsfromafunction; "l":thehookiscalledeverytimeLuaentersanewlineofcode.

91 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

Withacountdifferentfromzero,thehookiscalledaftereverycountinstructions. Whencalledwithoutarguments,debug.sethookturnsoffthehook. Whenthehookiscalled,itsfirstparameterisastringdescribingtheeventthathastriggeredits call:"call","return"(or"tail return",whensimulatingareturnfromatailcall),"line", and"count".Forlineevents,thehookalsogetsthenewlinenumberasitssecondparameter. Inside a hook,you can call getinfowith level2 to getmore information aboutthe running function(level0isthegetinfofunction,andlevel1isthehookfunction),unlesstheeventis "tail return".Inthiscase,Luaisonlysimulatingthereturn,andacalltogetinfowillreturn invaliddata.

debug.setlocal ([thread,] level, local, value)


Thisfunctionassignsthevaluevaluetothelocalvariablewithindexlocalofthefunctionat levellevelofthestack.Thefunctionreturnsnilifthereisnolocalvariablewiththegivenindex, and raisesan errorwhen called with a leveloutofrange.(You can call getinfoto check whetherthelevelisvalid.)Otherwise,itreturnsthenameofthelocalvariable.

debug.setmetatable (object, table)


Setsthemetatableforthegivenobjecttothegiventable(whichcanbenil).

debug.setupvalue (func, up, value)


Thisfunction assignsthe value valueto the upvalue with indexupofthe function func.The functionreturnsnilifthereisnoupvaluewiththegivenindex.Otherwise,itreturnsthenameof theupvalue.

debug.traceback ([thread,] [message [, level]])


Returnsastringwithatracebackofthecallstack.Anoptionalmessagestringisappendedatthe beginningofthetraceback.Anoptionallevelnumbertellsatwhichleveltostartthetraceback (defaultis1,thefunctioncallingtraceback).

6 - Lua Stand-alone
Although Lua has been designed as an extension language, to be embedded in a host Cprogram,itisalso frequently used asa stand-alone language.An interpreterfor Lua asa stand-alone language, called simply lua, is provided with the standard distribution. The stand-aloneinterpreterincludesallstandardlibraries,includingthedebuglibrary.Itsusageis:

92 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

lua [options] [script [args]] Theoptionsare: -e stat:executesstringstat; -l mod:"requires"mod; -i:entersinteractivemodeafterrunningscript; -v:printsversioninformation; --:stopshandlingoptions; -:executesstdinasafileandstopshandlingoptions. After handling its options, lua runs the given script, passing to it the given args as string arguments.When called withoutarguments,luabehavesaslua -v -iwhen the standard input(stdin)isaterminal,andaslua -otherwise. Beforerunninganyargument,theinterpreterchecksforanenvironmentvariableLUA_INIT.Ifits formatis@filename,thenluaexecutesthefile.Otherwise,luaexecutesthestringitself. Alloptionsarehandledinorder,except-i.Forinstance,aninvocationlike $ lua -e'a=1' -e 'print(a)' script.lua willfirstsetato1,thenprintthevalueofa(whichis'1'),andfinallyrunthefilescript.luawith noarguments.(Here$istheshellprompt.Yourpromptmaybedifferent.) Beforestartingtorunthescript,luacollectsallargumentsinthecommandlineinaglobaltable calledarg.Thescriptnameisstoredatindex0,thefirstargumentafterthescriptnamegoesto index1,andsoon.Anyargumentsbeforethescriptname(thatis,theinterpreternameplusthe options)gotonegativeindices.Forinstance,inthecall $ lua -la b.lua t1 t2 theinterpreterfirstrunsthefilea.lua,thencreatesatable arg = { [-2] = "lua", [-1] = "-la", [0] = "b.lua", [1] = "t1", [2] = "t2" } andfinallyrunsthefileb.lua.Thescriptiscalledwitharg[1],arg[2],asarguments;itcan alsoaccesstheseargumentswiththevarargexpression'...'. Ininteractivemode,ifyouwriteanincompletestatement,theinterpreterwaitsforitscompletion byissuingadifferentprompt. Iftheglobalvariable_PROMPTcontainsastring,thenitsvalueisusedastheprompt.Similarly,if theglobalvariable_PROMPT2containsastring,itsvalueisusedasthesecondaryprompt(issued during incomplete statements). Therefore, both prompts can be changed directly on the commandlineorinanyLuaprogramsbyassigningto_PROMPT.Seethenextexample: $ lua -e"_PROMPT='myprompt> '" -i

93 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

(Theouterpairofquotesisfortheshell,theinnerpairisforLua.)Notetheuseof-itoenter interactive mode;otherwise,the programwould justend silentlyrightafterthe assignmentto _PROMPT. ToallowtheuseofLuaasascriptinterpreterinUnixsystems,thestand-aloneinterpreterskips the firstline ofa chunkifitstartswith #.Therefore,Lua scriptscan be made into executable programsbyusingchmod +xandthe#!form,asin #!/usr/local/bin/lua (Ofcourse,thelocationoftheLuainterpretermaybedifferentinyourmachine.Ifluaisinyour PATH,then #!/usr/bin/env lua isamoreportablesolution.)

7 - Incompatibilities with the Previous Version


Here we listthe incompatibilities thatyou may find when moving a program from Lua5.0 to Lua5.1.YoucanavoidmostoftheincompatibilitiescompilingLuawithappropriateoptions(see fileluaconf.h).However,allthesecompatibilityoptionswillberemovedinthenextversionof Lua.

7.1 - Changes in the Language


The vararg system changed from the pseudo-argumentargwith a table with the extra arguments to the vararg expression. (See compile-time option LUA_COMPAT_VARARG in luaconf.h.) Therewasasubtlechangeinthescopeoftheimplicitvariablesoftheforstatementandfor therepeatstatement. Thelongstring/longcommentsyntax([[string]])doesnotallownesting.Youcanuse the new syntax ([=[string]=]) in these cases. (See compile-time option LUA_COMPAT_LSTRinluaconf.h.)

7.2 - Changes in the Libraries


Function string.gfind was renamed string.gmatch. (See compile-time option LUA_COMPAT_GFINDinluaconf.h.) Whenstring.gsubiscalledwithafunctionasitsthirdargument,wheneverthisfunction returnsnilorfalsethereplacementstringisthewholematch,insteadoftheemptystring. Function table.setn was deprecated. Function table.getn corresponds to the new

94 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

length operator (#); use the operator instead of the function. (See compile-time option LUA_COMPAT_GETNinluaconf.h.) Function loadlib was renamed package.loadlib. (See compile-time option LUA_COMPAT_LOADLIBinluaconf.h.) Functionmath.modwasrenamedmath.fmod.(Seecompile-timeoptionLUA_COMPAT_MOD inluaconf.h.) Functionstable.foreachandtable.foreachiaredeprecated.Youcanuseaforloop withpairsoripairsinstead. There were substantial changes in function require due to the new module system. However,thenewbehaviorismostlycompatiblewiththeold,butrequiregetsthepath frompackage.pathinsteadoffromLUA_PATH. Function collectgarbagehasdifferentarguments.Function gcinfoisdeprecated;use collectgarbage("count")instead.

7.3 - Changes in the API


The luaopen_*functions (to open libraries) cannotbe called directly,like a regular C function.TheymustbecalledthroughLua,likeaLuafunction. Function lua_openwasreplaced bylua_newstateto allow the userto seta memoryallocationfunction.YoucanuseluaL_newstatefromthestandardlibrarytocreateastate withastandardallocationfunction(basedonrealloc). Functions luaL_getn and luaL_setn (from the auxiliary library) are deprecated. Use lua_objleninsteadofluaL_getnandnothinginsteadofluaL_setn. FunctionluaL_openlibwasreplacedbyluaL_register. FunctionluaL_checkudatanowthrowsanerrorwhenthegivenvalueisnotauserdataof theexpectedtype.(InLua5.0itreturnedNULL.)

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 ::= varlist `= explist | 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 |

95 of 96

05/10/2012 05:29 PM

Lua 5.1 Reference Manual

http://www.lua.org/manual/5.1/manual.html

for namelist in explist do block end | function funcname funcbody | local function Name funcbody | local namelist [`= explist] laststat ::= return [explist] | break funcname ::= Name {`. Name} [`: Name] varlist ::= var {`, var} var ::= Name | prefixexp `[ exp `] | prefixexp `. Name

namelist ::= Name {`, Name} explist ::= {exp `,} exp exp ::= nil | false | true | Number | String | `... | function | prefixexp | tableconstructor | exp binop exp | unop exp

prefixexp ::= var | functioncall | `( exp `) functioncall ::= args ::= prefixexp args | prefixexp `: Name args

`( [explist] `) | tableconstructor | String

function ::= function funcbody funcbody ::= `( [parlist] `) block end parlist ::= namelist [`, `...] | `... tableconstructor ::= `{ [fieldlist] `} fieldlist ::= field {fieldsep field} [fieldsep] field ::= `[ exp `] `= exp | Name `= exp | exp fieldsep ::= `, | `; binop ::= `+ | `- | `* | `/ | `^ | `% | `.. | `< | `<= | `> | `>= | `== | `~= | and | or unop ::= `- | not | `#

Lastupdate:TueFeb719:14:47BRST2012

96 of 96

05/10/2012 05:29 PM

Potrebbero piacerti anche