LUA 5.1 Reference Manual
LUA 5.1 Reference Manual
LUA 5.1 Reference Manual
1 Reference Manual
http://www.lua.org/manual/5.1/manual.html
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
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.
while
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
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.
3 of 96
05/10/2012 05:29 PM
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
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
http://www.lua.org/manual/5.1/manual.html
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
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.)
7 of 96
05/10/2012 05:29 PM
http://www.lua.org/manual/5.1/manual.html
8 of 96
05/10/2012 05:29 PM
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.
9 of 96
05/10/2012 05:29 PM
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
http://www.lua.org/manual/5.1/manual.html
Anyexpressionenclosedinparenthesesalwaysresultsinonlyonevalue.Thus,(f(x,y,z))is alwaysa single value,even iffreturnsseveral values.(The value of(f(x,y,z))isthe first valuereturnedbyforniliffdoesnotreturnanyvalues.)
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.
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.6 - Precedence
OperatorprecedenceinLuafollowsthetablebelow,fromlowertohigherpriority: or and < .. + * not ^
> / #
<=
>=
~=
==
% - (unary)
12 of 96
05/10/2012 05:29 PM
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.
-----
-- 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.
13 of 96
05/10/2012 05:29 PM
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
14 of 96
05/10/2012 05:29 PM
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
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
16 of 96
05/10/2012 05:29 PM
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.8 - Metatables
EveryvalueinLuacanhaveametatable.ThismetatableisanordinaryLuatablethatdefinesthe behavioroftheoriginalvalueundercertainspecialoperations.Youcanchangeseveralaspects ofthebehaviorofoperationsoveravaluebysettingspecificfieldsinitsmetatable.Forinstance, whenanon-numericvalueistheoperandofanaddition,Luachecksforafunctioninthefield
17 of 96 05/10/2012 05:29 PM
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
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
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
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
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
http://www.lua.org/manual/5.1/manual.html
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.
23 of 96
05/10/2012 05:29 PM
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).
24 of 96
05/10/2012 05:29 PM
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
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
26 of 96
05/10/2012 05:29 PM
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.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
http://www.lua.org/manual/5.1/manual.html
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.
28 of 96
05/10/2012 05:29 PM
http://www.lua.org/manual/5.1/manual.html
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
http://www.lua.org/manual/5.1/manual.html
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
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]
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
http://www.lua.org/manual/5.1/manual.html
lua_concat
void lua_concat (lua_State *L, int n);
[-n,+1,e]
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]
32 of 96
05/10/2012 05:29 PM
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
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),-]
lua_gettable
void lua_gettable (lua_State *L, int index);
[-1,+1,e]
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
http://www.lua.org/manual/5.1/manual.html
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
http://www.lua.org/manual/5.1/manual.html
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
http://www.lua.org/manual/5.1/manual.html
lua_lessthan
int lua_lessthan (lua_State *L, int index1, int index2);
[-0,+0,e]
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
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]
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
http://www.lua.org/manual/5.1/manual.html
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,-]
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
http://www.lua.org/manual/5.1/manual.html
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
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
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
http://www.lua.org/manual/5.1/manual.html
lua_rawequal
int lua_rawequal (lua_State *L, int index1, int index2);
[-0,+0,-]
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]
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
http://www.lua.org/manual/5.1/manual.html
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,-]
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
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]
lua_setglobal
void lua_setglobal (lua_State *L, const char *name);
[-1,+0,e]
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]
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);
[-?,+?,-]
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,-]
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
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,-]
lua_tostring
[-0,+0,m]
47 of 96
05/10/2012 05:29 PM
http://www.lua.org/manual/5.1/manual.html
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,-]
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
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);
[-?,+?,-]
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
/* /* /* /* /* /* /* /* /*
*/ */ */ */ */ number of upvalues */ */ */ */
49 of 96
05/10/2012 05:29 PM
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
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
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
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,-]
53 of 96
05/10/2012 05:29 PM
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.
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
http://www.lua.org/manual/5.1/manual.html
luaL_argcheck
void luaL_argcheck (lua_State *L, int cond, int narg, const char *extramsg);
[-0,+0,v]
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
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
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]
luaL_checkstack
void luaL_checkstack (lua_State *L, int sz, const char *msg);
[-0,+0,v]
luaL_checkstring
const char *luaL_checkstring (lua_State *L, int narg);
[-0,+0,v]
57 of 96
05/10/2012 05:29 PM
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]
58 of 96
05/10/2012 05:29 PM
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
http://www.lua.org/manual/5.1/manual.html
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]
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
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]
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]
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
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
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,-]
luaL_where
void luaL_where (lua_State *L, int lvl);
[-0,+1,m]
63 of 96
05/10/2012 05:29 PM
http://www.lua.org/manual/5.1/manual.html
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.
64 of 96
05/10/2012 05:29 PM
http://www.lua.org/manual/5.1/manual.html
itsfacilities.
assert (v [, message])
Issuesanerrorwhenthevalueofitsargumentvisfalse(i.e.,nilorfalse);otherwise,returnsallits arguments.messageisanerrormessage;whenabsent,itdefaultsto"assertionfailed!"
dofile ([filename])
OpensthenamedfileandexecutesitscontentsasaLuachunk.Whencalledwithoutarguments, dofileexecutesthecontentsofthestandardinput(stdin).Returnsallvaluesreturnedbythe chunk.Incaseoferrors,dofilepropagatestheerrortoitscaller(thatis,dofiledoesnotrunin protectedmode).
65 of 96
05/10/2012 05:29 PM
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.
loadfile ([filename])
Similartoload,butgetsthechunkfromfilefilenameorfromthestandardinput,ifnofilename isgiven.
66 of 96
05/10/2012 05:29 PM
http://www.lua.org/manual/5.1/manual.html
pairs (t)
Returnsthreevalues:thenextfunction,thetablet,andnil,sothattheconstruction for k,v in pairs(t) do body end williterateoverallkeyvaluepairsoftablet. Seefunctionnextforthecaveatsofmodifyingthetableduringitstraversal.
print ()
67 of 96
05/10/2012 05:29 PM
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.
select (index, )
Ifindexisa number,returnsall argumentsafterargumentnumberindex.Otherwise,index mustbethestring"#",andselectreturnsthetotalnumberofextraargumentsitreceived.
68 of 96
05/10/2012 05:29 PM
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".
_VERSION
Aglobalvariable(notafunction)thatholdsastringcontainingthecurrentinterpreterversion.The currentcontentsofthisvariableis"Lua 5.1".
69 of 96
05/10/2012 05:29 PM
http://www.lua.org/manual/5.1/manual.html
coroutine.create (f)
Createsanewcoroutine,withbodyf.fmustbeaLuafunction.Returnsthisnewcoroutine,an objectwithtype"thread".
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
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
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
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.path
ThepathusedbyrequiretosearchforaLualoader. Atstart-up,LuainitializesthisvariablewiththevalueoftheenvironmentvariableLUA_PATHor withadefaultpathdefinedinluaconf.h,iftheenvironmentvariableisnotdefined.Any";;"in thevalueoftheenvironmentvariableisreplacedbythedefaultpath.
package.preload
73 of 96
05/10/2012 05:29 PM
http://www.lua.org/manual/5.1/manual.html
Atabletostoreloadersforspecificmodules(seerequire).
package.seeall (module)
Setsametatableformodulewithits__indexfieldreferringtotheglobalenvironment,sothatthis moduleinheritsvaluesfromtheglobalenvironment.Tobeusedasanoptiontofunctionmodule.
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.
74 of 96
05/10/2012 05:29 PM
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.
75 of 96
05/10/2012 05:29 PM
http://www.lua.org/manual/5.1/manual.html
76 of 96
05/10/2012 05:29 PM
http://www.lua.org/manual/5.1/manual.html
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.rep (s, n)
Returnsastringthatistheconcatenationofncopiesofthestrings.
string.reverse (s)
Returnsastringthatisthestringsreversed.
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
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
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.
79 of 96
05/10/2012 05:29 PM
http://www.lua.org/manual/5.1/manual.html
table.maxn (table)
Returnsthelargestpositivenumericalindexofthegiventable,orzeroifthetablehasnopositive numericalindices.(Todoitsjobthisfunctiondoesalineartraversalofthewholetable.)
math.abs (x)
80 of 96
05/10/2012 05:29 PM
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
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
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.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
http://www.lua.org/manual/5.1/manual.html
Returnsthetangentofx(assumedtobeinradians).
math.tanh (x)
Returnsthehyperbolictangentofx.
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
http://www.lua.org/manual/5.1/manual.html
io.output ([file])
Similartoio.input,butoperatesoverthedefaultoutputfile.
io.read ()
Equivalenttoio.input():read.
io.tmpfile ()
Returnsahandleforatemporaryfile.Thisfileisopenedinupdatemodeanditisautomatically removedwhentheprogramends.
85 of 96 05/10/2012 05:29 PM
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
http://www.lua.org/manual/5.1/manual.html
numberiszero,itreadsnothingandreturnsanemptystring,ornilonendoffile.
file:write ()
Writesthevalueofeachofitsargumentstothefile.Theargumentsmustbestringsornumbers. Towriteothervalues,usetostringorstring.formatbeforewrite.
os.clock ()
ReturnsanapproximationoftheamountinsecondsofCPUtimeusedbytheprogram.
87 of 96
05/10/2012 05:29 PM
http://www.lua.org/manual/5.1/manual.html
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
http://www.lua.org/manual/5.1/manual.html
Deletesthefileordirectorywiththegivenname.Directoriesmustbeemptytoberemoved.Ifthis functionfails,itreturnsnil,plusastringdescribingtheerror.
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
http://www.lua.org/manual/5.1/manual.html
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).
90 of 96
05/10/2012 05:29 PM
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.getmetatable (object)
Returnsthemetatableofthegivenobjectornilifitdoesnothaveametatable.
debug.getregistry ()
Returnstheregistrytable(see3.5).
91 of 96
05/10/2012 05:29 PM
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.
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
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
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.)
94 of 96
05/10/2012 05:29 PM
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.
95 of 96
05/10/2012 05:29 PM
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
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