manual.of 264 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922
  1. @Ci{$Id: manual.of $}
  2. @C{[(-------------------------------------------------------------------------}
  3. @manual{
  4. @sect1{@title{Introduction}
  5. Lua is a powerful, efficient, lightweight, embeddable scripting language.
  6. It supports procedural programming,
  7. object-oriented programming, functional programming,
  8. data-driven programming, and data description.
  9. Lua combines simple procedural syntax with powerful data description
  10. constructs based on associative arrays and extensible semantics.
  11. Lua is dynamically typed,
  12. runs by interpreting bytecode with a register-based
  13. virtual machine,
  14. and has automatic memory management with
  15. incremental garbage collection,
  16. making it ideal for configuration, scripting,
  17. and rapid prototyping.
  18. Lua is implemented as a library, written in @emphx{clean C},
  19. the common subset of @N{Standard C} and C++.
  20. The Lua distribution includes a host program called @id{lua},
  21. which uses the Lua library to offer a complete,
  22. standalone Lua interpreter,
  23. for interactive or batch use.
  24. Lua is intended to be used both as a powerful, lightweight,
  25. embeddable scripting language for any program that needs one,
  26. and as a powerful but lightweight and efficient stand-alone language.
  27. As an extension language, Lua has no notion of a @Q{main} program:
  28. it works @emph{embedded} in a host client,
  29. called the @emph{embedding program} or simply the @emphx{host}.
  30. (Frequently, this host is the stand-alone @id{lua} program.)
  31. The host program can invoke functions to execute a piece of Lua code,
  32. can write and read Lua variables,
  33. and can register @N{C functions} to be called by Lua code.
  34. Through the use of @N{C functions}, Lua can be augmented to cope with
  35. a wide range of different domains,
  36. thus creating customized programming languages sharing a syntactical framework.
  37. Lua is free software,
  38. and is provided as usual with no guarantees,
  39. as stated in its license.
  40. The implementation described in this manual is available
  41. at Lua's official web site, @id{www.lua.org}.
  42. Like any other reference manual,
  43. this document is dry in places.
  44. For a discussion of the decisions behind the design of Lua,
  45. see the technical papers available at Lua's web site.
  46. For a detailed introduction to programming in Lua,
  47. see Roberto's book, @emphx{Programming in Lua}.
  48. }
  49. @C{-------------------------------------------------------------------------}
  50. @sect1{basic| @title{Basic Concepts}
  51. This section describes the basic concepts of the language.
  52. @sect2{TypesSec| @title{Values and Types}
  53. Lua is a dynamically typed language.
  54. This means that
  55. variables do not have types; only values do.
  56. There are no type definitions in the language.
  57. All values carry their own type.
  58. All values in Lua are first-class values.
  59. This means that all values can be stored in variables,
  60. passed as arguments to other functions, and returned as results.
  61. There are eight @x{basic types} in Lua:
  62. @def{nil}, @def{boolean}, @def{number},
  63. @def{string}, @def{function}, @def{userdata},
  64. @def{thread}, and @def{table}.
  65. The type @emph{nil} has one single value, @nil,
  66. whose main property is to be different from any other value;
  67. it usually represents the absence of a useful value.
  68. The type @emph{boolean} has two values, @false and @true.
  69. Both @nil and @false make a condition false;
  70. any other value makes it true.
  71. The type @emph{number} represents both
  72. integer numbers and real (floating-point) numbers,
  73. using two @x{subtypes}: @def{integer} and @def{float}.
  74. Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
  75. but you can also compile Lua so that it
  76. uses 32-bit integers and/or single-precision (32-bit) floats.
  77. The option with 32 bits for both integers and floats
  78. is particularly attractive
  79. for small machines and embedded systems.
  80. (See macro @id{LUA_32BITS} in file @id{luaconf.h}.)
  81. Lua has explicit rules about when each subtype is used,
  82. but it also converts between them automatically as needed @see{coercion}.
  83. Therefore,
  84. the programmer may choose to mostly ignore the difference
  85. between integers and floats
  86. or to assume complete control over the representation of each number.
  87. The type @emph{string} represents immutable sequences of bytes.
  88. @index{eight-bit clean}
  89. Lua is 8-bit clean:
  90. strings can contain any 8-bit value,
  91. including @x{embedded zeros} (@Char{\0}).
  92. Lua is also encoding-agnostic;
  93. it makes no assumptions about the contents of a string.
  94. The length of any string in Lua must fit in a Lua integer.
  95. Lua can call (and manipulate) functions written in Lua and
  96. functions written in C @see{functioncall}.
  97. Both are represented by the type @emph{function}.
  98. The type @emph{userdata} is provided to allow arbitrary @N{C data} to
  99. be stored in Lua variables.
  100. A userdata value represents a block of raw memory.
  101. There are two kinds of userdata:
  102. @emphx{full userdata},
  103. which is an object with a block of memory managed by Lua,
  104. and @emphx{light userdata},
  105. which is simply a @N{C pointer} value.
  106. Userdata has no predefined operations in Lua,
  107. except assignment and identity test.
  108. By using @emph{metatables},
  109. the programmer can define operations for full userdata values
  110. @see{metatable}.
  111. Userdata values cannot be created or modified in Lua,
  112. only through the @N{C API}.
  113. This guarantees the integrity of data owned by the host program.
  114. The type @def{thread} represents independent threads of execution
  115. and it is used to implement coroutines @see{coroutine}.
  116. Lua threads are not related to operating-system threads.
  117. Lua supports coroutines on all systems,
  118. even those that do not support threads natively.
  119. The type @emph{table} implements @x{associative arrays},
  120. that is, @x{arrays} that can have as indices not only numbers,
  121. but any Lua value except @nil and @x{NaN}.
  122. (@emphx{Not a Number} is a special floating-point value
  123. used by the @x{IEEE 754} standard to represent
  124. undefined numerical results, such as @T{0/0}.)
  125. Tables can be @emph{heterogeneous};
  126. that is, they can contain values of all types (except @nil).
  127. Any key with value @nil is not considered part of the table.
  128. Conversely, any key that is not part of a table has
  129. an associated value @nil.
  130. Tables are the sole data-structuring mechanism in Lua;
  131. they can be used to represent ordinary arrays, lists,
  132. symbol tables, sets, records, graphs, trees, etc.
  133. To represent @x{records}, Lua uses the field name as an index.
  134. The language supports this representation by
  135. providing @id{a.name} as syntactic sugar for @T{a["name"]}.
  136. There are several convenient ways to create tables in Lua
  137. @see{tableconstructor}.
  138. Like indices,
  139. the values of table fields can be of any type.
  140. In particular,
  141. because functions are first-class values,
  142. table fields can contain functions.
  143. Thus tables can also carry @emph{methods} @see{func-def}.
  144. The indexing of tables follows
  145. the definition of raw equality in the language.
  146. The expressions @T{a[i]} and @T{a[j]}
  147. denote the same table element
  148. if and only if @id{i} and @id{j} are raw equal
  149. (that is, equal without metamethods).
  150. In particular, floats with integral values
  151. are equal to their respective integers
  152. (e.g., @T{1.0 == 1}).
  153. To avoid ambiguities,
  154. any float with integral value used as a key
  155. is converted to its respective integer.
  156. For instance, if you write @T{a[2.0] = true},
  157. the actual key inserted into the table will be the
  158. integer @T{2}.
  159. (On the other hand,
  160. 2 and @St{2} are different Lua values and therefore
  161. denote different table entries.)
  162. Tables, functions, threads, and (full) userdata values are @emph{objects}:
  163. variables do not actually @emph{contain} these values,
  164. only @emph{references} to them.
  165. Assignment, parameter passing, and function returns
  166. always manipulate references to such values;
  167. these operations do not imply any kind of copy.
  168. The library function @Lid{type} returns a string describing the type
  169. of a given value @see{predefined}.
  170. }
  171. @sect2{globalenv| @title{Environments and the Global Environment}
  172. As will be discussed in @refsec{variables} and @refsec{assignment},
  173. any reference to a free name
  174. (that is, a name not bound to any declaration) @id{var}
  175. is syntactically translated to @T{_ENV.var}.
  176. Moreover, every chunk is compiled in the scope of
  177. an external local variable named @id{_ENV} @see{chunks},
  178. so @id{_ENV} itself is never a free name in a chunk.
  179. Despite the existence of this external @id{_ENV} variable and
  180. the translation of free names,
  181. @id{_ENV} is a completely regular name.
  182. In particular,
  183. you can define new variables and parameters with that name.
  184. Each reference to a free name uses the @id{_ENV} that is
  185. visible at that point in the program,
  186. following the usual visibility rules of Lua @see{visibility}.
  187. Any table used as the value of @id{_ENV} is called an @def{environment}.
  188. Lua keeps a distinguished environment called the @def{global environment}.
  189. This value is kept at a special index in the C registry @see{registry}.
  190. In Lua, the global variable @Lid{_G} is initialized with this same value.
  191. (@Lid{_G} is never used internally.)
  192. When Lua loads a chunk,
  193. the default value for its @id{_ENV} upvalue
  194. is the global environment @seeF{load}.
  195. Therefore, by default,
  196. free names in Lua code refer to entries in the global environment
  197. (and, therefore, they are also called @def{global variables}).
  198. Moreover, all standard libraries are loaded in the global environment
  199. and some functions there operate on that environment.
  200. You can use @Lid{load} (or @Lid{loadfile})
  201. to load a chunk with a different environment.
  202. (In C, you have to load the chunk and then change the value
  203. of its first upvalue.)
  204. }
  205. @sect2{error| @title{Error Handling}
  206. Because Lua is an embedded extension language,
  207. all Lua actions start from @N{C code} in the host program
  208. calling a function from the Lua library.
  209. (When you use Lua standalone,
  210. the @id{lua} application is the host program.)
  211. Whenever an error occurs during
  212. the compilation or execution of a Lua chunk,
  213. control returns to the host,
  214. which can take appropriate measures
  215. (such as printing an error message).
  216. Lua code can explicitly generate an error by calling the
  217. @Lid{error} function.
  218. If you need to catch errors in Lua,
  219. you can use @Lid{pcall} or @Lid{xpcall}
  220. to call a given function in @emphx{protected mode}.
  221. Whenever there is an error,
  222. an @def{error object} (also called an @def{error message})
  223. is propagated with information about the error.
  224. Lua itself only generates errors whose error object is a string,
  225. but programs may generate errors with
  226. any value as the error object.
  227. It is up to the Lua program or its host to handle such error objects.
  228. When you use @Lid{xpcall} or @Lid{lua_pcall},
  229. you may give a @def{message handler}
  230. to be called in case of errors.
  231. This function is called with the original error object
  232. and returns a new error object.
  233. It is called before the error unwinds the stack,
  234. so that it can gather more information about the error,
  235. for instance by inspecting the stack and creating a stack traceback.
  236. This message handler is still protected by the protected call;
  237. so, an error inside the message handler
  238. will call the message handler again.
  239. If this loop goes on for too long,
  240. Lua breaks it and returns an appropriate message.
  241. (The message handler is called only for regular runtime errors.
  242. It is not called for memory-allocation errors
  243. nor for errors while running finalizers.)
  244. }
  245. @sect2{metatable| @title{Metatables and Metamethods}
  246. Every value in Lua can have a @emph{metatable}.
  247. This @def{metatable} is an ordinary Lua table
  248. that defines the behavior of the original value
  249. under certain special operations.
  250. You can change several aspects of the behavior
  251. of operations over a value by setting specific fields in its metatable.
  252. For instance, when a non-numeric value is the operand of an addition,
  253. Lua checks for a function in the field @St{__add} of the value's metatable.
  254. If it finds one,
  255. Lua calls this function to perform the addition.
  256. The key for each event in a metatable is a string
  257. with the event name prefixed by two underscores;
  258. the corresponding values are called @def{metamethods}.
  259. In the previous example, the key is @St{__add}
  260. and the metamethod is the function that performs the addition.
  261. Unless stated otherwise,
  262. metamethods should be function values.
  263. You can query the metatable of any value
  264. using the @Lid{getmetatable} function.
  265. Lua queries metamethods in metatables using a raw access @seeF{rawget}.
  266. So, to retrieve the metamethod for event @id{ev} in object @id{o},
  267. Lua does the equivalent to the following code:
  268. @verbatim{
  269. rawget(getmetatable(@rep{o}) or {}, "__@rep{ev}")
  270. }
  271. You can replace the metatable of tables
  272. using the @Lid{setmetatable} function.
  273. You cannot change the metatable of other types from Lua code
  274. (except by using the @link{debuglib|debug library});
  275. you should use the @N{C API} for that.
  276. Tables and full userdata have individual metatables
  277. (although multiple tables and userdata can share their metatables).
  278. Values of all other types share one single metatable per type;
  279. that is, there is one single metatable for all numbers,
  280. one for all strings, etc.
  281. By default, a value has no metatable,
  282. but the string library sets a metatable for the string type @see{strlib}.
  283. A metatable controls how an object behaves in
  284. arithmetic operations, bitwise operations,
  285. order comparisons, concatenation, length operation, calls, and indexing.
  286. A metatable also can define a function to be called
  287. when a userdata or a table is @link{GC|garbage collected}.
  288. For the unary operators (negation, length, and bitwise NOT),
  289. the metamethod is computed and called with a dummy second operand,
  290. equal to the first one.
  291. This extra operand is only to simplify Lua's internals
  292. (by making these operators behave like a binary operation)
  293. and may be removed in future versions.
  294. (For most uses this extra operand is irrelevant.)
  295. A detailed list of events controlled by metatables is given next.
  296. Each operation is identified by its corresponding key.
  297. @description{
  298. @item{@idx{__add}|
  299. the addition (@T{+}) operation.
  300. If any operand for an addition is not a number
  301. (nor a string coercible to a number),
  302. Lua will try to call a metamethod.
  303. First, Lua will check the first operand (even if it is valid).
  304. If that operand does not define a metamethod for @idx{__add},
  305. then Lua will check the second operand.
  306. If Lua can find a metamethod,
  307. it calls the metamethod with the two operands as arguments,
  308. and the result of the call
  309. (adjusted to one value)
  310. is the result of the operation.
  311. Otherwise,
  312. it raises an error.
  313. }
  314. @item{@idx{__sub}|
  315. the subtraction (@T{-}) operation.
  316. Behavior similar to the addition operation.
  317. }
  318. @item{@idx{__mul}|
  319. the multiplication (@T{*}) operation.
  320. Behavior similar to the addition operation.
  321. }
  322. @item{@idx{__div}|
  323. the division (@T{/}) operation.
  324. Behavior similar to the addition operation.
  325. }
  326. @item{@idx{__mod}|
  327. the modulo (@T{%}) operation.
  328. Behavior similar to the addition operation.
  329. }
  330. @item{@idx{__pow}|
  331. the exponentiation (@T{^}) operation.
  332. Behavior similar to the addition operation.
  333. }
  334. @item{@idx{__unm}|
  335. the negation (unary @T{-}) operation.
  336. Behavior similar to the addition operation.
  337. }
  338. @item{@idx{__idiv}|
  339. the floor division (@T{//}) operation.
  340. Behavior similar to the addition operation.
  341. }
  342. @item{@idx{__band}|
  343. the bitwise AND (@T{&}) operation.
  344. Behavior similar to the addition operation,
  345. except that Lua will try a metamethod
  346. if any operand is neither an integer
  347. nor a value coercible to an integer @see{coercion}.
  348. }
  349. @item{@idx{__bor}|
  350. the bitwise OR (@T{|}) operation.
  351. Behavior similar to the bitwise AND operation.
  352. }
  353. @item{@idx{__bxor}|
  354. the bitwise exclusive OR (binary @T{~}) operation.
  355. Behavior similar to the bitwise AND operation.
  356. }
  357. @item{@idx{__bnot}|
  358. the bitwise NOT (unary @T{~}) operation.
  359. Behavior similar to the bitwise AND operation.
  360. }
  361. @item{@idx{__shl}|
  362. the bitwise left shift (@T{<<}) operation.
  363. Behavior similar to the bitwise AND operation.
  364. }
  365. @item{@idx{__shr}|
  366. the bitwise right shift (@T{>>}) operation.
  367. Behavior similar to the bitwise AND operation.
  368. }
  369. @item{@idx{__concat}|
  370. the concatenation (@T{..}) operation.
  371. Behavior similar to the addition operation,
  372. except that Lua will try a metamethod
  373. if any operand is neither a string nor a number
  374. (which is always coercible to a string).
  375. }
  376. @item{@idx{__len}|
  377. the length (@T{#}) operation.
  378. If the object is not a string,
  379. Lua will try its metamethod.
  380. If there is a metamethod,
  381. Lua calls it with the object as argument,
  382. and the result of the call
  383. (always adjusted to one value)
  384. is the result of the operation.
  385. If there is no metamethod but the object is a table,
  386. then Lua uses the table length operation @see{len-op}.
  387. Otherwise, Lua raises an error.
  388. }
  389. @item{@idx{__eq}|
  390. the equal (@T{==}) operation.
  391. Behavior similar to the addition operation,
  392. except that Lua will try a metamethod only when the values
  393. being compared are either both tables or both full userdata
  394. and they are not primitively equal.
  395. The result of the call is always converted to a boolean.
  396. }
  397. @item{@idx{__lt}|
  398. the less than (@T{<}) operation.
  399. Behavior similar to the addition operation,
  400. except that Lua will try a metamethod only when the values
  401. being compared are neither both numbers nor both strings.
  402. The result of the call is always converted to a boolean.
  403. }
  404. @item{@idx{__le}|
  405. the less equal (@T{<=}) operation.
  406. Behavior similar to the less than operation.
  407. }
  408. @item{@idx{__index}|
  409. The indexing access operation @T{table[key]}.
  410. This event happens when @id{table} is not a table or
  411. when @id{key} is not present in @id{table}.
  412. The metamethod is looked up in @id{table}.
  413. Despite the name,
  414. the metamethod for this event can be either a function or a table.
  415. If it is a function,
  416. it is called with @id{table} and @id{key} as arguments,
  417. and the result of the call
  418. (adjusted to one value)
  419. is the result of the operation.
  420. If it is a table,
  421. the final result is the result of indexing this table with @id{key}.
  422. (This indexing is regular, not raw,
  423. and therefore can trigger another metamethod.)
  424. }
  425. @item{@idx{__newindex}|
  426. The indexing assignment @T{table[key] = value}.
  427. Like the index event,
  428. this event happens when @id{table} is not a table or
  429. when @id{key} is not present in @id{table}.
  430. The metamethod is looked up in @id{table}.
  431. Like with indexing,
  432. the metamethod for this event can be either a function or a table.
  433. If it is a function,
  434. it is called with @id{table}, @id{key}, and @id{value} as arguments.
  435. If it is a table,
  436. Lua does an indexing assignment to this table with the same key and value.
  437. (This assignment is regular, not raw,
  438. and therefore can trigger another metamethod.)
  439. Whenever there is a @idx{__newindex} metamethod,
  440. Lua does not perform the primitive assignment.
  441. (If necessary,
  442. the metamethod itself can call @Lid{rawset}
  443. to do the assignment.)
  444. }
  445. @item{@idx{__call}|
  446. The call operation @T{func(args)}.
  447. This event happens when Lua tries to call a non-function value
  448. (that is, @id{func} is not a function).
  449. The metamethod is looked up in @id{func}.
  450. If present,
  451. the metamethod is called with @id{func} as its first argument,
  452. followed by the arguments of the original call (@id{args}).
  453. All results of the call
  454. are the result of the operation.
  455. (This is the only metamethod that allows multiple results.)
  456. }
  457. }
  458. It is a good practice to add all needed metamethods to a table
  459. before setting it as a metatable of some object.
  460. In particular, the @idx{__gc} metamethod works only when this order
  461. is followed @see{finalizers}.
  462. Because metatables are regular tables,
  463. they can contain arbitrary fields,
  464. not only the event names defined above.
  465. Some functions in the standard library
  466. (e.g., @Lid{tostring})
  467. use other fields in metatables for their own purposes.
  468. }
  469. @sect2{GC| @title{Garbage Collection}
  470. Lua performs automatic memory management.
  471. This means that
  472. you do not have to worry about allocating memory for new objects
  473. or freeing it when the objects are no longer needed.
  474. Lua manages memory automatically by running
  475. a @def{garbage collector} to collect all @emph{dead objects}
  476. (that is, objects that are no longer accessible from Lua).
  477. All memory used by Lua is subject to automatic management:
  478. strings, tables, userdata, functions, threads, internal structures, etc.
  479. The garbage collector (GC) in Lua can work in two modes:
  480. incremental and generational.
  481. The default GC mode with the default parameters
  482. are adequate for most uses.
  483. Programs that waste a large proportion of its time
  484. allocating and freeing memory can benefit from other settings.
  485. Keep in mind that the GC behavior is non-portable
  486. both across platforms and across different Lua releases;
  487. therefore, optimal settings are also non-portable.
  488. You can change the GC mode and parameters by calling
  489. @Lid{lua_gc} in C
  490. or @Lid{collectgarbage} in Lua.
  491. You can also use these functions to control
  492. the collector directly (e.g., stop and restart it).
  493. @sect3{@title{Incremental Garbage Collection}
  494. In incremental mode,
  495. each GC cycle performs a mark-and-sweep collection in small steps
  496. interleaved with the program's execution.
  497. In this mode,
  498. the collector uses three numbers to control its garbage-collection cycles:
  499. the @def{garbage-collector pause},
  500. the @def{garbage-collector step multiplier},
  501. and the @def{garbage-collector step size}.
  502. The garbage-collector pause
  503. controls how long the collector waits before starting a new cycle.
  504. The collector starts a new cycle when the use of memory
  505. hits @M{n%} of the use after the previous collection.
  506. Larger values make the collector less aggressive.
  507. Values smaller than 100 mean the collector will not wait to
  508. start a new cycle.
  509. A value of 200 means that the collector waits for the total memory in use
  510. to double before starting a new cycle.
  511. The default value is 200; the maximum value is 1000.
  512. The garbage-collector step multiplier
  513. controls the relative speed of the collector relative to
  514. memory allocation,
  515. that is,
  516. how many elements it marks or sweeps for each
  517. kilobyte of memory allocated.
  518. Larger values make the collector more aggressive but also increase
  519. the size of each incremental step.
  520. You should not use values smaller than 100,
  521. because they make the collector too slow and
  522. can result in the collector never finishing a cycle.
  523. The default value is 100; the maximum value is 1000.
  524. The garbage-collector step size controls the
  525. size of each incremental step,
  526. specifically how many bytes the interpreter allocates
  527. before performing a step.
  528. This parameter is logarithmic:
  529. A value of @M{n} means the interpreter will allocate @M{2@sp{n}}
  530. bytes between steps and perform equivalent work during the step.
  531. A large value (e.g., 60) makes the collector a stop-the-world
  532. (non-incremental) collector.
  533. The default value is 13,
  534. which makes for steps of approximately @N{8 Kbytes}.
  535. }
  536. @sect3{@title{Generational Garbage Collection}
  537. In generational mode,
  538. the collector does frequent @emph{minor} collections,
  539. which traverses only objects recently created.
  540. If after a minor collection the use of memory is still above a limit,
  541. the collector does a @emph{major} collection,
  542. which traverses all objects.
  543. The generational mode uses two parameters:
  544. the @def{major multiplier} and the @def{the minor multiplier}.
  545. The major multiplier controls the frequency of major collections.
  546. For a major multiplier @M{x},
  547. a new major collection will be done when memory
  548. grows @M{x%} larger than the memory in use after the previous major
  549. collection.
  550. For instance, for a multiplier of 100,
  551. the collector will do a major collection when the use of memory
  552. gets larger than twice the use after the previous collection.
  553. The default value is 100; the maximum value is 1000.
  554. The minor multiplier controls the frequency of minor collections.
  555. For a minor multiplier @M{x},
  556. a new minor collection will be done when memory
  557. grows @M{x%} larger than the memory in use after the previous major
  558. collection.
  559. For instance, for a multiplier of 20,
  560. the collector will do a minor collection when the use of memory
  561. gets 20% larger than the use after the previous major collection.
  562. The default value is 20; the maximum value is 200.
  563. }
  564. @sect3{finalizers| @title{Garbage-Collection Metamethods}
  565. You can set garbage-collector metamethods for tables
  566. and, using the @N{C API},
  567. for full userdata @see{metatable}.
  568. These metamethods, called @def{finalizers},
  569. are called when the garbage collector detects that the
  570. corresponding table or userdata is unreachable.
  571. Finalizers allow you to coordinate Lua's garbage collection
  572. with external resource management
  573. such as closing files, network or database connections,
  574. or freeing your own memory.
  575. For an object (table or userdata) to be finalized when collected,
  576. you must @emph{mark} it for finalization.
  577. @index{mark (for finalization)}
  578. You mark an object for finalization when you set its metatable
  579. and the metatable has a field indexed by the string @St{__gc}.
  580. Note that if you set a metatable without a @idx{__gc} field
  581. and later create that field in the metatable,
  582. the object will not be marked for finalization.
  583. When a marked object becomes garbage,
  584. it is not collected immediately by the garbage collector.
  585. Instead, Lua puts it in a list.
  586. After the collection,
  587. Lua goes through that list.
  588. For each object in the list,
  589. it checks the object's @idx{__gc} metamethod:
  590. If it is a function,
  591. Lua calls it with the object as its single argument;
  592. if the metamethod is not a function,
  593. Lua simply ignores it.
  594. At the end of each garbage-collection cycle,
  595. the finalizers for objects are called in
  596. the reverse order that the objects were marked for finalization,
  597. among those collected in that cycle;
  598. that is, the first finalizer to be called is the one associated
  599. with the object marked last in the program.
  600. The execution of each finalizer may occur at any point during
  601. the execution of the regular code.
  602. Because the object being collected must still be used by the finalizer,
  603. that object (and other objects accessible only through it)
  604. must be @emph{resurrected} by Lua.@index{resurrection}
  605. Usually, this resurrection is transient,
  606. and the object memory is freed in the next garbage-collection cycle.
  607. However, if the finalizer stores the object in some global place
  608. (e.g., a global variable),
  609. then the resurrection is permanent.
  610. Moreover, if the finalizer marks a finalizing object for finalization again,
  611. its finalizer will be called again in the next cycle where the
  612. object is unreachable.
  613. In any case,
  614. the object memory is freed only in a GC cycle where
  615. the object is unreachable and not marked for finalization.
  616. When you close a state @seeF{lua_close},
  617. Lua calls the finalizers of all objects marked for finalization,
  618. following the reverse order that they were marked.
  619. If any finalizer marks objects for collection during that phase,
  620. these marks have no effect.
  621. Finalizers cannot yield.
  622. }
  623. @sect3{weak-table| @title{Weak Tables}
  624. A @def{weak table} is a table whose elements are
  625. @def{weak references}.
  626. A weak reference is ignored by the garbage collector.
  627. In other words,
  628. if the only references to an object are weak references,
  629. then the garbage collector will collect that object.
  630. A weak table can have weak keys, weak values, or both.
  631. A table with weak values allows the collection of its values,
  632. but prevents the collection of its keys.
  633. A table with both weak keys and weak values allows the collection of
  634. both keys and values.
  635. In any case, if either the key or the value is collected,
  636. the whole pair is removed from the table.
  637. The weakness of a table is controlled by the
  638. @idx{__mode} field of its metatable.
  639. This field, if present, must be one of the following strings:
  640. @St{k}, for a table with weak keys;
  641. @St{v}, for a table with weak values;
  642. or @St{kv}, for a table with both weak keys and values.
  643. A table with weak keys and strong values
  644. is also called an @def{ephemeron table}.
  645. In an ephemeron table,
  646. a value is considered reachable only if its key is reachable.
  647. In particular,
  648. if the only reference to a key comes through its value,
  649. the pair is removed.
  650. Any change in the weakness of a table may take effect only
  651. at the next collect cycle.
  652. In particular, if you change the weakness to a stronger mode,
  653. Lua may still collect some items from that table
  654. before the change takes effect.
  655. Only objects that have an explicit construction
  656. are removed from weak tables.
  657. Values, such as numbers and @x{light @N{C functions}},
  658. are not subject to garbage collection,
  659. and therefore are not removed from weak tables
  660. (unless their associated values are collected).
  661. Although strings are subject to garbage collection,
  662. they do not have an explicit construction,
  663. and therefore are not removed from weak tables.
  664. Resurrected objects
  665. (that is, objects being finalized
  666. and objects accessible only through objects being finalized)
  667. have a special behavior in weak tables.
  668. They are removed from weak values before running their finalizers,
  669. but are removed from weak keys only in the next collection
  670. after running their finalizers, when such objects are actually freed.
  671. This behavior allows the finalizer to access properties
  672. associated with the object through weak tables.
  673. If a weak table is among the resurrected objects in a collection cycle,
  674. it may not be properly cleared until the next cycle.
  675. }
  676. }
  677. @sect2{coroutine| @title{Coroutines}
  678. Lua supports coroutines,
  679. also called @emphx{collaborative multithreading}.
  680. A coroutine in Lua represents an independent thread of execution.
  681. Unlike threads in multithread systems, however,
  682. a coroutine only suspends its execution by explicitly calling
  683. a yield function.
  684. You create a coroutine by calling @Lid{coroutine.create}.
  685. Its sole argument is a function
  686. that is the main function of the coroutine.
  687. The @id{create} function only creates a new coroutine and
  688. returns a handle to it (an object of type @emph{thread});
  689. it does not start the coroutine.
  690. You execute a coroutine by calling @Lid{coroutine.resume}.
  691. When you first call @Lid{coroutine.resume},
  692. passing as its first argument
  693. a thread returned by @Lid{coroutine.create},
  694. the coroutine starts its execution by
  695. calling its main function.
  696. Extra arguments passed to @Lid{coroutine.resume} are passed
  697. as arguments to that function.
  698. After the coroutine starts running,
  699. it runs until it terminates or @emph{yields}.
  700. A coroutine can terminate its execution in two ways:
  701. normally, when its main function returns
  702. (explicitly or implicitly, after the last instruction);
  703. and abnormally, if there is an unprotected error.
  704. In case of normal termination,
  705. @Lid{coroutine.resume} returns @true,
  706. plus any values returned by the coroutine main function.
  707. In case of errors, @Lid{coroutine.resume} returns @false
  708. plus an error object.
  709. A coroutine yields by calling @Lid{coroutine.yield}.
  710. When a coroutine yields,
  711. the corresponding @Lid{coroutine.resume} returns immediately,
  712. even if the yield happens inside nested function calls
  713. (that is, not in the main function,
  714. but in a function directly or indirectly called by the main function).
  715. In the case of a yield, @Lid{coroutine.resume} also returns @true,
  716. plus any values passed to @Lid{coroutine.yield}.
  717. The next time you resume the same coroutine,
  718. it continues its execution from the point where it yielded,
  719. with the call to @Lid{coroutine.yield} returning any extra
  720. arguments passed to @Lid{coroutine.resume}.
  721. Like @Lid{coroutine.create},
  722. the @Lid{coroutine.wrap} function also creates a coroutine,
  723. but instead of returning the coroutine itself,
  724. it returns a function that, when called, resumes the coroutine.
  725. Any arguments passed to this function
  726. go as extra arguments to @Lid{coroutine.resume}.
  727. @Lid{coroutine.wrap} returns all the values returned by @Lid{coroutine.resume},
  728. except the first one (the boolean error code).
  729. Unlike @Lid{coroutine.resume},
  730. @Lid{coroutine.wrap} does not catch errors;
  731. any error is propagated to the caller.
  732. As an example of how coroutines work,
  733. consider the following code:
  734. @verbatim{
  735. function foo (a)
  736. print("foo", a)
  737. return coroutine.yield(2*a)
  738. end
  739. co = coroutine.create(function (a,b)
  740. print("co-body", a, b)
  741. local r = foo(a+1)
  742. print("co-body", r)
  743. local r, s = coroutine.yield(a+b, a-b)
  744. print("co-body", r, s)
  745. return b, "end"
  746. end)
  747. print("main", coroutine.resume(co, 1, 10))
  748. print("main", coroutine.resume(co, "r"))
  749. print("main", coroutine.resume(co, "x", "y"))
  750. print("main", coroutine.resume(co, "x", "y"))
  751. }
  752. When you run it, it produces the following output:
  753. @verbatim{
  754. co-body 1 10
  755. foo 2
  756. main true 4
  757. co-body r
  758. main true 11 -9
  759. co-body x y
  760. main true 10 end
  761. main false cannot resume dead coroutine
  762. }
  763. You can also create and manipulate coroutines through the C API:
  764. see functions @Lid{lua_newthread}, @Lid{lua_resume},
  765. and @Lid{lua_yield}.
  766. }
  767. }
  768. @C{-------------------------------------------------------------------------}
  769. @sect1{language| @title{The Language}
  770. This section describes the lexis, the syntax, and the semantics of Lua.
  771. In other words,
  772. this section describes
  773. which tokens are valid,
  774. how they can be combined,
  775. and what their combinations mean.
  776. Language constructs will be explained using the usual extended BNF notation,
  777. in which
  778. @N{@bnfrep{@rep{a}} means 0} or more @rep{a}'s, and
  779. @N{@bnfopt{@rep{a}} means} an optional @rep{a}.
  780. Non-terminals are shown like @bnfNter{non-terminal},
  781. keywords are shown like @rw{kword},
  782. and other terminal symbols are shown like @bnfter{=}.
  783. The complete syntax of Lua can be found in @refsec{BNF}
  784. at the end of this manual.
  785. @sect2{lexical| @title{Lexical Conventions}
  786. Lua is a @x{free-form} language.
  787. It ignores spaces and comments between lexical elements (@x{tokens}),
  788. except as delimiters between @x{names} and @x{keywords}.
  789. In source code,
  790. Lua recognizes as spaces the standard ASCII white-space
  791. characters space, form feed, newline,
  792. carriage return, horizontal tab, and vertical tab.
  793. @def{Names}
  794. (also called @def{identifiers})
  795. in Lua can be any string of Latin letters,
  796. Arabic-Indic digits, and underscores,
  797. not beginning with a digit and
  798. not being a reserved word.
  799. Identifiers are used to name variables, table fields, and labels.
  800. The following @def{keywords} are reserved
  801. and cannot be used as names:
  802. @index{reserved words}
  803. @verbatim{
  804. and break do else elseif end
  805. false for function goto if in
  806. local nil not or repeat return
  807. then true until while
  808. }
  809. Lua is a case-sensitive language:
  810. @id{and} is a reserved word, but @id{And} and @id{AND}
  811. are two different, valid names.
  812. As a convention,
  813. programs should avoid creating
  814. names that start with an underscore followed by
  815. one or more uppercase letters (such as @Lid{_VERSION}).
  816. The following strings denote other @x{tokens}:
  817. @verbatim{
  818. + - * / % ^ #
  819. & ~ | << >> //
  820. == ~= <= >= < > =
  821. ( ) { } [ ] ::
  822. ; : , . .. ...
  823. }
  824. A @def{short literal string}
  825. can be delimited by matching single or double quotes,
  826. and can contain the following C-like escape sequences:
  827. @Char{\a} (bell),
  828. @Char{\b} (backspace),
  829. @Char{\f} (form feed),
  830. @Char{\n} (newline),
  831. @Char{\r} (carriage return),
  832. @Char{\t} (horizontal tab),
  833. @Char{\v} (vertical tab),
  834. @Char{\\} (backslash),
  835. @Char{\"} (quotation mark [double quote]),
  836. and @Char{\'} (apostrophe [single quote]).
  837. A backslash followed by a line break
  838. results in a newline in the string.
  839. The escape sequence @Char{\z} skips the following span
  840. of white-space characters,
  841. including line breaks;
  842. it is particularly useful to break and indent a long literal string
  843. into multiple lines without adding the newlines and spaces
  844. into the string contents.
  845. A short literal string cannot contain unescaped line breaks
  846. nor escapes not forming a valid escape sequence.
  847. We can specify any byte in a short literal string,
  848. including @x{embedded zeros},
  849. by its numeric value.
  850. This can be done
  851. with the escape sequence @T{\x@rep{XX}},
  852. where @rep{XX} is a sequence of exactly two hexadecimal digits,
  853. or with the escape sequence @T{\@rep{ddd}},
  854. where @rep{ddd} is a sequence of up to three decimal digits.
  855. (Note that if a decimal escape sequence is to be followed by a digit,
  856. it must be expressed using exactly three digits.)
  857. The @x{UTF-8} encoding of a @x{Unicode} character
  858. can be inserted in a literal string with
  859. the escape sequence @T{\u{@rep{XXX}}}
  860. (note the mandatory enclosing brackets),
  861. where @rep{XXX} is a sequence of one or more hexadecimal digits
  862. representing the character code point.
  863. Literal strings can also be defined using a long format
  864. enclosed by @def{long brackets}.
  865. We define an @def{opening long bracket of level @rep{n}} as an opening
  866. square bracket followed by @rep{n} equal signs followed by another
  867. opening square bracket.
  868. So, an opening long bracket of @N{level 0} is written as @T{[[}, @C{]]}
  869. an opening long bracket of @N{level 1} is written as @T{[=[}, @C{]]}
  870. and so on.
  871. A @emph{closing long bracket} is defined similarly;
  872. for instance,
  873. a closing long bracket of @N{level 4} is written as @C{[[} @T{]====]}.
  874. A @def{long literal} starts with an opening long bracket of any level and
  875. ends at the first closing long bracket of the same level.
  876. It can contain any text except a closing bracket of the same level.
  877. Literals in this bracketed form can run for several lines,
  878. do not interpret any escape sequences,
  879. and ignore long brackets of any other level.
  880. Any kind of end-of-line sequence
  881. (carriage return, newline, carriage return followed by newline,
  882. or newline followed by carriage return)
  883. is converted to a simple newline.
  884. When the opening long bracket is immediately followed by a newline,
  885. the newline is not included in the string.
  886. As an example, in a system using ASCII
  887. (in which @Char{a} is coded @N{as 97},
  888. newline is coded @N{as 10}, and @Char{1} is coded @N{as 49}),
  889. the five literal strings below denote the same string:
  890. @verbatim{
  891. a = 'alo\n123"'
  892. a = "alo\n123\""
  893. a = '\97lo\10\04923"'
  894. a = [[alo
  895. 123"]]
  896. a = [==[
  897. alo
  898. 123"]==]
  899. }
  900. Any byte in a literal string not
  901. explicitly affected by the previous rules represents itself.
  902. However, Lua opens files for parsing in text mode,
  903. and the system's file functions may have problems with
  904. some control characters.
  905. So, it is safer to represent
  906. non-text data as a quoted literal with
  907. explicit escape sequences for the non-text characters.
  908. A @def{numeric constant} (or @def{numeral})
  909. can be written with an optional fractional part
  910. and an optional decimal exponent,
  911. marked by a letter @Char{e} or @Char{E}.
  912. Lua also accepts @x{hexadecimal constants},
  913. which start with @T{0x} or @T{0X}.
  914. Hexadecimal constants also accept an optional fractional part
  915. plus an optional binary exponent,
  916. marked by a letter @Char{p} or @Char{P}.
  917. A numeric constant with a radix point or an exponent
  918. denotes a float;
  919. otherwise,
  920. if its value fits in an integer or it is a hexadecimal constant,
  921. it denotes an integer;
  922. otherwise (that is, a decimal integer numeral that overflows),
  923. it denotes a float.
  924. (Hexadecimal integer numerals that overflow @emph{wrap around};
  925. they always denote an integer value.)
  926. Examples of valid integer constants are
  927. @verbatim{
  928. 3 345 0xff 0xBEBADA
  929. }
  930. Examples of valid float constants are
  931. @verbatim{
  932. 3.0 3.1416 314.16e-2 0.31416E1 34e1
  933. 0x0.1E 0xA23p-4 0X1.921FB54442D18P+1
  934. }
  935. A @def{comment} starts with a double hyphen (@T{--})
  936. anywhere outside a string.
  937. If the text immediately after @T{--} is not an opening long bracket,
  938. the comment is a @def{short comment},
  939. which runs until the end of the line.
  940. Otherwise, it is a @def{long comment},
  941. which runs until the corresponding closing long bracket.
  942. }
  943. @sect2{variables| @title{Variables}
  944. Variables are places that store values.
  945. There are three kinds of variables in Lua:
  946. global variables, local variables, and table fields.
  947. A single name can denote a global variable or a local variable
  948. (or a function's formal parameter,
  949. which is a particular kind of local variable):
  950. @Produc{
  951. @producname{var}@producbody{@bnfNter{Name}}
  952. }
  953. @bnfNter{Name} denotes identifiers, as defined in @See{lexical}.
  954. Any variable name is assumed to be global unless explicitly declared
  955. as a local @see{localvar}.
  956. @x{Local variables} are @emph{lexically scoped}:
  957. local variables can be freely accessed by functions
  958. defined inside their scope @see{visibility}.
  959. Before the first assignment to a variable, its value is @nil.
  960. Square brackets are used to index a table:
  961. @Produc{
  962. @producname{var}@producbody{prefixexp @bnfter{[} exp @bnfter{]}}
  963. }
  964. The meaning of accesses to table fields can be changed via metatables
  965. @see{metatable}.
  966. The syntax @id{var.Name} is just syntactic sugar for
  967. @T{var["Name"]}:
  968. @Produc{
  969. @producname{var}@producbody{prefixexp @bnfter{.} @bnfNter{Name}}
  970. }
  971. An access to a global variable @id{x}
  972. is equivalent to @id{_ENV.x}.
  973. Due to the way that chunks are compiled,
  974. the variable @id{_ENV} itself is never global @see{globalenv}.
  975. }
  976. @sect2{stats| @title{Statements}
  977. Lua supports an almost conventional set of @x{statements},
  978. similar to those in Pascal or C.
  979. This set includes
  980. assignments, control structures, function calls,
  981. and variable declarations.
  982. @sect3{@title{Blocks}
  983. A @x{block} is a list of statements,
  984. which are executed sequentially:
  985. @Produc{
  986. @producname{block}@producbody{@bnfrep{stat}}
  987. }
  988. Lua has @def{empty statements}
  989. that allow you to separate statements with semicolons,
  990. start a block with a semicolon
  991. or write two semicolons in sequence:
  992. @Produc{
  993. @producname{stat}@producbody{@bnfter{;}}
  994. }
  995. Function calls and assignments
  996. can start with an open parenthesis.
  997. This possibility leads to an ambiguity in Lua's grammar.
  998. Consider the following fragment:
  999. @verbatim{
  1000. a = b + c
  1001. (print or io.write)('done')
  1002. }
  1003. The grammar could see it in two ways:
  1004. @verbatim{
  1005. a = b + c(print or io.write)('done')
  1006. a = b + c; (print or io.write)('done')
  1007. }
  1008. The current parser always sees such constructions
  1009. in the first way,
  1010. interpreting the open parenthesis
  1011. as the start of the arguments to a call.
  1012. To avoid this ambiguity,
  1013. it is a good practice to always precede with a semicolon
  1014. statements that start with a parenthesis:
  1015. @verbatim{
  1016. ;(print or io.write)('done')
  1017. }
  1018. A block can be explicitly delimited to produce a single statement:
  1019. @Produc{
  1020. @producname{stat}@producbody{@Rw{do} block @Rw{end}}
  1021. }
  1022. Explicit blocks are useful
  1023. to control the scope of variable declarations.
  1024. Explicit blocks are also sometimes used to
  1025. add a @Rw{return} statement in the middle
  1026. of another block @see{control}.
  1027. }
  1028. @sect3{chunks| @title{Chunks}
  1029. The unit of compilation of Lua is called a @def{chunk}.
  1030. Syntactically,
  1031. a chunk is simply a block:
  1032. @Produc{
  1033. @producname{chunk}@producbody{block}
  1034. }
  1035. Lua handles a chunk as the body of an anonymous function
  1036. with a variable number of arguments
  1037. @see{func-def}.
  1038. As such, chunks can define local variables,
  1039. receive arguments, and return values.
  1040. Moreover, such anonymous function is compiled as in the
  1041. scope of an external local variable called @id{_ENV} @see{globalenv}.
  1042. The resulting function always has @id{_ENV} as its only upvalue,
  1043. even if it does not use that variable.
  1044. A chunk can be stored in a file or in a string inside the host program.
  1045. To execute a chunk,
  1046. Lua first @emph{loads} it,
  1047. precompiling the chunk's code into instructions for a virtual machine,
  1048. and then Lua executes the compiled code
  1049. with an interpreter for the virtual machine.
  1050. Chunks can also be precompiled into binary form;
  1051. see program @idx{luac} and function @Lid{string.dump} for details.
  1052. Programs in source and compiled forms are interchangeable;
  1053. Lua automatically detects the file type and acts accordingly @seeF{load}.
  1054. }
  1055. @sect3{assignment| @title{Assignment}
  1056. Lua allows @x{multiple assignments}.
  1057. Therefore, the syntax for assignment
  1058. defines a list of variables on the left side
  1059. and a list of expressions on the right side.
  1060. The elements in both lists are separated by commas:
  1061. @Produc{
  1062. @producname{stat}@producbody{varlist @bnfter{=} explist}
  1063. @producname{varlist}@producbody{var @bnfrep{@bnfter{,} var}}
  1064. @producname{explist}@producbody{exp @bnfrep{@bnfter{,} exp}}
  1065. }
  1066. Expressions are discussed in @See{expressions}.
  1067. Before the assignment,
  1068. the list of values is @emph{adjusted} to the length of
  1069. the list of variables.@index{adjustment}
  1070. If there are more values than needed,
  1071. the excess values are thrown away.
  1072. If there are fewer values than needed,
  1073. the list is extended with as many @nil's as needed.
  1074. If the list of expressions ends with a function call,
  1075. then all values returned by that call enter the list of values,
  1076. before the adjustment
  1077. (except when the call is enclosed in parentheses; see @See{expressions}).
  1078. The assignment statement first evaluates all its expressions
  1079. and only then the assignments are performed.
  1080. Thus the code
  1081. @verbatim{
  1082. i = 3
  1083. i, a[i] = i+1, 20
  1084. }
  1085. sets @T{a[3]} to 20, without affecting @T{a[4]}
  1086. because the @id{i} in @T{a[i]} is evaluated (to 3)
  1087. before it is @N{assigned 4}.
  1088. Similarly, the line
  1089. @verbatim{
  1090. x, y = y, x
  1091. }
  1092. exchanges the values of @id{x} and @id{y},
  1093. and
  1094. @verbatim{
  1095. x, y, z = y, z, x
  1096. }
  1097. cyclically permutes the values of @id{x}, @id{y}, and @id{z}.
  1098. An assignment to a global name @T{x = val}
  1099. is equivalent to the assignment
  1100. @T{_ENV.x = val} @see{globalenv}.
  1101. The meaning of assignments to table fields and
  1102. global variables (which are actually table fields, too)
  1103. can be changed via metatables @see{metatable}.
  1104. }
  1105. @sect3{control| @title{Control Structures}
  1106. The control structures
  1107. @Rw{if}, @Rw{while}, and @Rw{repeat} have the usual meaning and
  1108. familiar syntax:
  1109. @index{while-do statement}
  1110. @index{repeat-until statement}
  1111. @index{if-then-else statement}
  1112. @Produc{
  1113. @producname{stat}@producbody{@Rw{while} exp @Rw{do} block @Rw{end}}
  1114. @producname{stat}@producbody{@Rw{repeat} block @Rw{until} exp}
  1115. @producname{stat}@producbody{@Rw{if} exp @Rw{then} block
  1116. @bnfrep{@Rw{elseif} exp @Rw{then} block}
  1117. @bnfopt{@Rw{else} block} @Rw{end}}
  1118. }
  1119. Lua also has a @Rw{for} statement, in two flavors @see{for}.
  1120. The @x{condition expression} of a
  1121. control structure can return any value.
  1122. Both @false and @nil test false.
  1123. All values different from @nil and @false test true.
  1124. (In particular, the number 0 and the empty string also test true).
  1125. In the @Rw{repeat}@En@Rw{until} loop,
  1126. the inner block does not end at the @Rw{until} keyword,
  1127. but only after the condition.
  1128. So, the condition can refer to local variables
  1129. declared inside the loop block.
  1130. The @Rw{goto} statement transfers the program control to a label.
  1131. For syntactical reasons,
  1132. labels in Lua are considered statements too:
  1133. @index{goto statement}
  1134. @index{label}
  1135. @Produc{
  1136. @producname{stat}@producbody{@Rw{goto} Name}
  1137. @producname{stat}@producbody{label}
  1138. @producname{label}@producbody{@bnfter{::} Name @bnfter{::}}
  1139. }
  1140. A label is visible in the entire block where it is defined,
  1141. except inside nested functions.
  1142. A goto may jump to any visible label as long as it does not
  1143. enter into the scope of a local variable.
  1144. A label should not be declared
  1145. where a label with the same name is visible,
  1146. even if this other label has been declared in an enclosing block.
  1147. Labels and empty statements are called @def{void statements},
  1148. as they perform no actions.
  1149. The @Rw{break} statement terminates the execution of a
  1150. @Rw{while}, @Rw{repeat}, or @Rw{for} loop,
  1151. skipping to the next statement after the loop:
  1152. @index{break statement}
  1153. @Produc{
  1154. @producname{stat}@producbody{@Rw{break}}
  1155. }
  1156. A @Rw{break} ends the innermost enclosing loop.
  1157. The @Rw{return} statement is used to return values
  1158. from a function or a chunk
  1159. (which is an anonymous function).
  1160. @index{return statement}
  1161. Functions can return more than one value,
  1162. so the syntax for the @Rw{return} statement is
  1163. @Produc{
  1164. @producname{stat}@producbody{@Rw{return} @bnfopt{explist} @bnfopt{@bnfter{;}}}
  1165. }
  1166. The @Rw{return} statement can only be written
  1167. as the last statement of a block.
  1168. If it is really necessary to @Rw{return} in the middle of a block,
  1169. then an explicit inner block can be used,
  1170. as in the idiom @T{do return end},
  1171. because now @Rw{return} is the last statement in its (inner) block.
  1172. }
  1173. @sect3{for| @title{For Statement}
  1174. @index{for statement}
  1175. The @Rw{for} statement has two forms:
  1176. one numerical and one generic.
  1177. The numerical @Rw{for} loop repeats a block of code while a
  1178. control variable runs through an arithmetic progression.
  1179. It has the following syntax:
  1180. @Produc{
  1181. @producname{stat}@producbody{@Rw{for} @bnfNter{Name} @bnfter{=}
  1182. exp @bnfter{,} exp @bnfopt{@bnfter{,} exp} @Rw{do} block @Rw{end}}
  1183. }
  1184. The @emph{block} is repeated for @emph{name} starting at the value of
  1185. the first @emph{exp}, until it passes the second @emph{exp} by steps of the
  1186. third @emph{exp}.
  1187. More precisely, a @Rw{for} statement like
  1188. @verbatim{
  1189. for v = @rep{e1}, @rep{e2}, @rep{e3} do @rep{block} end
  1190. }
  1191. is equivalent to the code:
  1192. @verbatim{
  1193. do
  1194. local @rep{var}, @rep{limit}, @rep{step} = tonumber(@rep{e1}), tonumber(@rep{e2}), tonumber(@rep{e3})
  1195. if not (@rep{var} and @rep{limit} and @rep{step}) then error() end
  1196. @rep{var} = @rep{var} - @rep{step}
  1197. while true do
  1198. @rep{var} = @rep{var} + @rep{step}
  1199. if (@rep{step} >= 0 and @rep{var} > @rep{limit}) or (@rep{step} < 0 and @rep{var} < @rep{limit}) then
  1200. break
  1201. end
  1202. local v = @rep{var}
  1203. @rep{block}
  1204. end
  1205. end
  1206. }
  1207. Note the following:
  1208. @itemize{
  1209. @item{
  1210. All three control expressions are evaluated only once,
  1211. before the loop starts.
  1212. They must all result in numbers.
  1213. }
  1214. @item{
  1215. @T{@rep{var}}, @T{@rep{limit}}, and @T{@rep{step}} are invisible variables.
  1216. The names shown here are for explanatory purposes only.
  1217. }
  1218. @item{
  1219. If the third expression (the step) is absent,
  1220. then a step @N{of 1} is used.
  1221. }
  1222. @item{
  1223. You can use @Rw{break} and @Rw{goto} to exit a @Rw{for} loop.
  1224. }
  1225. @item{
  1226. The loop variable @T{v} is local to the loop body.
  1227. If you need its value after the loop,
  1228. assign it to another variable before exiting the loop.
  1229. }
  1230. @item{
  1231. The values in @rep{var}, @rep{limit}, and @rep{step}
  1232. can be integers or floats.
  1233. All operations on them respect the usual rules in Lua.
  1234. }
  1235. }
  1236. The generic @Rw{for} statement works over functions,
  1237. called @def{iterators}.
  1238. On each iteration, the iterator function is called to produce a new value,
  1239. stopping when this new value is @nil.
  1240. The generic @Rw{for} loop has the following syntax:
  1241. @Produc{
  1242. @producname{stat}@producbody{@Rw{for} namelist @Rw{in} explist
  1243. @Rw{do} block @Rw{end}}
  1244. @producname{namelist}@producbody{@bnfNter{Name} @bnfrep{@bnfter{,} @bnfNter{Name}}}
  1245. }
  1246. A @Rw{for} statement like
  1247. @verbatim{
  1248. for @rep{var_1}, @Cdots, @rep{var_n} in @rep{explist} do @rep{block} end
  1249. }
  1250. is equivalent to the code:
  1251. @verbatim{
  1252. do
  1253. local @rep{f}, @rep{s}, @rep{var}
  1254. local *toclose @rep{tbc} = nil
  1255. @rep{f}, @rep{s}, @rep{var}, @rep{tbc} = @rep{explist}
  1256. while true do
  1257. local @rep{var_1}, @Cdots, @rep{var_n} = @rep{f}(@rep{s}, @rep{var})
  1258. if @rep{var_1} == nil then break end
  1259. @rep{var} = @rep{var_1}
  1260. @rep{block}
  1261. end
  1262. end
  1263. }
  1264. Note the following:
  1265. @itemize{
  1266. @item{
  1267. @T{@rep{explist}} is evaluated only once.
  1268. Its results are an @emph{iterator} function,
  1269. a @emph{state},
  1270. an initial value for the first @emph{iterator variable},
  1271. and a to-be-closed variable @see{to-be-closed},
  1272. which can be used to release resources when the loop ends.
  1273. }
  1274. @item{
  1275. @T{@rep{f}}, @T{@rep{s}}, @T{@rep{var}}, and @T{@rep{tbc}}
  1276. are invisible variables.
  1277. The names are here for explanatory purposes only.
  1278. }
  1279. @item{
  1280. You can use @Rw{break} to exit a @Rw{for} loop.
  1281. }
  1282. @item{
  1283. The loop variables @T{@rep{var_i}} are local to the loop;
  1284. you cannot use their values after the @Rw{for} ends.
  1285. If you need these values,
  1286. then assign them to other variables before breaking or exiting the loop.
  1287. }
  1288. }
  1289. }
  1290. @sect3{funcstat| @title{Function Calls as Statements}
  1291. To allow possible side-effects,
  1292. function calls can be executed as statements:
  1293. @Produc{
  1294. @producname{stat}@producbody{functioncall}
  1295. }
  1296. In this case, all returned values are thrown away.
  1297. Function calls are explained in @See{functioncall}.
  1298. }
  1299. @sect3{localvar| @title{Local Declarations}
  1300. @x{Local variables} can be declared anywhere inside a block.
  1301. The declaration can include an initial assignment:
  1302. @Produc{
  1303. @producname{stat}@producbody{@Rw{local} namelist @bnfopt{@bnfter{=} explist}}
  1304. }
  1305. If present, an initial assignment has the same semantics
  1306. of a multiple assignment @see{assignment}.
  1307. Otherwise, all variables are initialized with @nil.
  1308. A chunk is also a block @see{chunks},
  1309. and so local variables can be declared in a chunk outside any explicit block.
  1310. The visibility rules for local variables are explained in @See{visibility}.
  1311. }
  1312. @sect3{to-be-closed| @title{To-be-closed Variables}
  1313. A local variable can be declared as a @def{to-be-closed} variable,
  1314. with the following syntax:
  1315. @Produc{
  1316. @producname{stat}@producbody{
  1317. @Rw{local} @bnfter{*} @bnfter{toclose} Name @bnfter{=} exp
  1318. }}
  1319. A to-be-closed variable behaves like a normal local variable,
  1320. except that its value is @emph{closed} whenever the variable
  1321. goes out of scope, including normal block termination,
  1322. exiting its block by @Rw{break}/@Rw{goto}/@Rw{return},
  1323. or exiting by an error.
  1324. Here, to @emph{close} a value means
  1325. to call its @idx{__close} metamethod.
  1326. If the value is @nil, it is ignored;
  1327. otherwise,
  1328. if it does not have a @idx{__close} metamethod,
  1329. an error is raised.
  1330. When calling the metamethod,
  1331. the value itself is passed as the first argument
  1332. and the error object (if any) is passed as a second argument;
  1333. if there was no error, the second argument is @nil.
  1334. If several to-be-closed variables go out of scope at the same event,
  1335. they are closed in the reverse order that they were declared.
  1336. If there is any error while running a closing method,
  1337. that error is handled like an error in the regular code
  1338. where the variable was defined;
  1339. in particular,
  1340. the other pending closing methods will still be called.
  1341. If a coroutine yields inside a block and is never resumed again,
  1342. the variables visible at that block will never go out of scope,
  1343. and therefore they will not be closed.
  1344. (You should use finalizers to handle this case.)
  1345. }
  1346. }
  1347. @sect2{expressions| @title{Expressions}
  1348. The basic expressions in Lua are the following:
  1349. @Produc{
  1350. @producname{exp}@producbody{prefixexp}
  1351. @producname{exp}@producbody{@Rw{nil} @Or @Rw{false} @Or @Rw{true}}
  1352. @producname{exp}@producbody{@bnfNter{Numeral}}
  1353. @producname{exp}@producbody{@bnfNter{LiteralString}}
  1354. @producname{exp}@producbody{functiondef}
  1355. @producname{exp}@producbody{tableconstructor}
  1356. @producname{exp}@producbody{@bnfter{...}}
  1357. @producname{exp}@producbody{exp binop exp}
  1358. @producname{exp}@producbody{unop exp}
  1359. @producname{prefixexp}@producbody{var @Or functioncall @Or
  1360. @bnfter{(} exp @bnfter{)}}
  1361. }
  1362. Numerals and literal strings are explained in @See{lexical};
  1363. variables are explained in @See{variables};
  1364. function definitions are explained in @See{func-def};
  1365. function calls are explained in @See{functioncall};
  1366. table constructors are explained in @See{tableconstructor}.
  1367. Vararg expressions,
  1368. denoted by three dots (@Char{...}), can only be used when
  1369. directly inside a vararg function;
  1370. they are explained in @See{func-def}.
  1371. Binary operators comprise arithmetic operators @see{arith},
  1372. bitwise operators @see{bitwise},
  1373. relational operators @see{rel-ops}, logical operators @see{logic},
  1374. and the concatenation operator @see{concat}.
  1375. Unary operators comprise the unary minus @see{arith},
  1376. the unary bitwise NOT @see{bitwise},
  1377. the unary logical @Rw{not} @see{logic},
  1378. and the unary @def{length operator} @see{len-op}.
  1379. Both function calls and vararg expressions can result in multiple values.
  1380. If a function call is used as a statement @see{funcstat},
  1381. then its return list is adjusted to zero elements,
  1382. thus discarding all returned values.
  1383. If an expression is used as the last (or the only) element
  1384. of a list of expressions,
  1385. then no adjustment is made
  1386. (unless the expression is enclosed in parentheses).
  1387. In all other contexts,
  1388. Lua adjusts the result list to one element,
  1389. either discarding all values except the first one
  1390. or adding a single @nil if there are no values.
  1391. Here are some examples:
  1392. @verbatim{
  1393. f() -- adjusted to 0 results
  1394. g(f(), x) -- f() is adjusted to 1 result
  1395. g(x, f()) -- g gets x plus all results from f()
  1396. a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
  1397. a,b = ... -- a gets the first vararg argument, b gets
  1398. -- the second (both a and b can get nil if there
  1399. -- is no corresponding vararg argument)
  1400. a,b,c = x, f() -- f() is adjusted to 2 results
  1401. a,b,c = f() -- f() is adjusted to 3 results
  1402. return f() -- returns all results from f()
  1403. return ... -- returns all received vararg arguments
  1404. return x,y,f() -- returns x, y, and all results from f()
  1405. {f()} -- creates a list with all results from f()
  1406. {...} -- creates a list with all vararg arguments
  1407. {f(), nil} -- f() is adjusted to 1 result
  1408. }
  1409. Any expression enclosed in parentheses always results in only one value.
  1410. Thus,
  1411. @T{(f(x,y,z))} is always a single value,
  1412. even if @id{f} returns several values.
  1413. (The value of @T{(f(x,y,z))} is the first value returned by @id{f}
  1414. or @nil if @id{f} does not return any values.)
  1415. @sect3{arith| @title{Arithmetic Operators}
  1416. Lua supports the following @x{arithmetic operators}:
  1417. @description{
  1418. @item{@T{+}|addition}
  1419. @item{@T{-}|subtraction}
  1420. @item{@T{*}|multiplication}
  1421. @item{@T{/}|float division}
  1422. @item{@T{//}|floor division}
  1423. @item{@T{%}|modulo}
  1424. @item{@T{^}|exponentiation}
  1425. @item{@T{-}|unary minus}
  1426. }
  1427. With the exception of exponentiation and float division,
  1428. the arithmetic operators work as follows:
  1429. If both operands are integers,
  1430. the operation is performed over integers and the result is an integer.
  1431. Otherwise, if both operands are numbers,
  1432. then they are converted to floats,
  1433. the operation is performed following the machine's rules
  1434. for floating-point arithmetic
  1435. (usually the @x{IEEE 754} standard),
  1436. and the result is a float.
  1437. (The string library coerces strings to numbers in
  1438. arithmetic operations; see @See{coercion} for details.)
  1439. Exponentiation and float division (@T{/})
  1440. always convert their operands to floats
  1441. and the result is always a float.
  1442. Exponentiation uses the @ANSI{pow},
  1443. so that it works for non-integer exponents too.
  1444. Floor division (@T{//}) is a division
  1445. that rounds the quotient towards minus infinity,
  1446. that is, the floor of the division of its operands.
  1447. Modulo is defined as the remainder of a division
  1448. that rounds the quotient towards minus infinity (floor division).
  1449. In case of overflows in integer arithmetic,
  1450. all operations @emphx{wrap around},
  1451. according to the usual rules of two-complement arithmetic.
  1452. (In other words,
  1453. they return the unique representable integer
  1454. that is equal modulo @M{2@sp{n}} to the mathematical result,
  1455. where @M{n} is the number of bits of the integer type.)
  1456. }
  1457. @sect3{bitwise| @title{Bitwise Operators}
  1458. Lua supports the following @x{bitwise operators}:
  1459. @description{
  1460. @item{@T{&}|bitwise AND}
  1461. @item{@T{@VerBar}|bitwise OR}
  1462. @item{@T{~}|bitwise exclusive OR}
  1463. @item{@T{>>}|right shift}
  1464. @item{@T{<<}|left shift}
  1465. @item{@T{~}|unary bitwise NOT}
  1466. }
  1467. All bitwise operations convert its operands to integers
  1468. @see{coercion},
  1469. operate on all bits of those integers,
  1470. and result in an integer.
  1471. Both right and left shifts fill the vacant bits with zeros.
  1472. Negative displacements shift to the other direction;
  1473. displacements with absolute values equal to or higher than
  1474. the number of bits in an integer
  1475. result in zero (as all bits are shifted out).
  1476. }
  1477. @sect3{coercion| @title{Coercions and Conversions}
  1478. Lua provides some automatic conversions between some
  1479. types and representations at run time.
  1480. Bitwise operators always convert float operands to integers.
  1481. Exponentiation and float division
  1482. always convert integer operands to floats.
  1483. All other arithmetic operations applied to mixed numbers
  1484. (integers and floats) convert the integer operand to a float.
  1485. The C API also converts both integers to floats and
  1486. floats to integers, as needed.
  1487. Moreover, string concatenation accepts numbers as arguments,
  1488. besides strings.
  1489. In a conversion from integer to float,
  1490. if the integer value has an exact representation as a float,
  1491. that is the result.
  1492. Otherwise,
  1493. the conversion gets the nearest higher or
  1494. the nearest lower representable value.
  1495. This kind of conversion never fails.
  1496. The conversion from float to integer
  1497. checks whether the float has an exact representation as an integer
  1498. (that is, the float has an integral value and
  1499. it is in the range of integer representation).
  1500. If it does, that representation is the result.
  1501. Otherwise, the conversion fails.
  1502. The string library uses metamethods that try to coerce
  1503. strings to numbers in all arithmetic operations.
  1504. Any string operator is converted to an integer or a float,
  1505. following its syntax and the rules of the Lua lexer.
  1506. (The string may have also leading and trailing spaces and a sign.)
  1507. All conversions from strings to numbers
  1508. accept both a dot and the current locale mark
  1509. as the radix character.
  1510. (The Lua lexer, however, accepts only a dot.)
  1511. The conversion from numbers to strings uses a
  1512. non-specified human-readable format.
  1513. For complete control over how numbers are converted to strings,
  1514. use the @id{format} function from the string library
  1515. @seeF{string.format}.
  1516. }
  1517. @sect3{rel-ops| @title{Relational Operators}
  1518. Lua supports the following @x{relational operators}:
  1519. @description{
  1520. @item{@T{==}|equality}
  1521. @item{@T{~=}|inequality}
  1522. @item{@T{<}|less than}
  1523. @item{@T{>}|greater than}
  1524. @item{@T{<=}|less or equal}
  1525. @item{@T{>=}|greater or equal}
  1526. }
  1527. These operators always result in @false or @true.
  1528. Equality (@T{==}) first compares the type of its operands.
  1529. If the types are different, then the result is @false.
  1530. Otherwise, the values of the operands are compared.
  1531. Strings are equal if they have the same content.
  1532. Numbers are equal if they denote the same mathematical value.
  1533. Tables, userdata, and threads
  1534. are compared by reference:
  1535. two objects are considered equal only if they are the same object.
  1536. Every time you create a new object
  1537. (a table, a userdata, or a thread),
  1538. this new object is different from any previously existing object.
  1539. A function is always equal to itself.
  1540. Functions with any detectable difference
  1541. (different behavior, different definition) are always different.
  1542. Functions created at different times but with no detectable differences
  1543. may be classified as equal or not
  1544. (depending on internal caching details).
  1545. You can change the way that Lua compares tables and userdata
  1546. by using the @idx{__eq} metamethod @see{metatable}.
  1547. Equality comparisons do not convert strings to numbers
  1548. or vice versa.
  1549. Thus, @T{"0"==0} evaluates to @false,
  1550. and @T{t[0]} and @T{t["0"]} denote different
  1551. entries in a table.
  1552. The operator @T{~=} is exactly the negation of equality (@T{==}).
  1553. The order operators work as follows.
  1554. If both arguments are numbers,
  1555. then they are compared according to their mathematical values
  1556. (regardless of their subtypes).
  1557. Otherwise, if both arguments are strings,
  1558. then their values are compared according to the current locale.
  1559. Otherwise, Lua tries to call the @idx{__lt} or the @idx{__le}
  1560. metamethod @see{metatable}.
  1561. A comparison @T{a > b} is translated to @T{b < a}
  1562. and @T{a >= b} is translated to @T{b <= a}.
  1563. Following the @x{IEEE 754} standard,
  1564. @x{NaN} is considered neither smaller than,
  1565. nor equal to, nor greater than any value (including itself).
  1566. }
  1567. @sect3{logic| @title{Logical Operators}
  1568. The @x{logical operators} in Lua are
  1569. @Rw{and}, @Rw{or}, and @Rw{not}.
  1570. Like the control structures @see{control},
  1571. all logical operators consider both @false and @nil as false
  1572. and anything else as true.
  1573. The negation operator @Rw{not} always returns @false or @true.
  1574. The conjunction operator @Rw{and} returns its first argument
  1575. if this value is @false or @nil;
  1576. otherwise, @Rw{and} returns its second argument.
  1577. The disjunction operator @Rw{or} returns its first argument
  1578. if this value is different from @nil and @false;
  1579. otherwise, @Rw{or} returns its second argument.
  1580. Both @Rw{and} and @Rw{or} use @x{short-circuit evaluation};
  1581. that is,
  1582. the second operand is evaluated only if necessary.
  1583. Here are some examples:
  1584. @verbatim{
  1585. 10 or 20 --> 10
  1586. 10 or error() --> 10
  1587. nil or "a" --> "a"
  1588. nil and 10 --> nil
  1589. false and error() --> false
  1590. false and nil --> false
  1591. false or nil --> nil
  1592. 10 and 20 --> 20
  1593. }
  1594. }
  1595. @sect3{concat| @title{Concatenation}
  1596. The string @x{concatenation} operator in Lua is
  1597. denoted by two dots (@Char{..}).
  1598. If both operands are strings or numbers, then they are converted to
  1599. strings according to the rules described in @See{coercion}.
  1600. Otherwise, the @idx{__concat} metamethod is called @see{metatable}.
  1601. }
  1602. @sect3{len-op| @title{The Length Operator}
  1603. The length operator is denoted by the unary prefix operator @T{#}.
  1604. The length of a string is its number of bytes
  1605. (that is, the usual meaning of string length when each
  1606. character is one byte).
  1607. The length operator applied on a table
  1608. returns a @x{border} in that table.
  1609. A @def{border} in a table @id{t} is any natural number
  1610. that satisfies the following condition:
  1611. @verbatim{
  1612. (border == 0 or t[border] ~= nil) and t[border + 1] == nil
  1613. }
  1614. In words,
  1615. a border is any (natural) index present in the table
  1616. that is followed by an absent index
  1617. (or zero, when index 1 is absent).
  1618. A table with exactly one border is called a @def{sequence}.
  1619. For instance, the table @T{{10, 20, 30, 40, 50}} is a sequence,
  1620. as it has only one border (5).
  1621. The table @T{{10, 20, 30, nil, 50}} has two borders (3 and 5),
  1622. and therefore it is not a sequence.
  1623. The table @T{{nil, 20, 30, nil, nil, 60, nil}}
  1624. has three borders (0, 3, and 6),
  1625. so it is not a sequence, too.
  1626. The table @T{{}} is a sequence with border 0.
  1627. Note that non-natural keys do not interfere
  1628. with whether a table is a sequence.
  1629. When @id{t} is a sequence,
  1630. @T{#t} returns its only border,
  1631. which corresponds to the intuitive notion of the length of the sequence.
  1632. When @id{t} is not a sequence,
  1633. @T{#t} can return any of its borders.
  1634. (The exact one depends on details of
  1635. the internal representation of the table,
  1636. which in turn can depend on how the table was populated and
  1637. the memory addresses of its non-numeric keys.)
  1638. The computation of the length of a table
  1639. has a guaranteed worst time of @M{O(log n)},
  1640. where @M{n} is the largest natural key in the table.
  1641. A program can modify the behavior of the length operator for
  1642. any value but strings through the @idx{__len} metamethod @see{metatable}.
  1643. }
  1644. @sect3{prec| @title{Precedence}
  1645. @x{Operator precedence} in Lua follows the table below,
  1646. from lower to higher priority:
  1647. @verbatim{
  1648. or
  1649. and
  1650. < > <= >= ~= ==
  1651. |
  1652. ~
  1653. &
  1654. << >>
  1655. ..
  1656. + -
  1657. * / // %
  1658. unary operators (not # - ~)
  1659. ^
  1660. }
  1661. As usual,
  1662. you can use parentheses to change the precedences of an expression.
  1663. The concatenation (@Char{..}) and exponentiation (@Char{^})
  1664. operators are right associative.
  1665. All other binary operators are left associative.
  1666. }
  1667. @sect3{tableconstructor| @title{Table Constructors}
  1668. Table @x{constructors} are expressions that create tables.
  1669. Every time a constructor is evaluated, a new table is created.
  1670. A constructor can be used to create an empty table
  1671. or to create a table and initialize some of its fields.
  1672. The general syntax for constructors is
  1673. @Produc{
  1674. @producname{tableconstructor}@producbody{@bnfter{@Open} @bnfopt{fieldlist} @bnfter{@Close}}
  1675. @producname{fieldlist}@producbody{field @bnfrep{fieldsep field} @bnfopt{fieldsep}}
  1676. @producname{field}@producbody{@bnfter{[} exp @bnfter{]} @bnfter{=} exp @Or
  1677. @bnfNter{Name} @bnfter{=} exp @Or exp}
  1678. @producname{fieldsep}@producbody{@bnfter{,} @Or @bnfter{;}}
  1679. }
  1680. Each field of the form @T{[exp1] = exp2} adds to the new table an entry
  1681. with key @id{exp1} and value @id{exp2}.
  1682. A field of the form @T{name = exp} is equivalent to
  1683. @T{["name"] = exp}.
  1684. Finally, fields of the form @id{exp} are equivalent to
  1685. @T{[i] = exp}, where @id{i} are consecutive integers
  1686. starting with 1.
  1687. Fields in the other formats do not affect this counting.
  1688. For example,
  1689. @verbatim{
  1690. a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
  1691. }
  1692. is equivalent to
  1693. @verbatim{
  1694. do
  1695. local t = {}
  1696. t[f(1)] = g
  1697. t[1] = "x" -- 1st exp
  1698. t[2] = "y" -- 2nd exp
  1699. t.x = 1 -- t["x"] = 1
  1700. t[3] = f(x) -- 3rd exp
  1701. t[30] = 23
  1702. t[4] = 45 -- 4th exp
  1703. a = t
  1704. end
  1705. }
  1706. The order of the assignments in a constructor is undefined.
  1707. (This order would be relevant only when there are repeated keys.)
  1708. If the last field in the list has the form @id{exp}
  1709. and the expression is a function call or a vararg expression,
  1710. then all values returned by this expression enter the list consecutively
  1711. @see{functioncall}.
  1712. The field list can have an optional trailing separator,
  1713. as a convenience for machine-generated code.
  1714. }
  1715. @sect3{functioncall| @title{Function Calls}
  1716. A @x{function call} in Lua has the following syntax:
  1717. @Produc{
  1718. @producname{functioncall}@producbody{prefixexp args}
  1719. }
  1720. In a function call,
  1721. first @bnfNter{prefixexp} and @bnfNter{args} are evaluated.
  1722. If the value of @bnfNter{prefixexp} has type @emph{function},
  1723. then this function is called
  1724. with the given arguments.
  1725. Otherwise, the @bnfNter{prefixexp} @idx{__call} metamethod is called,
  1726. having as first argument the value of @bnfNter{prefixexp},
  1727. followed by the original call arguments
  1728. @see{metatable}.
  1729. The form
  1730. @Produc{
  1731. @producname{functioncall}@producbody{prefixexp @bnfter{:} @bnfNter{Name} args}
  1732. }
  1733. can be used to call @Q{methods}.
  1734. A call @T{v:name(@rep{args})}
  1735. is syntactic sugar for @T{v.name(v,@rep{args})},
  1736. except that @id{v} is evaluated only once.
  1737. Arguments have the following syntax:
  1738. @Produc{
  1739. @producname{args}@producbody{@bnfter{(} @bnfopt{explist} @bnfter{)}}
  1740. @producname{args}@producbody{tableconstructor}
  1741. @producname{args}@producbody{@bnfNter{LiteralString}}
  1742. }
  1743. All argument expressions are evaluated before the call.
  1744. A call of the form @T{f{@rep{fields}}} is
  1745. syntactic sugar for @T{f({@rep{fields}})};
  1746. that is, the argument list is a single new table.
  1747. A call of the form @T{f'@rep{string}'}
  1748. (or @T{f"@rep{string}"} or @T{f[[@rep{string}]]})
  1749. is syntactic sugar for @T{f('@rep{string}')};
  1750. that is, the argument list is a single literal string.
  1751. A call of the form @T{return @rep{functioncall}} not in the
  1752. scope of a to-be-closed variable is called a @def{tail call}.
  1753. Lua implements @def{proper tail calls}
  1754. (or @emph{proper tail recursion}):
  1755. in a tail call,
  1756. the called function reuses the stack entry of the calling function.
  1757. Therefore, there is no limit on the number of nested tail calls that
  1758. a program can execute.
  1759. However, a tail call erases any debug information about the
  1760. calling function.
  1761. Note that a tail call only happens with a particular syntax,
  1762. where the @Rw{return} has one single function call as argument,
  1763. and it is outside the scope of any to-be-closed variable.
  1764. This syntax makes the calling function return exactly
  1765. the returns of the called function,
  1766. without any intervening action.
  1767. So, none of the following examples are tail calls:
  1768. @verbatim{
  1769. return (f(x)) -- results adjusted to 1
  1770. return 2 * f(x) -- result multiplied by 2
  1771. return x, f(x) -- additional results
  1772. f(x); return -- results discarded
  1773. return x or f(x) -- results adjusted to 1
  1774. }
  1775. }
  1776. @sect3{func-def| @title{Function Definitions}
  1777. The syntax for function definition is
  1778. @Produc{
  1779. @producname{functiondef}@producbody{@Rw{function} funcbody}
  1780. @producname{funcbody}@producbody{@bnfter{(} @bnfopt{parlist} @bnfter{)} block @Rw{end}}
  1781. }
  1782. The following syntactic sugar simplifies function definitions:
  1783. @Produc{
  1784. @producname{stat}@producbody{@Rw{function} funcname funcbody}
  1785. @producname{stat}@producbody{@Rw{local} @Rw{function} @bnfNter{Name} funcbody}
  1786. @producname{funcname}@producbody{@bnfNter{Name} @bnfrep{@bnfter{.} @bnfNter{Name}} @bnfopt{@bnfter{:} @bnfNter{Name}}}
  1787. }
  1788. The statement
  1789. @verbatim{
  1790. function f () @rep{body} end
  1791. }
  1792. translates to
  1793. @verbatim{
  1794. f = function () @rep{body} end
  1795. }
  1796. The statement
  1797. @verbatim{
  1798. function t.a.b.c.f () @rep{body} end
  1799. }
  1800. translates to
  1801. @verbatim{
  1802. t.a.b.c.f = function () @rep{body} end
  1803. }
  1804. The statement
  1805. @verbatim{
  1806. local function f () @rep{body} end
  1807. }
  1808. translates to
  1809. @verbatim{
  1810. local f; f = function () @rep{body} end
  1811. }
  1812. not to
  1813. @verbatim{
  1814. local f = function () @rep{body} end
  1815. }
  1816. (This only makes a difference when the body of the function
  1817. contains references to @id{f}.)
  1818. A function definition is an executable expression,
  1819. whose value has type @emph{function}.
  1820. When Lua precompiles a chunk,
  1821. all its function bodies are precompiled too.
  1822. Then, whenever Lua executes the function definition,
  1823. the function is @emph{instantiated} (or @emph{closed}).
  1824. This function instance (or @emphx{closure})
  1825. is the final value of the expression.
  1826. Parameters act as local variables that are
  1827. initialized with the argument values:
  1828. @Produc{
  1829. @producname{parlist}@producbody{namelist @bnfopt{@bnfter{,} @bnfter{...}} @Or
  1830. @bnfter{...}}
  1831. }
  1832. When a Lua function is called,
  1833. it adjusts its list of @x{arguments} to
  1834. the length of its list of parameters,
  1835. unless the function is a @def{vararg function},
  1836. which is indicated by three dots (@Char{...})
  1837. at the end of its parameter list.
  1838. A vararg function does not adjust its argument list;
  1839. instead, it collects all extra arguments and supplies them
  1840. to the function through a @def{vararg expression},
  1841. which is also written as three dots.
  1842. The value of this expression is a list of all actual extra arguments,
  1843. similar to a function with multiple results.
  1844. If a vararg expression is used inside another expression
  1845. or in the middle of a list of expressions,
  1846. then its return list is adjusted to one element.
  1847. If the expression is used as the last element of a list of expressions,
  1848. then no adjustment is made
  1849. (unless that last expression is enclosed in parentheses).
  1850. As an example, consider the following definitions:
  1851. @verbatim{
  1852. function f(a, b) end
  1853. function g(a, b, ...) end
  1854. function r() return 1,2,3 end
  1855. }
  1856. Then, we have the following mapping from arguments to parameters and
  1857. to the vararg expression:
  1858. @verbatim{
  1859. CALL PARAMETERS
  1860. f(3) a=3, b=nil
  1861. f(3, 4) a=3, b=4
  1862. f(3, 4, 5) a=3, b=4
  1863. f(r(), 10) a=1, b=10
  1864. f(r()) a=1, b=2
  1865. g(3) a=3, b=nil, ... --> (nothing)
  1866. g(3, 4) a=3, b=4, ... --> (nothing)
  1867. g(3, 4, 5, 8) a=3, b=4, ... --> 5 8
  1868. g(5, r()) a=5, b=1, ... --> 2 3
  1869. }
  1870. Results are returned using the @Rw{return} statement @see{control}.
  1871. If control reaches the end of a function
  1872. without encountering a @Rw{return} statement,
  1873. then the function returns with no results.
  1874. @index{multiple return}
  1875. There is a system-dependent limit on the number of values
  1876. that a function may return.
  1877. This limit is guaranteed to be larger than 1000.
  1878. The @emphx{colon} syntax
  1879. is used for defining @def{methods},
  1880. that is, functions that have an implicit extra parameter @idx{self}.
  1881. Thus, the statement
  1882. @verbatim{
  1883. function t.a.b.c:f (@rep{params}) @rep{body} end
  1884. }
  1885. is syntactic sugar for
  1886. @verbatim{
  1887. t.a.b.c.f = function (self, @rep{params}) @rep{body} end
  1888. }
  1889. }
  1890. }
  1891. @sect2{visibility| @title{Visibility Rules}
  1892. @index{visibility}
  1893. Lua is a lexically scoped language.
  1894. The scope of a local variable begins at the first statement after
  1895. its declaration and lasts until the last non-void statement
  1896. of the innermost block that includes the declaration.
  1897. Consider the following example:
  1898. @verbatim{
  1899. x = 10 -- global variable
  1900. do -- new block
  1901. local x = x -- new 'x', with value 10
  1902. print(x) --> 10
  1903. x = x+1
  1904. do -- another block
  1905. local x = x+1 -- another 'x'
  1906. print(x) --> 12
  1907. end
  1908. print(x) --> 11
  1909. end
  1910. print(x) --> 10 (the global one)
  1911. }
  1912. Notice that, in a declaration like @T{local x = x},
  1913. the new @id{x} being declared is not in scope yet,
  1914. and so the second @id{x} refers to the outside variable.
  1915. Because of the @x{lexical scoping} rules,
  1916. local variables can be freely accessed by functions
  1917. defined inside their scope.
  1918. A local variable used by an inner function is called
  1919. an @def{upvalue}, or @emphx{external local variable},
  1920. inside the inner function.
  1921. Notice that each execution of a @Rw{local} statement
  1922. defines new local variables.
  1923. Consider the following example:
  1924. @verbatim{
  1925. a = {}
  1926. local x = 20
  1927. for i=1,10 do
  1928. local y = 0
  1929. a[i] = function () y=y+1; return x+y end
  1930. end
  1931. }
  1932. The loop creates ten closures
  1933. (that is, ten instances of the anonymous function).
  1934. Each of these closures uses a different @id{y} variable,
  1935. while all of them share the same @id{x}.
  1936. }
  1937. }
  1938. @C{-------------------------------------------------------------------------}
  1939. @sect1{API| @title{The Application Program Interface}
  1940. @index{C API}
  1941. This section describes the @N{C API} for Lua, that is,
  1942. the set of @N{C functions} available to the host program to communicate
  1943. with Lua.
  1944. All API functions and related types and constants
  1945. are declared in the header file @defid{lua.h}.
  1946. Even when we use the term @Q{function},
  1947. any facility in the API may be provided as a macro instead.
  1948. Except where stated otherwise,
  1949. all such macros use each of their arguments exactly once
  1950. (except for the first argument, which is always a Lua state),
  1951. and so do not generate any hidden side-effects.
  1952. As in most @N{C libraries},
  1953. the Lua API functions do not check their arguments
  1954. for validity or consistency.
  1955. However, you can change this behavior by compiling Lua
  1956. with the macro @defid{LUA_USE_APICHECK} defined.
  1957. The Lua library is fully reentrant:
  1958. it has no global variables.
  1959. It keeps all information it needs in a dynamic structure,
  1960. called the @def{Lua state}.
  1961. Each Lua state has one or more threads,
  1962. which correspond to independent, cooperative lines of execution.
  1963. The type @Lid{lua_State} (despite its name) refers to a thread.
  1964. (Indirectly, through the thread, it also refers to the
  1965. Lua state associated to the thread.)
  1966. A pointer to a thread must be passed as the first argument to
  1967. every function in the library, except to @Lid{lua_newstate},
  1968. which creates a Lua state from scratch and returns a pointer
  1969. to the @emph{main thread} in the new state.
  1970. @sect2{@title{The Stack}
  1971. Lua uses a @emph{virtual stack} to pass values to and from C.
  1972. Each element in this stack represents a Lua value
  1973. (@nil, number, string, etc.).
  1974. Functions in the API can access this stack through the
  1975. Lua state parameter that they receive.
  1976. Whenever Lua calls C, the called function gets a new stack,
  1977. which is independent of previous stacks and of stacks of
  1978. @N{C functions} that are still active.
  1979. This stack initially contains any arguments to the @N{C function}
  1980. and it is where the @N{C function} can store temporary
  1981. Lua values and must push its results
  1982. to be returned to the caller @seeC{lua_CFunction}.
  1983. For convenience,
  1984. most query operations in the API do not follow a strict stack discipline.
  1985. Instead, they can refer to any element in the stack
  1986. by using an @emph{index}:@index{index (API stack)}
  1987. A positive index represents an absolute stack position
  1988. (starting @N{at 1});
  1989. a negative index represents an offset relative to the top of the stack.
  1990. More specifically, if the stack has @rep{n} elements,
  1991. then @N{index 1} represents the first element
  1992. (that is, the element that was pushed onto the stack first)
  1993. and
  1994. @N{index @rep{n}} represents the last element;
  1995. @N{index @num{-1}} also represents the last element
  1996. (that is, the element at @N{the top})
  1997. and index @M{-n} represents the first element.
  1998. }
  1999. @sect2{stacksize| @title{Stack Size}
  2000. When you interact with the Lua API,
  2001. you are responsible for ensuring consistency.
  2002. In particular,
  2003. @emph{you are responsible for controlling stack overflow}.
  2004. You can use the function @Lid{lua_checkstack}
  2005. to ensure that the stack has enough space for pushing new elements.
  2006. Whenever Lua calls C,
  2007. it ensures that the stack has space for
  2008. at least @defid{LUA_MINSTACK} extra slots.
  2009. @id{LUA_MINSTACK} is defined as 20,
  2010. so that usually you do not have to worry about stack space
  2011. unless your code has loops pushing elements onto the stack.
  2012. When you call a Lua function
  2013. without a fixed number of results @seeF{lua_call},
  2014. Lua ensures that the stack has enough space for all results,
  2015. but it does not ensure any extra space.
  2016. So, before pushing anything in the stack after such a call
  2017. you should use @Lid{lua_checkstack}.
  2018. }
  2019. @sect2{@title{Valid and Acceptable Indices}
  2020. Any function in the API that receives stack indices
  2021. works only with @emphx{valid indices} or @emphx{acceptable indices}.
  2022. A @def{valid index} is an index that refers to a
  2023. position that stores a modifiable Lua value.
  2024. It comprises stack indices @N{between 1} and the stack top
  2025. (@T{1 @leq abs(index) @leq top})
  2026. @index{stack index}
  2027. plus @def{pseudo-indices},
  2028. which represent some positions that are accessible to @N{C code}
  2029. but that are not in the stack.
  2030. Pseudo-indices are used to access the registry @see{registry}
  2031. and the upvalues of a @N{C function} @see{c-closure}.
  2032. Functions that do not need a specific mutable position,
  2033. but only a value (e.g., query functions),
  2034. can be called with acceptable indices.
  2035. An @def{acceptable index} can be any valid index,
  2036. but it also can be any positive index after the stack top
  2037. within the space allocated for the stack,
  2038. that is, indices up to the stack size.
  2039. (Note that 0 is never an acceptable index.)
  2040. Indices to upvalues @see{c-closure} larger than the real number
  2041. of upvalues in the current @N{C function} are also acceptable (but invalid).
  2042. Except when noted otherwise,
  2043. functions in the API work with acceptable indices.
  2044. Acceptable indices serve to avoid extra tests
  2045. against the stack top when querying the stack.
  2046. For instance, a @N{C function} can query its third argument
  2047. without the need to first check whether there is a third argument,
  2048. that is, without the need to check whether 3 is a valid index.
  2049. For functions that can be called with acceptable indices,
  2050. any non-valid index is treated as if it
  2051. contains a value of a virtual type @defid{LUA_TNONE},
  2052. which behaves like a nil value.
  2053. }
  2054. @sect2{c-closure| @title{C Closures}
  2055. When a @N{C function} is created,
  2056. it is possible to associate some values with it,
  2057. thus creating a @def{@N{C closure}}
  2058. @seeC{lua_pushcclosure};
  2059. these values are called @def{upvalues} and are
  2060. accessible to the function whenever it is called.
  2061. Whenever a @N{C function} is called,
  2062. its upvalues are located at specific pseudo-indices.
  2063. These pseudo-indices are produced by the macro
  2064. @Lid{lua_upvalueindex}.
  2065. The first upvalue associated with a function is at index
  2066. @T{lua_upvalueindex(1)}, and so on.
  2067. Any access to @T{lua_upvalueindex(@rep{n})},
  2068. where @rep{n} is greater than the number of upvalues of the
  2069. current function
  2070. (but not greater than 256,
  2071. which is one plus the maximum number of upvalues in a closure),
  2072. produces an acceptable but invalid index.
  2073. A @N{C closure} can also change the values of its corresponding upvalues.
  2074. }
  2075. @sect2{registry| @title{Registry}
  2076. Lua provides a @def{registry},
  2077. a predefined table that can be used by any @N{C code} to
  2078. store whatever Lua values it needs to store.
  2079. The registry table is always located at pseudo-index
  2080. @defid{LUA_REGISTRYINDEX}.
  2081. Any @N{C library} can store data into this table,
  2082. but it must take care to choose keys
  2083. that are different from those used
  2084. by other libraries, to avoid collisions.
  2085. Typically, you should use as key a string containing your library name,
  2086. or a light userdata with the address of a @N{C object} in your code,
  2087. or any Lua object created by your code.
  2088. As with variable names,
  2089. string keys starting with an underscore followed by
  2090. uppercase letters are reserved for Lua.
  2091. The integer keys in the registry are used
  2092. by the reference mechanism @seeC{luaL_ref}
  2093. and by some predefined values.
  2094. Therefore, integer keys must not be used for other purposes.
  2095. When you create a new Lua state,
  2096. its registry comes with some predefined values.
  2097. These predefined values are indexed with integer keys
  2098. defined as constants in @id{lua.h}.
  2099. The following constants are defined:
  2100. @description{
  2101. @item{@defid{LUA_RIDX_MAINTHREAD}| At this index the registry has
  2102. the main thread of the state.
  2103. (The main thread is the one created together with the state.)
  2104. }
  2105. @item{@defid{LUA_RIDX_GLOBALS}| At this index the registry has
  2106. the @x{global environment}.
  2107. }
  2108. }
  2109. }
  2110. @sect2{C-error|@title{Error Handling in C}
  2111. Internally, Lua uses the C @id{longjmp} facility to handle errors.
  2112. (Lua will use exceptions if you compile it as C++;
  2113. search for @id{LUAI_THROW} in the source code for details.)
  2114. When Lua faces any error
  2115. (such as a @x{memory allocation error} or a type error)
  2116. it @emph{raises} an error;
  2117. that is, it does a long jump.
  2118. A @emphx{protected environment} uses @id{setjmp}
  2119. to set a recovery point;
  2120. any error jumps to the most recent active recovery point.
  2121. Inside a @N{C function} you can raise an error by calling @Lid{lua_error}.
  2122. Most functions in the API can raise an error,
  2123. for instance due to a @x{memory allocation error}.
  2124. The documentation for each function indicates whether
  2125. it can raise errors.
  2126. If an error happens outside any protected environment,
  2127. Lua calls a @def{panic function} (see @Lid{lua_atpanic})
  2128. and then calls @T{abort},
  2129. thus exiting the host application.
  2130. Your panic function can avoid this exit by
  2131. never returning
  2132. (e.g., doing a long jump to your own recovery point outside Lua).
  2133. The panic function,
  2134. as its name implies,
  2135. is a mechanism of last resort.
  2136. Programs should avoid it.
  2137. As a general rule,
  2138. when a @N{C function} is called by Lua with a Lua state,
  2139. it can do whatever it wants on that Lua state,
  2140. as it should be already protected.
  2141. However,
  2142. when C code operates on other Lua states
  2143. (e.g., a Lua-state argument to the function,
  2144. a Lua state stored in the registry, or
  2145. the result of @Lid{lua_newthread}),
  2146. it should use them only in API calls that cannot raise errors.
  2147. The panic function runs as if it were a @x{message handler} @see{error};
  2148. in particular, the error object is on the top of the stack.
  2149. However, there is no guarantee about stack space.
  2150. To push anything on the stack,
  2151. the panic function must first check the available space @see{stacksize}.
  2152. }
  2153. @sect2{continuations|@title{Handling Yields in C}
  2154. Internally, Lua uses the C @id{longjmp} facility to yield a coroutine.
  2155. Therefore, if a @N{C function} @id{foo} calls an API function
  2156. and this API function yields
  2157. (directly or indirectly by calling another function that yields),
  2158. Lua cannot return to @id{foo} any more,
  2159. because the @id{longjmp} removes its frame from the C stack.
  2160. To avoid this kind of problem,
  2161. Lua raises an error whenever it tries to yield across an API call,
  2162. except for three functions:
  2163. @Lid{lua_yieldk}, @Lid{lua_callk}, and @Lid{lua_pcallk}.
  2164. All those functions receive a @def{continuation function}
  2165. (as a parameter named @id{k}) to continue execution after a yield.
  2166. We need to set some terminology to explain continuations.
  2167. We have a @N{C function} called from Lua which we will call
  2168. the @emph{original function}.
  2169. This original function then calls one of those three functions in the C API,
  2170. which we will call the @emph{callee function},
  2171. that then yields the current thread.
  2172. (This can happen when the callee function is @Lid{lua_yieldk},
  2173. or when the callee function is either @Lid{lua_callk} or @Lid{lua_pcallk}
  2174. and the function called by them yields.)
  2175. Suppose the running thread yields while executing the callee function.
  2176. After the thread resumes,
  2177. it eventually will finish running the callee function.
  2178. However,
  2179. the callee function cannot return to the original function,
  2180. because its frame in the C stack was destroyed by the yield.
  2181. Instead, Lua calls a @def{continuation function},
  2182. which was given as an argument to the callee function.
  2183. As the name implies,
  2184. the continuation function should continue the task
  2185. of the original function.
  2186. As an illustration, consider the following function:
  2187. @verbatim{
  2188. int original_function (lua_State *L) {
  2189. ... /* code 1 */
  2190. status = lua_pcall(L, n, m, h); /* calls Lua */
  2191. ... /* code 2 */
  2192. }
  2193. }
  2194. Now we want to allow
  2195. the Lua code being run by @Lid{lua_pcall} to yield.
  2196. First, we can rewrite our function like here:
  2197. @verbatim{
  2198. int k (lua_State *L, int status, lua_KContext ctx) {
  2199. ... /* code 2 */
  2200. }
  2201. int original_function (lua_State *L) {
  2202. ... /* code 1 */
  2203. return k(L, lua_pcall(L, n, m, h), ctx);
  2204. }
  2205. }
  2206. In the above code,
  2207. the new function @id{k} is a
  2208. @emph{continuation function} (with type @Lid{lua_KFunction}),
  2209. which should do all the work that the original function
  2210. was doing after calling @Lid{lua_pcall}.
  2211. Now, we must inform Lua that it must call @id{k} if the Lua code
  2212. being executed by @Lid{lua_pcall} gets interrupted in some way
  2213. (errors or yielding),
  2214. so we rewrite the code as here,
  2215. replacing @Lid{lua_pcall} by @Lid{lua_pcallk}:
  2216. @verbatim{
  2217. int original_function (lua_State *L) {
  2218. ... /* code 1 */
  2219. return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
  2220. }
  2221. }
  2222. Note the external, explicit call to the continuation:
  2223. Lua will call the continuation only if needed, that is,
  2224. in case of errors or resuming after a yield.
  2225. If the called function returns normally without ever yielding,
  2226. @Lid{lua_pcallk} (and @Lid{lua_callk}) will also return normally.
  2227. (Of course, instead of calling the continuation in that case,
  2228. you can do the equivalent work directly inside the original function.)
  2229. Besides the Lua state,
  2230. the continuation function has two other parameters:
  2231. the final status of the call plus the context value (@id{ctx}) that
  2232. was passed originally to @Lid{lua_pcallk}.
  2233. (Lua does not use this context value;
  2234. it only passes this value from the original function to the
  2235. continuation function.)
  2236. For @Lid{lua_pcallk},
  2237. the status is the same value that would be returned by @Lid{lua_pcallk},
  2238. except that it is @Lid{LUA_YIELD} when being executed after a yield
  2239. (instead of @Lid{LUA_OK}).
  2240. For @Lid{lua_yieldk} and @Lid{lua_callk},
  2241. the status is always @Lid{LUA_YIELD} when Lua calls the continuation.
  2242. (For these two functions,
  2243. Lua will not call the continuation in case of errors,
  2244. because they do not handle errors.)
  2245. Similarly, when using @Lid{lua_callk},
  2246. you should call the continuation function
  2247. with @Lid{LUA_OK} as the status.
  2248. (For @Lid{lua_yieldk}, there is not much point in calling
  2249. directly the continuation function,
  2250. because @Lid{lua_yieldk} usually does not return.)
  2251. Lua treats the continuation function as if it were the original function.
  2252. The continuation function receives the same Lua stack
  2253. from the original function,
  2254. in the same state it would be if the callee function had returned.
  2255. (For instance,
  2256. after a @Lid{lua_callk} the function and its arguments are
  2257. removed from the stack and replaced by the results from the call.)
  2258. It also has the same upvalues.
  2259. Whatever it returns is handled by Lua as if it were the return
  2260. of the original function.
  2261. }
  2262. @sect2{@title{Functions and Types}
  2263. Here we list all functions and types from the @N{C API} in
  2264. alphabetical order.
  2265. Each function has an indicator like this:
  2266. @apii{o,p,x}
  2267. The first field, @T{o},
  2268. is how many elements the function pops from the stack.
  2269. The second field, @T{p},
  2270. is how many elements the function pushes onto the stack.
  2271. (Any function always pushes its results after popping its arguments.)
  2272. A field in the form @T{x|y} means the function can push (or pop)
  2273. @T{x} or @T{y} elements,
  2274. depending on the situation;
  2275. an interrogation mark @Char{?} means that
  2276. we cannot know how many elements the function pops/pushes
  2277. by looking only at its arguments
  2278. (e.g., they may depend on what is on the stack).
  2279. The third field, @T{x},
  2280. tells whether the function may raise errors:
  2281. @Char{-} means the function never raises any error;
  2282. @Char{m} means the function may raise only out-of-memory errors;
  2283. @Char{v} means the function may raise the errors explained in the text;
  2284. @Char{e} means the function can run arbitrary Lua code,
  2285. either directly or through metamethods,
  2286. and therefore may raise any errors.
  2287. @APIEntry{int lua_absindex (lua_State *L, int idx);|
  2288. @apii{0,0,-}
  2289. Converts the @x{acceptable index} @id{idx}
  2290. into an equivalent @x{absolute index}
  2291. (that is, one that does not depend on the stack top).
  2292. }
  2293. @APIEntry{
  2294. typedef void * (*lua_Alloc) (void *ud,
  2295. void *ptr,
  2296. size_t osize,
  2297. size_t nsize);|
  2298. The type of the @x{memory-allocation function} used by Lua states.
  2299. The allocator function must provide a
  2300. functionality similar to @id{realloc},
  2301. but not exactly the same.
  2302. Its arguments are
  2303. @id{ud}, an opaque pointer passed to @Lid{lua_newstate};
  2304. @id{ptr}, a pointer to the block being allocated/reallocated/freed;
  2305. @id{osize}, the original size of the block or some code about what
  2306. is being allocated;
  2307. and @id{nsize}, the new size of the block.
  2308. When @id{ptr} is not @id{NULL},
  2309. @id{osize} is the size of the block pointed by @id{ptr},
  2310. that is, the size given when it was allocated or reallocated.
  2311. When @id{ptr} is @id{NULL},
  2312. @id{osize} encodes the kind of object that Lua is allocating.
  2313. @id{osize} is any of
  2314. @Lid{LUA_TSTRING}, @Lid{LUA_TTABLE}, @Lid{LUA_TFUNCTION},
  2315. @Lid{LUA_TUSERDATA}, or @Lid{LUA_TTHREAD} when (and only when)
  2316. Lua is creating a new object of that type.
  2317. When @id{osize} is some other value,
  2318. Lua is allocating memory for something else.
  2319. Lua assumes the following behavior from the allocator function:
  2320. When @id{nsize} is zero,
  2321. the allocator must behave like @id{free}
  2322. and return @id{NULL}.
  2323. When @id{nsize} is not zero,
  2324. the allocator must behave like @id{realloc}.
  2325. The allocator returns @id{NULL}
  2326. if and only if it cannot fulfill the request.
  2327. Here is a simple implementation for the @x{allocator function}.
  2328. It is used in the auxiliary library by @Lid{luaL_newstate}.
  2329. @verbatim{
  2330. static void *l_alloc (void *ud, void *ptr, size_t osize,
  2331. size_t nsize) {
  2332. (void)ud; (void)osize; /* not used */
  2333. if (nsize == 0) {
  2334. free(ptr);
  2335. return NULL;
  2336. }
  2337. else
  2338. return realloc(ptr, nsize);
  2339. }
  2340. }
  2341. Note that @N{Standard C} ensures
  2342. that @T{free(NULL)} has no effect and that
  2343. @T{realloc(NULL,size)} is equivalent to @T{malloc(size)}.
  2344. }
  2345. @APIEntry{void lua_arith (lua_State *L, int op);|
  2346. @apii{2|1,1,e}
  2347. Performs an arithmetic or bitwise operation over the two values
  2348. (or one, in the case of negations)
  2349. at the top of the stack,
  2350. with the value on the top being the second operand,
  2351. pops these values, and pushes the result of the operation.
  2352. The function follows the semantics of the corresponding Lua operator
  2353. (that is, it may call metamethods).
  2354. The value of @id{op} must be one of the following constants:
  2355. @description{
  2356. @item{@defid{LUA_OPADD}| performs addition (@T{+})}
  2357. @item{@defid{LUA_OPSUB}| performs subtraction (@T{-})}
  2358. @item{@defid{LUA_OPMUL}| performs multiplication (@T{*})}
  2359. @item{@defid{LUA_OPDIV}| performs float division (@T{/})}
  2360. @item{@defid{LUA_OPIDIV}| performs floor division (@T{//})}
  2361. @item{@defid{LUA_OPMOD}| performs modulo (@T{%})}
  2362. @item{@defid{LUA_OPPOW}| performs exponentiation (@T{^})}
  2363. @item{@defid{LUA_OPUNM}| performs mathematical negation (unary @T{-})}
  2364. @item{@defid{LUA_OPBNOT}| performs bitwise NOT (@T{~})}
  2365. @item{@defid{LUA_OPBAND}| performs bitwise AND (@T{&})}
  2366. @item{@defid{LUA_OPBOR}| performs bitwise OR (@T{|})}
  2367. @item{@defid{LUA_OPBXOR}| performs bitwise exclusive OR (@T{~})}
  2368. @item{@defid{LUA_OPSHL}| performs left shift (@T{<<})}
  2369. @item{@defid{LUA_OPSHR}| performs right shift (@T{>>})}
  2370. }
  2371. }
  2372. @APIEntry{lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);|
  2373. @apii{0,0,-}
  2374. Sets a new panic function and returns the old one @see{C-error}.
  2375. }
  2376. @APIEntry{void lua_call (lua_State *L, int nargs, int nresults);|
  2377. @apii{nargs+1,nresults,e}
  2378. Calls a function.
  2379. To do a call you must use the following protocol:
  2380. first, the value to be called is pushed onto the stack;
  2381. then, the arguments to the call are pushed
  2382. in direct order;
  2383. that is, the first argument is pushed first.
  2384. Finally you call @Lid{lua_call};
  2385. @id{nargs} is the number of arguments that you pushed onto the stack.
  2386. All arguments and the function value are popped from the stack
  2387. when the function is called.
  2388. The function results are pushed onto the stack when the function returns.
  2389. The number of results is adjusted to @id{nresults},
  2390. unless @id{nresults} is @defid{LUA_MULTRET}.
  2391. In this case, all results from the function are pushed;
  2392. Lua takes care that the returned values fit into the stack space,
  2393. but it does not ensure any extra space in the stack.
  2394. The function results are pushed onto the stack in direct order
  2395. (the first result is pushed first),
  2396. so that after the call the last result is on the top of the stack.
  2397. Any error while calling and running the function is propagated upwards
  2398. (with a @id{longjmp}).
  2399. Like regular Lua calls,
  2400. this function respects the @idx{__call} metamethod.
  2401. The following example shows how the host program can do the
  2402. equivalent to this Lua code:
  2403. @verbatim{
  2404. a = f("how", t.x, 14)
  2405. }
  2406. Here it is @N{in C}:
  2407. @verbatim{
  2408. lua_getglobal(L, "f"); /* function to be called */
  2409. lua_pushliteral(L, "how"); /* 1st argument */
  2410. lua_getglobal(L, "t"); /* table to be indexed */
  2411. lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
  2412. lua_remove(L, -2); /* remove 't' from the stack */
  2413. lua_pushinteger(L, 14); /* 3rd argument */
  2414. lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
  2415. lua_setglobal(L, "a"); /* set global 'a' */
  2416. }
  2417. Note that the code above is @emph{balanced}:
  2418. at its end, the stack is back to its original configuration.
  2419. This is considered good programming practice.
  2420. }
  2421. @APIEntry{
  2422. void lua_callk (lua_State *L,
  2423. int nargs,
  2424. int nresults,
  2425. lua_KContext ctx,
  2426. lua_KFunction k);|
  2427. @apii{nargs + 1,nresults,e}
  2428. This function behaves exactly like @Lid{lua_call},
  2429. but allows the called function to yield @see{continuations}.
  2430. }
  2431. @APIEntry{typedef int (*lua_CFunction) (lua_State *L);|
  2432. Type for @N{C functions}.
  2433. In order to communicate properly with Lua,
  2434. a @N{C function} must use the following protocol,
  2435. which defines the way parameters and results are passed:
  2436. a @N{C function} receives its arguments from Lua in its stack
  2437. in direct order (the first argument is pushed first).
  2438. So, when the function starts,
  2439. @T{lua_gettop(L)} returns the number of arguments received by the function.
  2440. The first argument (if any) is at index 1
  2441. and its last argument is at index @T{lua_gettop(L)}.
  2442. To return values to Lua, a @N{C function} just pushes them onto the stack,
  2443. in direct order (the first result is pushed first),
  2444. and returns the number of results.
  2445. Any other value in the stack below the results will be properly
  2446. discarded by Lua.
  2447. Like a Lua function, a @N{C function} called by Lua can also return
  2448. many results.
  2449. As an example, the following function receives a variable number
  2450. of numeric arguments and returns their average and their sum:
  2451. @verbatim{
  2452. static int foo (lua_State *L) {
  2453. int n = lua_gettop(L); /* number of arguments */
  2454. lua_Number sum = 0.0;
  2455. int i;
  2456. for (i = 1; i <= n; i++) {
  2457. if (!lua_isnumber(L, i)) {
  2458. lua_pushliteral(L, "incorrect argument");
  2459. lua_error(L);
  2460. }
  2461. sum += lua_tonumber(L, i);
  2462. }
  2463. lua_pushnumber(L, sum/n); /* first result */
  2464. lua_pushnumber(L, sum); /* second result */
  2465. return 2; /* number of results */
  2466. }
  2467. }
  2468. }
  2469. @APIEntry{int lua_checkstack (lua_State *L, int n);|
  2470. @apii{0,0,-}
  2471. Ensures that the stack has space for at least @id{n} extra slots
  2472. (that is, that you can safely push up to @id{n} values into it).
  2473. It returns false if it cannot fulfill the request,
  2474. either because it would cause the stack
  2475. to be larger than a fixed maximum size
  2476. (typically at least several thousand elements) or
  2477. because it cannot allocate memory for the extra space.
  2478. This function never shrinks the stack;
  2479. if the stack already has space for the extra slots,
  2480. it is left unchanged.
  2481. }
  2482. @APIEntry{void lua_close (lua_State *L);|
  2483. @apii{0,0,-}
  2484. Destroys all objects in the given Lua state
  2485. (calling the corresponding garbage-collection metamethods, if any)
  2486. and frees all dynamic memory used by this state.
  2487. On several platforms, you may not need to call this function,
  2488. because all resources are naturally released when the host program ends.
  2489. On the other hand, long-running programs that create multiple states,
  2490. such as daemons or web servers,
  2491. will probably need to close states as soon as they are not needed.
  2492. }
  2493. @APIEntry{int lua_compare (lua_State *L, int index1, int index2, int op);|
  2494. @apii{0,0,e}
  2495. Compares two Lua values.
  2496. Returns 1 if the value at index @id{index1} satisfies @id{op}
  2497. when compared with the value at index @id{index2},
  2498. following the semantics of the corresponding Lua operator
  2499. (that is, it may call metamethods).
  2500. Otherwise @N{returns 0}.
  2501. Also @N{returns 0} if any of the indices is not valid.
  2502. The value of @id{op} must be one of the following constants:
  2503. @description{
  2504. @item{@defid{LUA_OPEQ}| compares for equality (@T{==})}
  2505. @item{@defid{LUA_OPLT}| compares for less than (@T{<})}
  2506. @item{@defid{LUA_OPLE}| compares for less or equal (@T{<=})}
  2507. }
  2508. }
  2509. @APIEntry{void lua_concat (lua_State *L, int n);|
  2510. @apii{n,1,e}
  2511. Concatenates the @id{n} values at the top of the stack,
  2512. pops them, and leaves the result on the top.
  2513. If @N{@T{n} is 1}, the result is the single value on the stack
  2514. (that is, the function does nothing);
  2515. if @id{n} is 0, the result is the empty string.
  2516. Concatenation is performed following the usual semantics of Lua
  2517. @see{concat}.
  2518. }
  2519. @APIEntry{void lua_copy (lua_State *L, int fromidx, int toidx);|
  2520. @apii{0,0,-}
  2521. Copies the element at index @id{fromidx}
  2522. into the valid index @id{toidx},
  2523. replacing the value at that position.
  2524. Values at other positions are not affected.
  2525. }
  2526. @APIEntry{void lua_createtable (lua_State *L, int narr, int nrec);|
  2527. @apii{0,1,m}
  2528. Creates a new empty table and pushes it onto the stack.
  2529. Parameter @id{narr} is a hint for how many elements the table
  2530. will have as a sequence;
  2531. parameter @id{nrec} is a hint for how many other elements
  2532. the table will have.
  2533. Lua may use these hints to preallocate memory for the new table.
  2534. This preallocation is useful for performance when you know in advance
  2535. how many elements the table will have.
  2536. Otherwise you can use the function @Lid{lua_newtable}.
  2537. }
  2538. @APIEntry{int lua_dump (lua_State *L,
  2539. lua_Writer writer,
  2540. void *data,
  2541. int strip);|
  2542. @apii{0,0,-}
  2543. Dumps a function as a binary chunk.
  2544. Receives a Lua function on the top of the stack
  2545. and produces a binary chunk that,
  2546. if loaded again,
  2547. results in a function equivalent to the one dumped.
  2548. As it produces parts of the chunk,
  2549. @Lid{lua_dump} calls function @id{writer} @seeC{lua_Writer}
  2550. with the given @id{data}
  2551. to write them.
  2552. If @id{strip} is true,
  2553. the binary representation may not include all debug information
  2554. about the function,
  2555. to save space.
  2556. The value returned is the error code returned by the last
  2557. call to the writer;
  2558. @N{0 means} no errors.
  2559. This function does not pop the Lua function from the stack.
  2560. }
  2561. @APIEntry{int lua_error (lua_State *L);|
  2562. @apii{1,0,v}
  2563. Generates a Lua error,
  2564. using the value on the top of the stack as the error object.
  2565. This function does a long jump,
  2566. and therefore never returns
  2567. @seeC{luaL_error}.
  2568. }
  2569. @APIEntry{int lua_gc (lua_State *L, int what, int data);|
  2570. @apii{0,0,-}
  2571. Controls the garbage collector.
  2572. This function performs several tasks,
  2573. according to the value of the parameter @id{what}:
  2574. @description{
  2575. @item{@id{LUA_GCSTOP}|
  2576. stops the garbage collector.
  2577. }
  2578. @item{@id{LUA_GCRESTART}|
  2579. restarts the garbage collector.
  2580. }
  2581. @item{@id{LUA_GCCOLLECT}|
  2582. performs a full garbage-collection cycle.
  2583. }
  2584. @item{@id{LUA_GCCOUNT}|
  2585. returns the current amount of memory (in Kbytes) in use by Lua.
  2586. }
  2587. @item{@id{LUA_GCCOUNTB}|
  2588. returns the remainder of dividing the current amount of bytes of
  2589. memory in use by Lua by 1024.
  2590. }
  2591. @item{@id{LUA_GCSTEP}|
  2592. performs an incremental step of garbage collection.
  2593. }
  2594. @item{@id{LUA_GCSETPAUSE}|
  2595. sets @id{data} as the new value
  2596. for the @emph{pause} of the collector @see{GC}
  2597. and returns the previous value of the pause.
  2598. }
  2599. @item{@id{LUA_GCSETSTEPMUL}|
  2600. sets @id{data} as the new value for the @emph{step multiplier} of
  2601. the collector @see{GC}
  2602. and returns the previous value of the step multiplier.
  2603. }
  2604. @item{@id{LUA_GCISRUNNING}|
  2605. returns a boolean that tells whether the collector is running
  2606. (i.e., not stopped).
  2607. }
  2608. }
  2609. For more details about these options,
  2610. see @Lid{collectgarbage}.
  2611. }
  2612. @APIEntry{lua_Alloc lua_getallocf (lua_State *L, void **ud);|
  2613. @apii{0,0,-}
  2614. Returns the @x{memory-allocation function} of a given state.
  2615. If @id{ud} is not @id{NULL}, Lua stores in @T{*ud} the
  2616. opaque pointer given when the memory-allocator function was set.
  2617. }
  2618. @APIEntry{int lua_getfield (lua_State *L, int index, const char *k);|
  2619. @apii{0,1,e}
  2620. Pushes onto the stack the value @T{t[k]},
  2621. where @id{t} is the value at the given index.
  2622. As in Lua, this function may trigger a metamethod
  2623. for the @Q{index} event @see{metatable}.
  2624. Returns the type of the pushed value.
  2625. }
  2626. @APIEntry{void *lua_getextraspace (lua_State *L);|
  2627. @apii{0,0,-}
  2628. Returns a pointer to a raw memory area associated with the
  2629. given Lua state.
  2630. The application can use this area for any purpose;
  2631. Lua does not use it for anything.
  2632. Each new thread has this area initialized with a copy
  2633. of the area of the @x{main thread}.
  2634. By default, this area has the size of a pointer to void,
  2635. but you can recompile Lua with a different size for this area.
  2636. (See @id{LUA_EXTRASPACE} in @id{luaconf.h}.)
  2637. }
  2638. @APIEntry{int lua_getglobal (lua_State *L, const char *name);|
  2639. @apii{0,1,e}
  2640. Pushes onto the stack the value of the global @id{name}.
  2641. Returns the type of that value.
  2642. }
  2643. @APIEntry{int lua_geti (lua_State *L, int index, lua_Integer i);|
  2644. @apii{0,1,e}
  2645. Pushes onto the stack the value @T{t[i]},
  2646. where @id{t} is the value at the given index.
  2647. As in Lua, this function may trigger a metamethod
  2648. for the @Q{index} event @see{metatable}.
  2649. Returns the type of the pushed value.
  2650. }
  2651. @APIEntry{int lua_getmetatable (lua_State *L, int index);|
  2652. @apii{0,0|1,-}
  2653. If the value at the given index has a metatable,
  2654. the function pushes that metatable onto the stack and @N{returns 1}.
  2655. Otherwise,
  2656. the function @N{returns 0} and pushes nothing on the stack.
  2657. }
  2658. @APIEntry{int lua_gettable (lua_State *L, int index);|
  2659. @apii{1,1,e}
  2660. Pushes onto the stack the value @T{t[k]},
  2661. where @id{t} is the value at the given index
  2662. and @id{k} is the value on the top of the stack.
  2663. This function pops the key from the stack,
  2664. pushing the resulting value in its place.
  2665. As in Lua, this function may trigger a metamethod
  2666. for the @Q{index} event @see{metatable}.
  2667. Returns the type of the pushed value.
  2668. }
  2669. @APIEntry{int lua_gettop (lua_State *L);|
  2670. @apii{0,0,-}
  2671. Returns the index of the top element in the stack.
  2672. Because indices start @N{at 1},
  2673. this result is equal to the number of elements in the stack;
  2674. in particular, @N{0 means} an empty stack.
  2675. }
  2676. @APIEntry{int lua_getiuservalue (lua_State *L, int index, int n);|
  2677. @apii{0,1,-}
  2678. Pushes onto the stack the @id{n}-th user value associated with the
  2679. full userdata at the given index and
  2680. returns the type of the pushed value.
  2681. If the userdata does not have that value,
  2682. pushes @nil and returns @Lid{LUA_TNONE}.
  2683. }
  2684. @APIEntry{void lua_insert (lua_State *L, int index);|
  2685. @apii{1,1,-}
  2686. Moves the top element into the given valid index,
  2687. shifting up the elements above this index to open space.
  2688. This function cannot be called with a pseudo-index,
  2689. because a pseudo-index is not an actual stack position.
  2690. }
  2691. @APIEntry{typedef @ldots lua_Integer;|
  2692. The type of integers in Lua.
  2693. By default this type is @id{long long},
  2694. (usually a 64-bit two-complement integer),
  2695. but that can be changed to @id{long} or @id{int}
  2696. (usually a 32-bit two-complement integer).
  2697. (See @id{LUA_INT_TYPE} in @id{luaconf.h}.)
  2698. Lua also defines the constants
  2699. @defid{LUA_MININTEGER} and @defid{LUA_MAXINTEGER},
  2700. with the minimum and the maximum values that fit in this type.
  2701. }
  2702. @APIEntry{int lua_isboolean (lua_State *L, int index);|
  2703. @apii{0,0,-}
  2704. Returns 1 if the value at the given index is a boolean,
  2705. and @N{0 otherwise}.
  2706. }
  2707. @APIEntry{int lua_iscfunction (lua_State *L, int index);|
  2708. @apii{0,0,-}
  2709. Returns 1 if the value at the given index is a @N{C function},
  2710. and @N{0 otherwise}.
  2711. }
  2712. @APIEntry{int lua_isfunction (lua_State *L, int index);|
  2713. @apii{0,0,-}
  2714. Returns 1 if the value at the given index is a function
  2715. (either C or Lua), and @N{0 otherwise}.
  2716. }
  2717. @APIEntry{int lua_isinteger (lua_State *L, int index);|
  2718. @apii{0,0,-}
  2719. Returns 1 if the value at the given index is an integer
  2720. (that is, the value is a number and is represented as an integer),
  2721. and @N{0 otherwise}.
  2722. }
  2723. @APIEntry{int lua_islightuserdata (lua_State *L, int index);|
  2724. @apii{0,0,-}
  2725. Returns 1 if the value at the given index is a light userdata,
  2726. and @N{0 otherwise}.
  2727. }
  2728. @APIEntry{int lua_isnil (lua_State *L, int index);|
  2729. @apii{0,0,-}
  2730. Returns 1 if the value at the given index is @nil,
  2731. and @N{0 otherwise}.
  2732. }
  2733. @APIEntry{int lua_isnone (lua_State *L, int index);|
  2734. @apii{0,0,-}
  2735. Returns 1 if the given index is not valid,
  2736. and @N{0 otherwise}.
  2737. }
  2738. @APIEntry{int lua_isnoneornil (lua_State *L, int index);|
  2739. @apii{0,0,-}
  2740. Returns 1 if the given index is not valid
  2741. or if the value at this index is @nil,
  2742. and @N{0 otherwise}.
  2743. }
  2744. @APIEntry{int lua_isnumber (lua_State *L, int index);|
  2745. @apii{0,0,-}
  2746. Returns 1 if the value at the given index is a number
  2747. or a string convertible to a number,
  2748. and @N{0 otherwise}.
  2749. }
  2750. @APIEntry{int lua_isstring (lua_State *L, int index);|
  2751. @apii{0,0,-}
  2752. Returns 1 if the value at the given index is a string
  2753. or a number (which is always convertible to a string),
  2754. and @N{0 otherwise}.
  2755. }
  2756. @APIEntry{int lua_istable (lua_State *L, int index);|
  2757. @apii{0,0,-}
  2758. Returns 1 if the value at the given index is a table,
  2759. and @N{0 otherwise}.
  2760. }
  2761. @APIEntry{int lua_isthread (lua_State *L, int index);|
  2762. @apii{0,0,-}
  2763. Returns 1 if the value at the given index is a thread,
  2764. and @N{0 otherwise}.
  2765. }
  2766. @APIEntry{int lua_isuserdata (lua_State *L, int index);|
  2767. @apii{0,0,-}
  2768. Returns 1 if the value at the given index is a userdata
  2769. (either full or light), and @N{0 otherwise}.
  2770. }
  2771. @APIEntry{int lua_isyieldable (lua_State *L);|
  2772. @apii{0,0,-}
  2773. Returns 1 if the given coroutine can yield,
  2774. and @N{0 otherwise}.
  2775. }
  2776. @APIEntry{typedef @ldots lua_KContext;|
  2777. The type for continuation-function contexts.
  2778. It must be a numeric type.
  2779. This type is defined as @id{intptr_t}
  2780. when @id{intptr_t} is available,
  2781. so that it can store pointers too.
  2782. Otherwise, it is defined as @id{ptrdiff_t}.
  2783. }
  2784. @APIEntry{
  2785. typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);|
  2786. Type for continuation functions @see{continuations}.
  2787. }
  2788. @APIEntry{void lua_len (lua_State *L, int index);|
  2789. @apii{0,1,e}
  2790. Returns the length of the value at the given index.
  2791. It is equivalent to the @Char{#} operator in Lua @see{len-op} and
  2792. may trigger a metamethod for the @Q{length} event @see{metatable}.
  2793. The result is pushed on the stack.
  2794. }
  2795. @APIEntry{
  2796. int lua_load (lua_State *L,
  2797. lua_Reader reader,
  2798. void *data,
  2799. const char *chunkname,
  2800. const char *mode);|
  2801. @apii{0,1,-}
  2802. Loads a Lua chunk without running it.
  2803. If there are no errors,
  2804. @id{lua_load} pushes the compiled chunk as a Lua
  2805. function on top of the stack.
  2806. Otherwise, it pushes an error message.
  2807. The return values of @id{lua_load} are:
  2808. @description{
  2809. @item{@Lid{LUA_OK}| no errors;}
  2810. @item{@defid{LUA_ERRSYNTAX}|
  2811. syntax error during precompilation;}
  2812. @item{@Lid{LUA_ERRMEM}|
  2813. @x{memory allocation (out-of-memory) error};}
  2814. }
  2815. The @id{lua_load} function uses a user-supplied @id{reader} function
  2816. to read the chunk @seeC{lua_Reader}.
  2817. The @id{data} argument is an opaque value passed to the reader function.
  2818. The @id{chunkname} argument gives a name to the chunk,
  2819. which is used for error messages and in debug information @see{debugI}.
  2820. @id{lua_load} automatically detects whether the chunk is text or binary
  2821. and loads it accordingly (see program @idx{luac}).
  2822. The string @id{mode} works as in function @Lid{load},
  2823. with the addition that
  2824. a @id{NULL} value is equivalent to the string @St{bt}.
  2825. @id{lua_load} uses the stack internally,
  2826. so the reader function must always leave the stack
  2827. unmodified when returning.
  2828. If the resulting function has upvalues,
  2829. its first upvalue is set to the value of the @x{global environment}
  2830. stored at index @id{LUA_RIDX_GLOBALS} in the registry @see{registry}.
  2831. When loading main chunks,
  2832. this upvalue will be the @id{_ENV} variable @see{globalenv}.
  2833. Other upvalues are initialized with @nil.
  2834. }
  2835. @APIEntry{lua_State *lua_newstate (lua_Alloc f, void *ud);|
  2836. @apii{0,0,-}
  2837. Creates a new thread running in a new, independent state.
  2838. Returns @id{NULL} if it cannot create the thread or the state
  2839. (due to lack of memory).
  2840. The argument @id{f} is the @x{allocator function};
  2841. Lua does all memory allocation for this state
  2842. through this function @seeF{lua_Alloc}.
  2843. The second argument, @id{ud}, is an opaque pointer that Lua
  2844. passes to the allocator in every call.
  2845. }
  2846. @APIEntry{void lua_newtable (lua_State *L);|
  2847. @apii{0,1,m}
  2848. Creates a new empty table and pushes it onto the stack.
  2849. It is equivalent to @T{lua_createtable(L, 0, 0)}.
  2850. }
  2851. @APIEntry{lua_State *lua_newthread (lua_State *L);|
  2852. @apii{0,1,m}
  2853. Creates a new thread, pushes it on the stack,
  2854. and returns a pointer to a @Lid{lua_State} that represents this new thread.
  2855. The new thread returned by this function shares with the original thread
  2856. its global environment,
  2857. but has an independent execution stack.
  2858. There is no explicit function to close or to destroy a thread.
  2859. Threads are subject to garbage collection,
  2860. like any Lua object.
  2861. }
  2862. @APIEntry{void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue);|
  2863. @apii{0,1,m}
  2864. This function creates and pushes on the stack a new full userdata,
  2865. with @id{nuvalue} associated Lua values (called @id{user values})
  2866. plus an associated block of raw memory with @id{size} bytes.
  2867. (The user values can be set and read with the functions
  2868. @Lid{lua_setiuservalue} and @Lid{lua_getiuservalue}.)
  2869. The function returns the address of the block of memory.
  2870. }
  2871. @APIEntry{int lua_next (lua_State *L, int index);|
  2872. @apii{1,2|0,v}
  2873. Pops a key from the stack,
  2874. and pushes a key@En{}value pair from the table at the given index
  2875. (the @Q{next} pair after the given key).
  2876. If there are no more elements in the table,
  2877. then @Lid{lua_next} returns 0 (and pushes nothing).
  2878. A typical traversal looks like this:
  2879. @verbatim{
  2880. /* table is in the stack at index 't' */
  2881. lua_pushnil(L); /* first key */
  2882. while (lua_next(L, t) != 0) {
  2883. /* uses 'key' (at index -2) and 'value' (at index -1) */
  2884. printf("%s - %s\n",
  2885. lua_typename(L, lua_type(L, -2)),
  2886. lua_typename(L, lua_type(L, -1)));
  2887. /* removes 'value'; keeps 'key' for next iteration */
  2888. lua_pop(L, 1);
  2889. }
  2890. }
  2891. While traversing a table,
  2892. do not call @Lid{lua_tolstring} directly on a key,
  2893. unless you know that the key is actually a string.
  2894. Recall that @Lid{lua_tolstring} may change
  2895. the value at the given index;
  2896. this confuses the next call to @Lid{lua_next}.
  2897. This function may raise an error if the given key
  2898. is neither @nil nor present in the table.
  2899. See function @Lid{next} for the caveats of modifying
  2900. the table during its traversal.
  2901. }
  2902. @APIEntry{typedef @ldots lua_Number;|
  2903. The type of floats in Lua.
  2904. By default this type is double,
  2905. but that can be changed to a single float or a long double.
  2906. (See @id{LUA_FLOAT_TYPE} in @id{luaconf.h}.)
  2907. }
  2908. @APIEntry{int lua_numbertointeger (lua_Number n, lua_Integer *p);|
  2909. Converts a Lua float to a Lua integer.
  2910. This macro assumes that @id{n} has an integral value.
  2911. If that value is within the range of Lua integers,
  2912. it is converted to an integer and assigned to @T{*p}.
  2913. The macro results in a boolean indicating whether the
  2914. conversion was successful.
  2915. (Note that this range test can be tricky to do
  2916. correctly without this macro,
  2917. due to roundings.)
  2918. This macro may evaluate its arguments more than once.
  2919. }
  2920. @APIEntry{int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);|
  2921. @apii{nargs + 1,nresults|1,-}
  2922. Calls a function (or a callable object) in protected mode.
  2923. Both @id{nargs} and @id{nresults} have the same meaning as
  2924. in @Lid{lua_call}.
  2925. If there are no errors during the call,
  2926. @Lid{lua_pcall} behaves exactly like @Lid{lua_call}.
  2927. However, if there is any error,
  2928. @Lid{lua_pcall} catches it,
  2929. pushes a single value on the stack (the error object),
  2930. and returns an error code.
  2931. Like @Lid{lua_call},
  2932. @Lid{lua_pcall} always removes the function
  2933. and its arguments from the stack.
  2934. If @id{msgh} is 0,
  2935. then the error object returned on the stack
  2936. is exactly the original error object.
  2937. Otherwise, @id{msgh} is the stack index of a
  2938. @emph{message handler}.
  2939. (This index cannot be a pseudo-index.)
  2940. In case of runtime errors,
  2941. this function will be called with the error object
  2942. and its return value will be the object
  2943. returned on the stack by @Lid{lua_pcall}.
  2944. Typically, the message handler is used to add more debug
  2945. information to the error object, such as a stack traceback.
  2946. Such information cannot be gathered after the return of @Lid{lua_pcall},
  2947. since by then the stack has unwound.
  2948. The @Lid{lua_pcall} function returns one of the following constants
  2949. (defined in @id{lua.h}):
  2950. @description{
  2951. @item{@defid{LUA_OK} (0)|
  2952. success.}
  2953. @item{@defid{LUA_ERRRUN}|
  2954. a runtime error.
  2955. }
  2956. @item{@defid{LUA_ERRMEM}|
  2957. @x{memory allocation error}.
  2958. For such errors, Lua does not call the @x{message handler}.
  2959. }
  2960. @item{@defid{LUA_ERRERR}|
  2961. error while running the @x{message handler}.
  2962. }
  2963. }
  2964. }
  2965. @APIEntry{
  2966. int lua_pcallk (lua_State *L,
  2967. int nargs,
  2968. int nresults,
  2969. int msgh,
  2970. lua_KContext ctx,
  2971. lua_KFunction k);|
  2972. @apii{nargs + 1,nresults|1,-}
  2973. This function behaves exactly like @Lid{lua_pcall},
  2974. but allows the called function to yield @see{continuations}.
  2975. }
  2976. @APIEntry{void lua_pop (lua_State *L, int n);|
  2977. @apii{n,0,-}
  2978. Pops @id{n} elements from the stack.
  2979. }
  2980. @APIEntry{void lua_pushboolean (lua_State *L, int b);|
  2981. @apii{0,1,-}
  2982. Pushes a boolean value with value @id{b} onto the stack.
  2983. }
  2984. @APIEntry{void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);|
  2985. @apii{n,1,m}
  2986. Pushes a new @N{C closure} onto the stack.
  2987. This function receives a pointer to a @N{C function}
  2988. and pushes onto the stack a Lua value of type @id{function} that,
  2989. when called, invokes the corresponding @N{C function}.
  2990. The parameter @id{n} tells how many upvalues this function will have
  2991. @see{c-closure}.
  2992. Any function to be callable by Lua must
  2993. follow the correct protocol to receive its parameters
  2994. and return its results @seeC{lua_CFunction}.
  2995. When a @N{C function} is created,
  2996. it is possible to associate some values with it,
  2997. thus creating a @x{@N{C closure}} @see{c-closure};
  2998. these values are then accessible to the function whenever it is called.
  2999. To associate values with a @N{C function},
  3000. first these values must be pushed onto the stack
  3001. (when there are multiple values, the first value is pushed first).
  3002. Then @Lid{lua_pushcclosure}
  3003. is called to create and push the @N{C function} onto the stack,
  3004. with the argument @id{n} telling how many values will be
  3005. associated with the function.
  3006. @Lid{lua_pushcclosure} also pops these values from the stack.
  3007. The maximum value for @id{n} is 255.
  3008. When @id{n} is zero,
  3009. this function creates a @def{light @N{C function}},
  3010. which is just a pointer to the @N{C function}.
  3011. In that case, it never raises a memory error.
  3012. }
  3013. @APIEntry{void lua_pushcfunction (lua_State *L, lua_CFunction f);|
  3014. @apii{0,1,-}
  3015. Pushes a @N{C function} onto the stack.
  3016. }
  3017. @APIEntry{const char *lua_pushfstring (lua_State *L, const char *fmt, ...);|
  3018. @apii{0,1,v}
  3019. Pushes onto the stack a formatted string
  3020. and returns a pointer to this string.
  3021. It is similar to the @ANSI{sprintf},
  3022. but has two important differences.
  3023. First,
  3024. you do not have to allocate space for the result;
  3025. the result is a Lua string and Lua takes care of memory allocation
  3026. (and deallocation, through garbage collection).
  3027. Second,
  3028. the conversion specifiers are quite restricted.
  3029. There are no flags, widths, or precisions.
  3030. The conversion specifiers can only be
  3031. @Char{%%} (inserts the character @Char{%}),
  3032. @Char{%s} (inserts a zero-terminated string, with no size restrictions),
  3033. @Char{%f} (inserts a @Lid{lua_Number}),
  3034. @Char{%I} (inserts a @Lid{lua_Integer}),
  3035. @Char{%p} (inserts a pointer as a hexadecimal numeral),
  3036. @Char{%d} (inserts an @T{int}),
  3037. @Char{%c} (inserts an @T{int} as a one-byte character), and
  3038. @Char{%U} (inserts a @T{long int} as a @x{UTF-8} byte sequence).
  3039. This function may raise errors due to memory overflow
  3040. or an invalid conversion specifier.
  3041. }
  3042. @APIEntry{void lua_pushglobaltable (lua_State *L);|
  3043. @apii{0,1,-}
  3044. Pushes the @x{global environment} onto the stack.
  3045. }
  3046. @APIEntry{void lua_pushinteger (lua_State *L, lua_Integer n);|
  3047. @apii{0,1,-}
  3048. Pushes an integer with value @id{n} onto the stack.
  3049. }
  3050. @APIEntry{void lua_pushlightuserdata (lua_State *L, void *p);|
  3051. @apii{0,1,-}
  3052. Pushes a light userdata onto the stack.
  3053. Userdata represent @N{C values} in Lua.
  3054. A @def{light userdata} represents a pointer, a @T{void*}.
  3055. It is a value (like a number):
  3056. you do not create it, it has no individual metatable,
  3057. and it is not collected (as it was never created).
  3058. A light userdata is equal to @Q{any}
  3059. light userdata with the same @N{C address}.
  3060. }
  3061. @APIEntry{const char *lua_pushliteral (lua_State *L, const char *s);|
  3062. @apii{0,1,m}
  3063. This macro is equivalent to @Lid{lua_pushstring},
  3064. but should be used only when @id{s} is a literal string.
  3065. }
  3066. @APIEntry{const char *lua_pushlstring (lua_State *L, const char *s, size_t len);|
  3067. @apii{0,1,m}
  3068. Pushes the string pointed to by @id{s} with size @id{len}
  3069. onto the stack.
  3070. Lua makes (or reuses) an internal copy of the given string,
  3071. so the memory at @id{s} can be freed or reused immediately after
  3072. the function returns.
  3073. The string can contain any binary data,
  3074. including @x{embedded zeros}.
  3075. Returns a pointer to the internal copy of the string.
  3076. }
  3077. @APIEntry{void lua_pushnil (lua_State *L);|
  3078. @apii{0,1,-}
  3079. Pushes a nil value onto the stack.
  3080. }
  3081. @APIEntry{void lua_pushnumber (lua_State *L, lua_Number n);|
  3082. @apii{0,1,-}
  3083. Pushes a float with value @id{n} onto the stack.
  3084. }
  3085. @APIEntry{const char *lua_pushstring (lua_State *L, const char *s);|
  3086. @apii{0,1,m}
  3087. Pushes the zero-terminated string pointed to by @id{s}
  3088. onto the stack.
  3089. Lua makes (or reuses) an internal copy of the given string,
  3090. so the memory at @id{s} can be freed or reused immediately after
  3091. the function returns.
  3092. Returns a pointer to the internal copy of the string.
  3093. If @id{s} is @id{NULL}, pushes @nil and returns @id{NULL}.
  3094. }
  3095. @APIEntry{int lua_pushthread (lua_State *L);|
  3096. @apii{0,1,-}
  3097. Pushes the thread represented by @id{L} onto the stack.
  3098. Returns 1 if this thread is the @x{main thread} of its state.
  3099. }
  3100. @APIEntry{void lua_pushvalue (lua_State *L, int index);|
  3101. @apii{0,1,-}
  3102. Pushes a copy of the element at the given index
  3103. onto the stack.
  3104. }
  3105. @APIEntry{
  3106. const char *lua_pushvfstring (lua_State *L,
  3107. const char *fmt,
  3108. va_list argp);|
  3109. @apii{0,1,v}
  3110. Equivalent to @Lid{lua_pushfstring}, except that it receives a @id{va_list}
  3111. instead of a variable number of arguments.
  3112. }
  3113. @APIEntry{int lua_rawequal (lua_State *L, int index1, int index2);|
  3114. @apii{0,0,-}
  3115. Returns 1 if the two values in indices @id{index1} and
  3116. @id{index2} are primitively equal
  3117. (that is, without calling the @idx{__eq} metamethod).
  3118. Otherwise @N{returns 0}.
  3119. Also @N{returns 0} if any of the indices are not valid.
  3120. }
  3121. @APIEntry{int lua_rawget (lua_State *L, int index);|
  3122. @apii{1,1,-}
  3123. Similar to @Lid{lua_gettable}, but does a raw access
  3124. (i.e., without metamethods).
  3125. }
  3126. @APIEntry{int lua_rawgeti (lua_State *L, int index, lua_Integer n);|
  3127. @apii{0,1,-}
  3128. Pushes onto the stack the value @T{t[n]},
  3129. where @id{t} is the table at the given index.
  3130. The access is raw,
  3131. that is, it does not invoke the @idx{__index} metamethod.
  3132. Returns the type of the pushed value.
  3133. }
  3134. @APIEntry{int lua_rawgetp (lua_State *L, int index, const void *p);|
  3135. @apii{0,1,-}
  3136. Pushes onto the stack the value @T{t[k]},
  3137. where @id{t} is the table at the given index and
  3138. @id{k} is the pointer @id{p} represented as a light userdata.
  3139. The access is raw;
  3140. that is, it does not invoke the @idx{__index} metamethod.
  3141. Returns the type of the pushed value.
  3142. }
  3143. @APIEntry{lua_Unsigned lua_rawlen (lua_State *L, int index);|
  3144. @apii{0,0,-}
  3145. Returns the raw @Q{length} of the value at the given index:
  3146. for strings, this is the string length;
  3147. for tables, this is the result of the length operator (@Char{#})
  3148. with no metamethods;
  3149. for userdata, this is the size of the block of memory allocated
  3150. for the userdata;
  3151. for other values, it @N{is 0}.
  3152. }
  3153. @APIEntry{void lua_rawset (lua_State *L, int index);|
  3154. @apii{2,0,m}
  3155. Similar to @Lid{lua_settable}, but does a raw assignment
  3156. (i.e., without metamethods).
  3157. }
  3158. @APIEntry{void lua_rawseti (lua_State *L, int index, lua_Integer i);|
  3159. @apii{1,0,m}
  3160. Does the equivalent of @T{t[i] = v},
  3161. where @id{t} is the table at the given index
  3162. and @id{v} is the value on the top of the stack.
  3163. This function pops the value from the stack.
  3164. The assignment is raw,
  3165. that is, it does not invoke the @idx{__newindex} metamethod.
  3166. }
  3167. @APIEntry{void lua_rawsetp (lua_State *L, int index, const void *p);|
  3168. @apii{1,0,m}
  3169. Does the equivalent of @T{t[p] = v},
  3170. where @id{t} is the table at the given index,
  3171. @id{p} is encoded as a light userdata,
  3172. and @id{v} is the value on the top of the stack.
  3173. This function pops the value from the stack.
  3174. The assignment is raw,
  3175. that is, it does not invoke @idx{__newindex} metamethod.
  3176. }
  3177. @APIEntry{
  3178. typedef const char * (*lua_Reader) (lua_State *L,
  3179. void *data,
  3180. size_t *size);|
  3181. The reader function used by @Lid{lua_load}.
  3182. Every time it needs another piece of the chunk,
  3183. @Lid{lua_load} calls the reader,
  3184. passing along its @id{data} parameter.
  3185. The reader must return a pointer to a block of memory
  3186. with a new piece of the chunk
  3187. and set @id{size} to the block size.
  3188. The block must exist until the reader function is called again.
  3189. To signal the end of the chunk,
  3190. the reader must return @id{NULL} or set @id{size} to zero.
  3191. The reader function may return pieces of any size greater than zero.
  3192. }
  3193. @APIEntry{void lua_register (lua_State *L, const char *name, lua_CFunction f);|
  3194. @apii{0,0,e}
  3195. Sets the @N{C function} @id{f} as the new value of global @id{name}.
  3196. It is defined as a macro:
  3197. @verbatim{
  3198. #define lua_register(L,n,f) \
  3199. (lua_pushcfunction(L, f), lua_setglobal(L, n))
  3200. }
  3201. }
  3202. @APIEntry{void lua_remove (lua_State *L, int index);|
  3203. @apii{1,0,-}
  3204. Removes the element at the given valid index,
  3205. shifting down the elements above this index to fill the gap.
  3206. This function cannot be called with a pseudo-index,
  3207. because a pseudo-index is not an actual stack position.
  3208. }
  3209. @APIEntry{void lua_replace (lua_State *L, int index);|
  3210. @apii{1,0,-}
  3211. Moves the top element into the given valid index
  3212. without shifting any element
  3213. (therefore replacing the value at that given index),
  3214. and then pops the top element.
  3215. }
  3216. @APIEntry{int lua_resetthread (lua_State *L);|
  3217. @apii{0,?,-}
  3218. Resets a thread, cleaning its call stack and closing all pending
  3219. to-be-closed variables.
  3220. Returns a status code:
  3221. @Lid{LUA_OK} for no errors in closing methods,
  3222. or an error status otherwise.
  3223. In case of error,
  3224. leave the error object on the stack,
  3225. }
  3226. @APIEntry{int lua_resume (lua_State *L, lua_State *from, int nargs,
  3227. int *nresults);|
  3228. @apii{?,?,-}
  3229. Starts and resumes a coroutine in the given thread @id{L}.
  3230. To start a coroutine,
  3231. you push onto the thread stack the main function plus any arguments;
  3232. then you call @Lid{lua_resume},
  3233. with @id{nargs} being the number of arguments.
  3234. This call returns when the coroutine suspends or finishes its execution.
  3235. When it returns,
  3236. @id{nresults} is updated and
  3237. the top of the stack contains
  3238. the @id{nresults} values passed to @Lid{lua_yield}
  3239. or returned by the body function.
  3240. @Lid{lua_resume} returns
  3241. @Lid{LUA_YIELD} if the coroutine yields,
  3242. @Lid{LUA_OK} if the coroutine finishes its execution
  3243. without errors,
  3244. or an error code in case of errors @seeC{lua_pcall}.
  3245. In case of errors,
  3246. the error object is on the top of the stack.
  3247. To resume a coroutine,
  3248. you remove all results from the last @Lid{lua_yield},
  3249. put on its stack only the values to
  3250. be passed as results from @id{yield},
  3251. and then call @Lid{lua_resume}.
  3252. The parameter @id{from} represents the coroutine that is resuming @id{L}.
  3253. If there is no such coroutine,
  3254. this parameter can be @id{NULL}.
  3255. }
  3256. @APIEntry{void lua_rotate (lua_State *L, int idx, int n);|
  3257. @apii{0,0,-}
  3258. Rotates the stack elements between the valid index @id{idx}
  3259. and the top of the stack.
  3260. The elements are rotated @id{n} positions in the direction of the top,
  3261. for a positive @id{n},
  3262. or @T{-n} positions in the direction of the bottom,
  3263. for a negative @id{n}.
  3264. The absolute value of @id{n} must not be greater than the size
  3265. of the slice being rotated.
  3266. This function cannot be called with a pseudo-index,
  3267. because a pseudo-index is not an actual stack position.
  3268. }
  3269. @APIEntry{void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);|
  3270. @apii{0,0,-}
  3271. Changes the @x{allocator function} of a given state to @id{f}
  3272. with user data @id{ud}.
  3273. }
  3274. @APIEntry{void lua_setfield (lua_State *L, int index, const char *k);|
  3275. @apii{1,0,e}
  3276. Does the equivalent to @T{t[k] = v},
  3277. where @id{t} is the value at the given index
  3278. and @id{v} is the value on the top of the stack.
  3279. This function pops the value from the stack.
  3280. As in Lua, this function may trigger a metamethod
  3281. for the @Q{newindex} event @see{metatable}.
  3282. }
  3283. @APIEntry{void lua_setglobal (lua_State *L, const char *name);|
  3284. @apii{1,0,e}
  3285. Pops a value from the stack and
  3286. sets it as the new value of global @id{name}.
  3287. }
  3288. @APIEntry{void lua_seti (lua_State *L, int index, lua_Integer n);|
  3289. @apii{1,0,e}
  3290. Does the equivalent to @T{t[n] = v},
  3291. where @id{t} is the value at the given index
  3292. and @id{v} is the value on the top of the stack.
  3293. This function pops the value from the stack.
  3294. As in Lua, this function may trigger a metamethod
  3295. for the @Q{newindex} event @see{metatable}.
  3296. }
  3297. @APIEntry{int lua_setiuservalue (lua_State *L, int index, int n);|
  3298. @apii{1,0,-}
  3299. Pops a value from the stack and sets it as
  3300. the new @id{n}-th user value associated to the
  3301. full userdata at the given index.
  3302. Returns 0 if the userdata does not have that value.
  3303. }
  3304. @APIEntry{void lua_setmetatable (lua_State *L, int index);|
  3305. @apii{1,0,-}
  3306. Pops a table from the stack and
  3307. sets it as the new metatable for the value at the given index.
  3308. }
  3309. @APIEntry{void lua_settable (lua_State *L, int index);|
  3310. @apii{2,0,e}
  3311. Does the equivalent to @T{t[k] = v},
  3312. where @id{t} is the value at the given index,
  3313. @id{v} is the value on the top of the stack,
  3314. and @id{k} is the value just below the top.
  3315. This function pops both the key and the value from the stack.
  3316. As in Lua, this function may trigger a metamethod
  3317. for the @Q{newindex} event @see{metatable}.
  3318. }
  3319. @APIEntry{void lua_settop (lua_State *L, int index);|
  3320. @apii{?,?,-}
  3321. Accepts any index, @N{or 0},
  3322. and sets the stack top to this index.
  3323. If the new top is larger than the old one,
  3324. then the new elements are filled with @nil.
  3325. If @id{index} @N{is 0}, then all stack elements are removed.
  3326. }
  3327. @APIEntry{void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud);|
  3328. @apii{0,0,-}
  3329. Sets the @x{warning function} to be used by Lua to emit warnings
  3330. @see{lua_WarnFunction}.
  3331. The @id{ud} parameter sets the value @id{ud} passed to
  3332. the warning function.
  3333. }
  3334. @APIEntry{typedef struct lua_State lua_State;|
  3335. An opaque structure that points to a thread and indirectly
  3336. (through the thread) to the whole state of a Lua interpreter.
  3337. The Lua library is fully reentrant:
  3338. it has no global variables.
  3339. All information about a state is accessible through this structure.
  3340. A pointer to this structure must be passed as the first argument to
  3341. every function in the library, except to @Lid{lua_newstate},
  3342. which creates a Lua state from scratch.
  3343. }
  3344. @APIEntry{int lua_status (lua_State *L);|
  3345. @apii{0,0,-}
  3346. Returns the status of the thread @id{L}.
  3347. The status can be 0 (@Lid{LUA_OK}) for a normal thread,
  3348. an error code if the thread finished the execution
  3349. of a @Lid{lua_resume} with an error,
  3350. or @defid{LUA_YIELD} if the thread is suspended.
  3351. You can only call functions in threads with status @Lid{LUA_OK}.
  3352. You can resume threads with status @Lid{LUA_OK}
  3353. (to start a new coroutine) or @Lid{LUA_YIELD}
  3354. (to resume a coroutine).
  3355. }
  3356. @APIEntry{size_t lua_stringtonumber (lua_State *L, const char *s);|
  3357. @apii{0,1,-}
  3358. Converts the zero-terminated string @id{s} to a number,
  3359. pushes that number into the stack,
  3360. and returns the total size of the string,
  3361. that is, its length plus one.
  3362. The conversion can result in an integer or a float,
  3363. according to the lexical conventions of Lua @see{lexical}.
  3364. The string may have leading and trailing spaces and a sign.
  3365. If the string is not a valid numeral,
  3366. returns 0 and pushes nothing.
  3367. (Note that the result can be used as a boolean,
  3368. true if the conversion succeeds.)
  3369. }
  3370. @APIEntry{int lua_toboolean (lua_State *L, int index);|
  3371. @apii{0,0,-}
  3372. Converts the Lua value at the given index to a @N{C boolean}
  3373. value (@N{0 or 1}).
  3374. Like all tests in Lua,
  3375. @Lid{lua_toboolean} returns true for any Lua value
  3376. different from @false and @nil;
  3377. otherwise it returns false.
  3378. (If you want to accept only actual boolean values,
  3379. use @Lid{lua_isboolean} to test the value's type.)
  3380. }
  3381. @APIEntry{lua_CFunction lua_tocfunction (lua_State *L, int index);|
  3382. @apii{0,0,-}
  3383. Converts a value at the given index to a @N{C function}.
  3384. That value must be a @N{C function};
  3385. otherwise, returns @id{NULL}.
  3386. }
  3387. @APIEntry{void lua_toclose (lua_State *L, int index);|
  3388. @apii{0,0,v}
  3389. Marks the given index in the stack as a
  3390. to-be-closed @Q{variable} @see{to-be-closed}.
  3391. Like a to-be-closed variable in Lua,
  3392. the value at that index in the stack will be closed
  3393. when it goes out of scope.
  3394. Here, in the context of a C function,
  3395. to go out of scope means that the running function returns (to Lua),
  3396. there is an error,
  3397. or the index is removed from the stack through
  3398. @Lid{lua_settop} or @Lid{lua_pop}.
  3399. An index marked as to-be-closed should not be removed from the stack
  3400. by any other function in the API except @Lid{lua_settop} or @Lid{lua_pop}.
  3401. This function should not be called for an index
  3402. that is equal to or below an already marked to-be-closed index.
  3403. This function can raise an out-of-memory error.
  3404. In that case, the value in the given index is immediately closed,
  3405. as if it was already marked.
  3406. }
  3407. @APIEntry{lua_Integer lua_tointeger (lua_State *L, int index);|
  3408. @apii{0,0,-}
  3409. Equivalent to @Lid{lua_tointegerx} with @id{isnum} equal to @id{NULL}.
  3410. }
  3411. @APIEntry{lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);|
  3412. @apii{0,0,-}
  3413. Converts the Lua value at the given index
  3414. to the signed integral type @Lid{lua_Integer}.
  3415. The Lua value must be an integer,
  3416. or a number or string convertible to an integer @see{coercion};
  3417. otherwise, @id{lua_tointegerx} @N{returns 0}.
  3418. If @id{isnum} is not @id{NULL},
  3419. its referent is assigned a boolean value that
  3420. indicates whether the operation succeeded.
  3421. }
  3422. @APIEntry{const char *lua_tolstring (lua_State *L, int index, size_t *len);|
  3423. @apii{0,0,m}
  3424. Converts the Lua value at the given index to a @N{C string}.
  3425. If @id{len} is not @id{NULL},
  3426. it sets @T{*len} with the string length.
  3427. The Lua value must be a string or a number;
  3428. otherwise, the function returns @id{NULL}.
  3429. If the value is a number,
  3430. then @id{lua_tolstring} also
  3431. @emph{changes the actual value in the stack to a string}.
  3432. (This change confuses @Lid{lua_next}
  3433. when @id{lua_tolstring} is applied to keys during a table traversal.)
  3434. @id{lua_tolstring} returns a pointer
  3435. to a string inside the Lua state.
  3436. This string always has a zero (@Char{\0})
  3437. after its last character (as @N{in C}),
  3438. but can contain other zeros in its body.
  3439. Because Lua has garbage collection,
  3440. there is no guarantee that the pointer returned by @id{lua_tolstring}
  3441. will be valid after the corresponding Lua value is removed from the stack.
  3442. }
  3443. @APIEntry{lua_Number lua_tonumber (lua_State *L, int index);|
  3444. @apii{0,0,-}
  3445. Equivalent to @Lid{lua_tonumberx} with @id{isnum} equal to @id{NULL}.
  3446. }
  3447. @APIEntry{lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);|
  3448. @apii{0,0,-}
  3449. Converts the Lua value at the given index
  3450. to the @N{C type} @Lid{lua_Number} @seeC{lua_Number}.
  3451. The Lua value must be a number or a string convertible to a number
  3452. @see{coercion};
  3453. otherwise, @Lid{lua_tonumberx} @N{returns 0}.
  3454. If @id{isnum} is not @id{NULL},
  3455. its referent is assigned a boolean value that
  3456. indicates whether the operation succeeded.
  3457. }
  3458. @APIEntry{const void *lua_topointer (lua_State *L, int index);|
  3459. @apii{0,0,-}
  3460. Converts the value at the given index to a generic
  3461. @N{C pointer} (@T{void*}).
  3462. The value can be a userdata, a table, a thread, a string, or a function;
  3463. otherwise, @id{lua_topointer} returns @id{NULL}.
  3464. Different objects will give different pointers.
  3465. There is no way to convert the pointer back to its original value.
  3466. Typically this function is used only for hashing and debug information.
  3467. }
  3468. @APIEntry{const char *lua_tostring (lua_State *L, int index);|
  3469. @apii{0,0,m}
  3470. Equivalent to @Lid{lua_tolstring} with @id{len} equal to @id{NULL}.
  3471. }
  3472. @APIEntry{lua_State *lua_tothread (lua_State *L, int index);|
  3473. @apii{0,0,-}
  3474. Converts the value at the given index to a Lua thread
  3475. (represented as @T{lua_State*}).
  3476. This value must be a thread;
  3477. otherwise, the function returns @id{NULL}.
  3478. }
  3479. @APIEntry{void *lua_touserdata (lua_State *L, int index);|
  3480. @apii{0,0,-}
  3481. If the value at the given index is a full userdata,
  3482. returns its memory-block address.
  3483. If the value is a light userdata,
  3484. returns its pointer.
  3485. Otherwise, returns @id{NULL}.
  3486. }
  3487. @APIEntry{int lua_type (lua_State *L, int index);|
  3488. @apii{0,0,-}
  3489. Returns the type of the value in the given valid index,
  3490. or @id{LUA_TNONE} for a non-valid (but acceptable) index.
  3491. The types returned by @Lid{lua_type} are coded by the following constants
  3492. defined in @id{lua.h}:
  3493. @defid{LUA_TNIL},
  3494. @defid{LUA_TNUMBER},
  3495. @defid{LUA_TBOOLEAN},
  3496. @defid{LUA_TSTRING},
  3497. @defid{LUA_TTABLE},
  3498. @defid{LUA_TFUNCTION},
  3499. @defid{LUA_TUSERDATA},
  3500. @defid{LUA_TTHREAD},
  3501. and
  3502. @defid{LUA_TLIGHTUSERDATA}.
  3503. }
  3504. @APIEntry{const char *lua_typename (lua_State *L, int tp);|
  3505. @apii{0,0,-}
  3506. Returns the name of the type encoded by the value @id{tp},
  3507. which must be one the values returned by @Lid{lua_type}.
  3508. }
  3509. @APIEntry{typedef @ldots lua_Unsigned;|
  3510. The unsigned version of @Lid{lua_Integer}.
  3511. }
  3512. @APIEntry{int lua_upvalueindex (int i);|
  3513. @apii{0,0,-}
  3514. Returns the pseudo-index that represents the @id{i}-th upvalue of
  3515. the running function @see{c-closure}.
  3516. @id{i} must be in the range @M{[1,256]}.
  3517. }
  3518. @APIEntry{lua_Number lua_version (lua_State *L);|
  3519. @apii{0,0,-}
  3520. Returns the version number of this core.
  3521. }
  3522. @APIEntry{
  3523. typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont);|
  3524. The type of @x{warning function}s, called by Lua to emit warnings.
  3525. The first parameter is an opaque pointer
  3526. set by @Lid{lua_setwarnf}.
  3527. The second parameter is the warning message.
  3528. The third parameter is a boolean that
  3529. indicates whether the message is
  3530. to be continued by the message in the next call.
  3531. }
  3532. @APIEntry{
  3533. void lua_warning (lua_State *L, const char *msg, int tocont);|
  3534. @apii{0,0,-}
  3535. Emits a warning with the given message.
  3536. A message in a call with @id{tocont} true should be
  3537. continued in another call to this function.
  3538. }
  3539. @APIEntry{
  3540. typedef int (*lua_Writer) (lua_State *L,
  3541. const void* p,
  3542. size_t sz,
  3543. void* ud);|
  3544. The type of the writer function used by @Lid{lua_dump}.
  3545. Every time it produces another piece of chunk,
  3546. @Lid{lua_dump} calls the writer,
  3547. passing along the buffer to be written (@id{p}),
  3548. its size (@id{sz}),
  3549. and the @id{ud} parameter supplied to @Lid{lua_dump}.
  3550. The writer returns an error code:
  3551. @N{0 means} no errors;
  3552. any other value means an error and stops @Lid{lua_dump} from
  3553. calling the writer again.
  3554. }
  3555. @APIEntry{void lua_xmove (lua_State *from, lua_State *to, int n);|
  3556. @apii{?,?,-}
  3557. Exchange values between different threads of the same state.
  3558. This function pops @id{n} values from the stack @id{from},
  3559. and pushes them onto the stack @id{to}.
  3560. }
  3561. @APIEntry{int lua_yield (lua_State *L, int nresults);|
  3562. @apii{?,?,v}
  3563. This function is equivalent to @Lid{lua_yieldk},
  3564. but it has no continuation @see{continuations}.
  3565. Therefore, when the thread resumes,
  3566. it continues the function that called
  3567. the function calling @id{lua_yield}.
  3568. To avoid surprises,
  3569. this function should be called only in a tail call.
  3570. }
  3571. @APIEntry{
  3572. int lua_yieldk (lua_State *L,
  3573. int nresults,
  3574. lua_KContext ctx,
  3575. lua_KFunction k);|
  3576. @apii{?,?,v}
  3577. Yields a coroutine (thread).
  3578. When a @N{C function} calls @Lid{lua_yieldk},
  3579. the running coroutine suspends its execution,
  3580. and the call to @Lid{lua_resume} that started this coroutine returns.
  3581. The parameter @id{nresults} is the number of values from the stack
  3582. that will be passed as results to @Lid{lua_resume}.
  3583. When the coroutine is resumed again,
  3584. Lua calls the given @x{continuation function} @id{k} to continue
  3585. the execution of the @N{C function} that yielded @see{continuations}.
  3586. This continuation function receives the same stack
  3587. from the previous function,
  3588. with the @id{n} results removed and
  3589. replaced by the arguments passed to @Lid{lua_resume}.
  3590. Moreover,
  3591. the continuation function receives the value @id{ctx}
  3592. that was passed to @Lid{lua_yieldk}.
  3593. Usually, this function does not return;
  3594. when the coroutine eventually resumes,
  3595. it continues executing the continuation function.
  3596. However, there is one special case,
  3597. which is when this function is called
  3598. from inside a line or a count hook @see{debugI}.
  3599. In that case, @id{lua_yieldk} should be called with no continuation
  3600. (probably in the form of @Lid{lua_yield}) and no results,
  3601. and the hook should return immediately after the call.
  3602. Lua will yield and,
  3603. when the coroutine resumes again,
  3604. it will continue the normal execution
  3605. of the (Lua) function that triggered the hook.
  3606. This function can raise an error if it is called from a thread
  3607. with a pending C call with no continuation function
  3608. (what is called a @emphx{C-call boundary},
  3609. or it is called from a thread that is not running inside a resume
  3610. (typically the main thread).
  3611. }
  3612. }
  3613. @sect2{debugI| @title{The Debug Interface}
  3614. Lua has no built-in debugging facilities.
  3615. Instead, it offers a special interface
  3616. by means of functions and @emph{hooks}.
  3617. This interface allows the construction of different
  3618. kinds of debuggers, profilers, and other tools
  3619. that need @Q{inside information} from the interpreter.
  3620. @APIEntry{
  3621. typedef struct lua_Debug {
  3622. int event;
  3623. const char *name; /* (n) */
  3624. const char *namewhat; /* (n) */
  3625. const char *what; /* (S) */
  3626. const char *source; /* (S) */
  3627. int currentline; /* (l) */
  3628. int linedefined; /* (S) */
  3629. int lastlinedefined; /* (S) */
  3630. unsigned char nups; /* (u) number of upvalues */
  3631. unsigned char nparams; /* (u) number of parameters */
  3632. char isvararg; /* (u) */
  3633. char istailcall; /* (t) */
  3634. unsigned short ftransfer; /* (r) index of first value transferred */
  3635. unsigned short ntransfer; /* (r) number of transferred values */
  3636. char short_src[LUA_IDSIZE]; /* (S) */
  3637. /* private part */
  3638. @rep{other fields}
  3639. } lua_Debug;
  3640. |
  3641. A structure used to carry different pieces of
  3642. information about a function or an activation record.
  3643. @Lid{lua_getstack} fills only the private part
  3644. of this structure, for later use.
  3645. To fill the other fields of @Lid{lua_Debug} with useful information,
  3646. call @Lid{lua_getinfo}.
  3647. The fields of @Lid{lua_Debug} have the following meaning:
  3648. @description{
  3649. @item{@id{source}|
  3650. the name of the chunk that created the function.
  3651. If @T{source} starts with a @Char{@At},
  3652. it means that the function was defined in a file where
  3653. the file name follows the @Char{@At}.
  3654. If @T{source} starts with a @Char{=},
  3655. the remainder of its contents describe the source in a user-dependent manner.
  3656. Otherwise,
  3657. the function was defined in a string where
  3658. @T{source} is that string.
  3659. }
  3660. @item{@id{short_src}|
  3661. a @Q{printable} version of @T{source}, to be used in error messages.
  3662. }
  3663. @item{@id{linedefined}|
  3664. the line number where the definition of the function starts.
  3665. }
  3666. @item{@id{lastlinedefined}|
  3667. the line number where the definition of the function ends.
  3668. }
  3669. @item{@id{what}|
  3670. the string @T{"Lua"} if the function is a Lua function,
  3671. @T{"C"} if it is a @N{C function},
  3672. @T{"main"} if it is the main part of a chunk.
  3673. }
  3674. @item{@id{currentline}|
  3675. the current line where the given function is executing.
  3676. When no line information is available,
  3677. @T{currentline} is set to @num{-1}.
  3678. }
  3679. @item{@id{name}|
  3680. a reasonable name for the given function.
  3681. Because functions in Lua are first-class values,
  3682. they do not have a fixed name:
  3683. some functions can be the value of multiple global variables,
  3684. while others can be stored only in a table field.
  3685. The @T{lua_getinfo} function checks how the function was
  3686. called to find a suitable name.
  3687. If it cannot find a name,
  3688. then @id{name} is set to @id{NULL}.
  3689. }
  3690. @item{@id{namewhat}|
  3691. explains the @T{name} field.
  3692. The value of @T{namewhat} can be
  3693. @T{"global"}, @T{"local"}, @T{"method"},
  3694. @T{"field"}, @T{"upvalue"}, or @T{""} (the empty string),
  3695. according to how the function was called.
  3696. (Lua uses the empty string when no other option seems to apply.)
  3697. }
  3698. @item{@id{istailcall}|
  3699. true if this function invocation was called by a tail call.
  3700. In this case, the caller of this level is not in the stack.
  3701. }
  3702. @item{@id{nups}|
  3703. the number of upvalues of the function.
  3704. }
  3705. @item{@id{nparams}|
  3706. the number of parameters of the function
  3707. (always @N{0 for} @N{C functions}).
  3708. }
  3709. @item{@id{isvararg}|
  3710. true if the function is a vararg function
  3711. (always true for @N{C functions}).
  3712. }
  3713. @item{@id{ftransfer}|
  3714. the index on the stack of the first value being @Q{transferred},
  3715. that is, parameters in a call or return values in a return.
  3716. (The other values are in consecutive indices.)
  3717. Using this index, you can access and modify these values
  3718. through @Lid{lua_getlocal} and @Lid{lua_setlocal}.
  3719. This field is only meaningful during a
  3720. call hook, denoting the first parameter,
  3721. or a return hook, denoting the first value being returned.
  3722. (For call hooks, this value is always 1.)
  3723. }
  3724. @item{@id{ntransfer}|
  3725. The number of values being transferred (see previous item).
  3726. (For calls of Lua functions,
  3727. this value is always equal to @id{nparams}.)
  3728. }
  3729. }
  3730. }
  3731. @APIEntry{lua_Hook lua_gethook (lua_State *L);|
  3732. @apii{0,0,-}
  3733. Returns the current hook function.
  3734. }
  3735. @APIEntry{int lua_gethookcount (lua_State *L);|
  3736. @apii{0,0,-}
  3737. Returns the current hook count.
  3738. }
  3739. @APIEntry{int lua_gethookmask (lua_State *L);|
  3740. @apii{0,0,-}
  3741. Returns the current hook mask.
  3742. }
  3743. @APIEntry{int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);|
  3744. @apii{0|1,0|1|2,m}
  3745. Gets information about a specific function or function invocation.
  3746. To get information about a function invocation,
  3747. the parameter @id{ar} must be a valid activation record that was
  3748. filled by a previous call to @Lid{lua_getstack} or
  3749. given as argument to a hook @seeC{lua_Hook}.
  3750. To get information about a function, you push it onto the stack
  3751. and start the @id{what} string with the character @Char{>}.
  3752. (In that case,
  3753. @id{lua_getinfo} pops the function from the top of the stack.)
  3754. For instance, to know in which line a function @id{f} was defined,
  3755. you can write the following code:
  3756. @verbatim{
  3757. lua_Debug ar;
  3758. lua_getglobal(L, "f"); /* get global 'f' */
  3759. lua_getinfo(L, ">S", &ar);
  3760. printf("%d\n", ar.linedefined);
  3761. }
  3762. Each character in the string @id{what}
  3763. selects some fields of the structure @id{ar} to be filled or
  3764. a value to be pushed on the stack:
  3765. @description{
  3766. @item{@Char{n}| fills in the field @id{name} and @id{namewhat};
  3767. }
  3768. @item{@Char{S}|
  3769. fills in the fields @id{source}, @id{short_src},
  3770. @id{linedefined}, @id{lastlinedefined}, and @id{what};
  3771. }
  3772. @item{@Char{l}| fills in the field @id{currentline};
  3773. }
  3774. @item{@Char{t}| fills in the field @id{istailcall};
  3775. }
  3776. @item{@Char{u}| fills in the fields
  3777. @id{nups}, @id{nparams}, and @id{isvararg};
  3778. }
  3779. @item{@Char{f}|
  3780. pushes onto the stack the function that is
  3781. running at the given level;
  3782. }
  3783. @item{@Char{L}|
  3784. pushes onto the stack a table whose indices are the
  3785. numbers of the lines that are valid on the function.
  3786. (A @emph{valid line} is a line with some associated code,
  3787. that is, a line where you can put a break point.
  3788. Non-valid lines include empty lines and comments.)
  3789. If this option is given together with option @Char{f},
  3790. its table is pushed after the function.
  3791. This is the only option that can raise a memory error.
  3792. }
  3793. }
  3794. This function returns 0 to signal an invalid option in @id{what};
  3795. even then the valid options are handled correctly.
  3796. }
  3797. @APIEntry{const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);|
  3798. @apii{0,0|1,-}
  3799. Gets information about a local variable or a temporary value
  3800. of a given activation record or a given function.
  3801. In the first case,
  3802. the parameter @id{ar} must be a valid activation record that was
  3803. filled by a previous call to @Lid{lua_getstack} or
  3804. given as argument to a hook @seeC{lua_Hook}.
  3805. The index @id{n} selects which local variable to inspect;
  3806. see @Lid{debug.getlocal} for details about variable indices
  3807. and names.
  3808. @Lid{lua_getlocal} pushes the variable's value onto the stack
  3809. and returns its name.
  3810. In the second case, @id{ar} must be @id{NULL} and the function
  3811. to be inspected must be on the top of the stack.
  3812. In this case, only parameters of Lua functions are visible
  3813. (as there is no information about what variables are active)
  3814. and no values are pushed onto the stack.
  3815. Returns @id{NULL} (and pushes nothing)
  3816. when the index is greater than
  3817. the number of active local variables.
  3818. }
  3819. @APIEntry{int lua_getstack (lua_State *L, int level, lua_Debug *ar);|
  3820. @apii{0,0,-}
  3821. Gets information about the interpreter runtime stack.
  3822. This function fills parts of a @Lid{lua_Debug} structure with
  3823. an identification of the @emph{activation record}
  3824. of the function executing at a given level.
  3825. @N{Level 0} is the current running function,
  3826. whereas level @M{n+1} is the function that has called level @M{n}
  3827. (except for tail calls, which do not count on the stack).
  3828. When there are no errors, @Lid{lua_getstack} returns 1;
  3829. when called with a level greater than the stack depth,
  3830. it returns 0.
  3831. }
  3832. @APIEntry{const char *lua_getupvalue (lua_State *L, int funcindex, int n);|
  3833. @apii{0,0|1,-}
  3834. Gets information about the @id{n}-th upvalue
  3835. of the closure at index @id{funcindex}.
  3836. It pushes the upvalue's value onto the stack
  3837. and returns its name.
  3838. Returns @id{NULL} (and pushes nothing)
  3839. when the index @id{n} is greater than the number of upvalues.
  3840. For @N{C functions}, this function uses the empty string @T{""}
  3841. as a name for all upvalues.
  3842. (For Lua functions,
  3843. upvalues are the external local variables that the function uses,
  3844. and that are consequently included in its closure.)
  3845. Upvalues have no particular order,
  3846. as they are active through the whole function.
  3847. They are numbered in an arbitrary order.
  3848. }
  3849. @APIEntry{typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);|
  3850. Type for debugging hook functions.
  3851. Whenever a hook is called, its @id{ar} argument has its field
  3852. @id{event} set to the specific event that triggered the hook.
  3853. Lua identifies these events with the following constants:
  3854. @defid{LUA_HOOKCALL}, @defid{LUA_HOOKRET},
  3855. @defid{LUA_HOOKTAILCALL}, @defid{LUA_HOOKLINE},
  3856. and @defid{LUA_HOOKCOUNT}.
  3857. Moreover, for line events, the field @id{currentline} is also set.
  3858. To get the value of any other field in @id{ar},
  3859. the hook must call @Lid{lua_getinfo}.
  3860. For call events, @id{event} can be @id{LUA_HOOKCALL},
  3861. the normal value, or @id{LUA_HOOKTAILCALL}, for a tail call;
  3862. in this case, there will be no corresponding return event.
  3863. While Lua is running a hook, it disables other calls to hooks.
  3864. Therefore, if a hook calls back Lua to execute a function or a chunk,
  3865. this execution occurs without any calls to hooks.
  3866. Hook functions cannot have continuations,
  3867. that is, they cannot call @Lid{lua_yieldk},
  3868. @Lid{lua_pcallk}, or @Lid{lua_callk} with a non-null @id{k}.
  3869. Hook functions can yield under the following conditions:
  3870. Only count and line events can yield;
  3871. to yield, a hook function must finish its execution
  3872. calling @Lid{lua_yield} with @id{nresults} equal to zero
  3873. (that is, with no values).
  3874. }
  3875. @APIEntry{void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);|
  3876. @apii{0,0,-}
  3877. Sets the debugging hook function.
  3878. Argument @id{f} is the hook function.
  3879. @id{mask} specifies on which events the hook will be called:
  3880. it is formed by a bitwise OR of the constants
  3881. @defid{LUA_MASKCALL},
  3882. @defid{LUA_MASKRET},
  3883. @defid{LUA_MASKLINE},
  3884. and @defid{LUA_MASKCOUNT}.
  3885. The @id{count} argument is only meaningful when the mask
  3886. includes @id{LUA_MASKCOUNT}.
  3887. For each event, the hook is called as explained below:
  3888. @description{
  3889. @item{The call hook| is called when the interpreter calls a function.
  3890. The hook is called just after Lua enters the new function,
  3891. before the function gets its arguments.
  3892. }
  3893. @item{The return hook| is called when the interpreter returns from a function.
  3894. The hook is called just before Lua leaves the function.
  3895. There is no standard way to access the values
  3896. to be returned by the function.
  3897. }
  3898. @item{The line hook| is called when the interpreter is about to
  3899. start the execution of a new line of code,
  3900. or when it jumps back in the code (even to the same line).
  3901. (This event only happens while Lua is executing a Lua function.)
  3902. }
  3903. @item{The count hook| is called after the interpreter executes every
  3904. @T{count} instructions.
  3905. (This event only happens while Lua is executing a Lua function.)
  3906. }
  3907. }
  3908. A hook is disabled by setting @id{mask} to zero.
  3909. }
  3910. @APIEntry{const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);|
  3911. @apii{0|1,0,-}
  3912. Sets the value of a local variable of a given activation record.
  3913. It assigns the value on the top of the stack
  3914. to the variable and returns its name.
  3915. It also pops the value from the stack.
  3916. Returns @id{NULL} (and pops nothing)
  3917. when the index is greater than
  3918. the number of active local variables.
  3919. Parameters @id{ar} and @id{n} are as in function @Lid{lua_getlocal}.
  3920. }
  3921. @APIEntry{const char *lua_setupvalue (lua_State *L, int funcindex, int n);|
  3922. @apii{0|1,0,-}
  3923. Sets the value of a closure's upvalue.
  3924. It assigns the value on the top of the stack
  3925. to the upvalue and returns its name.
  3926. It also pops the value from the stack.
  3927. Returns @id{NULL} (and pops nothing)
  3928. when the index @id{n} is greater than the number of upvalues.
  3929. Parameters @id{funcindex} and @id{n} are as in function @Lid{lua_getupvalue}.
  3930. }
  3931. @APIEntry{void *lua_upvalueid (lua_State *L, int funcindex, int n);|
  3932. @apii{0,0,-}
  3933. Returns a unique identifier for the upvalue numbered @id{n}
  3934. from the closure at index @id{funcindex}.
  3935. These unique identifiers allow a program to check whether different
  3936. closures share upvalues.
  3937. Lua closures that share an upvalue
  3938. (that is, that access a same external local variable)
  3939. will return identical ids for those upvalue indices.
  3940. Parameters @id{funcindex} and @id{n} are as in function @Lid{lua_getupvalue},
  3941. but @id{n} cannot be greater than the number of upvalues.
  3942. }
  3943. @APIEntry{
  3944. void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
  3945. int funcindex2, int n2);|
  3946. @apii{0,0,-}
  3947. Make the @id{n1}-th upvalue of the Lua closure at index @id{funcindex1}
  3948. refer to the @id{n2}-th upvalue of the Lua closure at index @id{funcindex2}.
  3949. }
  3950. }
  3951. }
  3952. @C{-------------------------------------------------------------------------}
  3953. @sect1{@title{The Auxiliary Library}
  3954. @index{lauxlib.h}
  3955. The @def{auxiliary library} provides several convenient functions
  3956. to interface C with Lua.
  3957. While the basic API provides the primitive functions for all
  3958. interactions between C and Lua,
  3959. the auxiliary library provides higher-level functions for some
  3960. common tasks.
  3961. All functions and types from the auxiliary library
  3962. are defined in header file @id{lauxlib.h} and
  3963. have a prefix @id{luaL_}.
  3964. All functions in the auxiliary library are built on
  3965. top of the basic API,
  3966. and so they provide nothing that cannot be done with that API.
  3967. Nevertheless, the use of the auxiliary library ensures
  3968. more consistency to your code.
  3969. Several functions in the auxiliary library use internally some
  3970. extra stack slots.
  3971. When a function in the auxiliary library uses less than five slots,
  3972. it does not check the stack size;
  3973. it simply assumes that there are enough slots.
  3974. Several functions in the auxiliary library are used to
  3975. check @N{C function} arguments.
  3976. Because the error message is formatted for arguments
  3977. (e.g., @St{bad argument #1}),
  3978. you should not use these functions for other stack values.
  3979. Functions called @id{luaL_check*}
  3980. always raise an error if the check is not satisfied.
  3981. @sect2{@title{Functions and Types}
  3982. Here we list all functions and types from the auxiliary library
  3983. in alphabetical order.
  3984. @APIEntry{void luaL_addchar (luaL_Buffer *B, char c);|
  3985. @apii{?,?,m}
  3986. Adds the byte @id{c} to the buffer @id{B}
  3987. @seeC{luaL_Buffer}.
  3988. }
  3989. @APIEntry{void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);|
  3990. @apii{?,?,m}
  3991. Adds the string pointed to by @id{s} with length @id{l} to
  3992. the buffer @id{B}
  3993. @seeC{luaL_Buffer}.
  3994. The string can contain @x{embedded zeros}.
  3995. }
  3996. @APIEntry{void luaL_addsize (luaL_Buffer *B, size_t n);|
  3997. @apii{?,?,-}
  3998. Adds to the buffer @id{B} @seeC{luaL_Buffer}
  3999. a string of length @id{n} previously copied to the
  4000. buffer area @seeC{luaL_prepbuffer}.
  4001. }
  4002. @APIEntry{void luaL_addstring (luaL_Buffer *B, const char *s);|
  4003. @apii{?,?,m}
  4004. Adds the zero-terminated string pointed to by @id{s}
  4005. to the buffer @id{B}
  4006. @seeC{luaL_Buffer}.
  4007. }
  4008. @APIEntry{void luaL_addvalue (luaL_Buffer *B);|
  4009. @apii{1,?,m}
  4010. Adds the value on the top of the stack
  4011. to the buffer @id{B}
  4012. @seeC{luaL_Buffer}.
  4013. Pops the value.
  4014. This is the only function on string buffers that can (and must)
  4015. be called with an extra element on the stack,
  4016. which is the value to be added to the buffer.
  4017. }
  4018. @APIEntry{
  4019. void luaL_argcheck (lua_State *L,
  4020. int cond,
  4021. int arg,
  4022. const char *extramsg);|
  4023. @apii{0,0,v}
  4024. Checks whether @id{cond} is true.
  4025. If it is not, raises an error with a standard message @seeF{luaL_argerror}.
  4026. }
  4027. @APIEntry{int luaL_argerror (lua_State *L, int arg, const char *extramsg);|
  4028. @apii{0,0,v}
  4029. Raises an error reporting a problem with argument @id{arg}
  4030. of the @N{C function} that called it,
  4031. using a standard message
  4032. that includes @id{extramsg} as a comment:
  4033. @verbatim{
  4034. bad argument #@rep{arg} to '@rep{funcname}' (@rep{extramsg})
  4035. }
  4036. This function never returns.
  4037. }
  4038. @APIEntry{
  4039. void luaL_argexpected (lua_State *L,
  4040. int cond,
  4041. int arg,
  4042. const char *tname);|
  4043. @apii{0,0,v}
  4044. Checks whether @id{cond} is true.
  4045. If it is not, raises an error about the type of the argument @id{arg}
  4046. with a standard message @seeF{luaL_typeerror}.
  4047. }
  4048. @APIEntry{typedef struct luaL_Buffer luaL_Buffer;|
  4049. Type for a @def{string buffer}.
  4050. A string buffer allows @N{C code} to build Lua strings piecemeal.
  4051. Its pattern of use is as follows:
  4052. @itemize{
  4053. @item{First declare a variable @id{b} of type @Lid{luaL_Buffer}.}
  4054. @item{Then initialize it with a call @T{luaL_buffinit(L, &b)}.}
  4055. @item{
  4056. Then add string pieces to the buffer calling any of
  4057. the @id{luaL_add*} functions.
  4058. }
  4059. @item{
  4060. Finish by calling @T{luaL_pushresult(&b)}.
  4061. This call leaves the final string on the top of the stack.
  4062. }
  4063. }
  4064. If you know beforehand the maximum size of the resulting string,
  4065. you can use the buffer like this:
  4066. @itemize{
  4067. @item{First declare a variable @id{b} of type @Lid{luaL_Buffer}.}
  4068. @item{Then initialize it and preallocate a space of
  4069. size @id{sz} with a call @T{luaL_buffinitsize(L, &b, sz)}.}
  4070. @item{Then produce the string into that space.}
  4071. @item{
  4072. Finish by calling @T{luaL_pushresultsize(&b, sz)},
  4073. where @id{sz} is the total size of the resulting string
  4074. copied into that space (which may be smaller than or
  4075. equal to the preallocated size).
  4076. }
  4077. }
  4078. During its normal operation,
  4079. a string buffer uses a variable number of stack slots.
  4080. So, while using a buffer, you cannot assume that you know where
  4081. the top of the stack is.
  4082. You can use the stack between successive calls to buffer operations
  4083. as long as that use is balanced;
  4084. that is,
  4085. when you call a buffer operation,
  4086. the stack is at the same level
  4087. it was immediately after the previous buffer operation.
  4088. (The only exception to this rule is @Lid{luaL_addvalue}.)
  4089. After calling @Lid{luaL_pushresult},
  4090. the stack is back to its level when the buffer was initialized,
  4091. plus the final string on its top.
  4092. }
  4093. @APIEntry{void luaL_buffinit (lua_State *L, luaL_Buffer *B);|
  4094. @apii{0,0,-}
  4095. Initializes a buffer @id{B}.
  4096. This function does not allocate any space;
  4097. the buffer must be declared as a variable
  4098. @seeC{luaL_Buffer}.
  4099. }
  4100. @APIEntry{char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);|
  4101. @apii{?,?,m}
  4102. Equivalent to the sequence
  4103. @Lid{luaL_buffinit}, @Lid{luaL_prepbuffsize}.
  4104. }
  4105. @APIEntry{int luaL_callmeta (lua_State *L, int obj, const char *e);|
  4106. @apii{0,0|1,e}
  4107. Calls a metamethod.
  4108. If the object at index @id{obj} has a metatable and this
  4109. metatable has a field @id{e},
  4110. this function calls this field passing the object as its only argument.
  4111. In this case this function returns true and pushes onto the
  4112. stack the value returned by the call.
  4113. If there is no metatable or no metamethod,
  4114. this function returns false (without pushing any value on the stack).
  4115. }
  4116. @APIEntry{void luaL_checkany (lua_State *L, int arg);|
  4117. @apii{0,0,v}
  4118. Checks whether the function has an argument
  4119. of any type (including @nil) at position @id{arg}.
  4120. }
  4121. @APIEntry{lua_Integer luaL_checkinteger (lua_State *L, int arg);|
  4122. @apii{0,0,v}
  4123. Checks whether the function argument @id{arg} is an integer
  4124. (or can be converted to an integer)
  4125. and returns this integer cast to a @Lid{lua_Integer}.
  4126. }
  4127. @APIEntry{const char *luaL_checklstring (lua_State *L, int arg, size_t *l);|
  4128. @apii{0,0,v}
  4129. Checks whether the function argument @id{arg} is a string
  4130. and returns this string;
  4131. if @id{l} is not @id{NULL} fills @T{*l}
  4132. with the string's length.
  4133. This function uses @Lid{lua_tolstring} to get its result,
  4134. so all conversions and caveats of that function apply here.
  4135. }
  4136. @APIEntry{lua_Number luaL_checknumber (lua_State *L, int arg);|
  4137. @apii{0,0,v}
  4138. Checks whether the function argument @id{arg} is a number
  4139. and returns this number.
  4140. }
  4141. @APIEntry{
  4142. int luaL_checkoption (lua_State *L,
  4143. int arg,
  4144. const char *def,
  4145. const char *const lst[]);|
  4146. @apii{0,0,v}
  4147. Checks whether the function argument @id{arg} is a string and
  4148. searches for this string in the array @id{lst}
  4149. (which must be NULL-terminated).
  4150. Returns the index in the array where the string was found.
  4151. Raises an error if the argument is not a string or
  4152. if the string cannot be found.
  4153. If @id{def} is not @id{NULL},
  4154. the function uses @id{def} as a default value when
  4155. there is no argument @id{arg} or when this argument is @nil.
  4156. This is a useful function for mapping strings to @N{C enums}.
  4157. (The usual convention in Lua libraries is
  4158. to use strings instead of numbers to select options.)
  4159. }
  4160. @APIEntry{void luaL_checkstack (lua_State *L, int sz, const char *msg);|
  4161. @apii{0,0,v}
  4162. Grows the stack size to @T{top + sz} elements,
  4163. raising an error if the stack cannot grow to that size.
  4164. @id{msg} is an additional text to go into the error message
  4165. (or @id{NULL} for no additional text).
  4166. }
  4167. @APIEntry{const char *luaL_checkstring (lua_State *L, int arg);|
  4168. @apii{0,0,v}
  4169. Checks whether the function argument @id{arg} is a string
  4170. and returns this string.
  4171. This function uses @Lid{lua_tolstring} to get its result,
  4172. so all conversions and caveats of that function apply here.
  4173. }
  4174. @APIEntry{void luaL_checktype (lua_State *L, int arg, int t);|
  4175. @apii{0,0,v}
  4176. Checks whether the function argument @id{arg} has type @id{t}.
  4177. See @Lid{lua_type} for the encoding of types for @id{t}.
  4178. }
  4179. @APIEntry{void *luaL_checkudata (lua_State *L, int arg, const char *tname);|
  4180. @apii{0,0,v}
  4181. Checks whether the function argument @id{arg} is a userdata
  4182. of the type @id{tname} @seeC{luaL_newmetatable} and
  4183. returns the userdata's memory-block address @seeC{lua_touserdata}.
  4184. }
  4185. @APIEntry{void luaL_checkversion (lua_State *L);|
  4186. @apii{0,0,v}
  4187. Checks whether the code making the call and the Lua library being called
  4188. are using the same version of Lua and the same numeric types.
  4189. }
  4190. @APIEntry{int luaL_dofile (lua_State *L, const char *filename);|
  4191. @apii{0,?,m}
  4192. Loads and runs the given file.
  4193. It is defined as the following macro:
  4194. @verbatim{
  4195. (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
  4196. }
  4197. It returns false if there are no errors
  4198. or true in case of errors.
  4199. }
  4200. @APIEntry{int luaL_dostring (lua_State *L, const char *str);|
  4201. @apii{0,?,-}
  4202. Loads and runs the given string.
  4203. It is defined as the following macro:
  4204. @verbatim{
  4205. (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
  4206. }
  4207. It returns false if there are no errors
  4208. or true in case of errors.
  4209. }
  4210. @APIEntry{int luaL_error (lua_State *L, const char *fmt, ...);|
  4211. @apii{0,0,v}
  4212. Raises an error.
  4213. The error message format is given by @id{fmt}
  4214. plus any extra arguments,
  4215. following the same rules of @Lid{lua_pushfstring}.
  4216. It also adds at the beginning of the message the file name and
  4217. the line number where the error occurred,
  4218. if this information is available.
  4219. This function never returns,
  4220. but it is an idiom to use it in @N{C functions}
  4221. as @T{return luaL_error(@rep{args})}.
  4222. }
  4223. @APIEntry{int luaL_execresult (lua_State *L, int stat);|
  4224. @apii{0,3,m}
  4225. This function produces the return values for
  4226. process-related functions in the standard library
  4227. (@Lid{os.execute} and @Lid{io.close}).
  4228. }
  4229. @APIEntry{
  4230. int luaL_fileresult (lua_State *L, int stat, const char *fname);|
  4231. @apii{0,1|3,m}
  4232. This function produces the return values for
  4233. file-related functions in the standard library
  4234. (@Lid{io.open}, @Lid{os.rename}, @Lid{file:seek}, etc.).
  4235. }
  4236. @APIEntry{int luaL_getmetafield (lua_State *L, int obj, const char *e);|
  4237. @apii{0,0|1,m}
  4238. Pushes onto the stack the field @id{e} from the metatable
  4239. of the object at index @id{obj} and returns the type of the pushed value.
  4240. If the object does not have a metatable,
  4241. or if the metatable does not have this field,
  4242. pushes nothing and returns @id{LUA_TNIL}.
  4243. }
  4244. @APIEntry{int luaL_getmetatable (lua_State *L, const char *tname);|
  4245. @apii{0,1,m}
  4246. Pushes onto the stack the metatable associated with the name @id{tname}
  4247. in the registry @seeC{luaL_newmetatable},
  4248. or @nil if there is no metatable associated with that name.
  4249. Returns the type of the pushed value.
  4250. }
  4251. @APIEntry{int luaL_getsubtable (lua_State *L, int idx, const char *fname);|
  4252. @apii{0,1,e}
  4253. Ensures that the value @T{t[fname]},
  4254. where @id{t} is the value at index @id{idx},
  4255. is a table,
  4256. and pushes that table onto the stack.
  4257. Returns true if it finds a previous table there
  4258. and false if it creates a new table.
  4259. }
  4260. @APIEntry{
  4261. const char *luaL_gsub (lua_State *L,
  4262. const char *s,
  4263. const char *p,
  4264. const char *r);|
  4265. @apii{0,1,m}
  4266. Creates a copy of string @id{s} by replacing
  4267. any occurrence of the string @id{p}
  4268. with the string @id{r}.
  4269. Pushes the resulting string on the stack and returns it.
  4270. }
  4271. @APIEntry{lua_Integer luaL_len (lua_State *L, int index);|
  4272. @apii{0,0,e}
  4273. Returns the @Q{length} of the value at the given index
  4274. as a number;
  4275. it is equivalent to the @Char{#} operator in Lua @see{len-op}.
  4276. Raises an error if the result of the operation is not an integer.
  4277. (This case only can happen through metamethods.)
  4278. }
  4279. @APIEntry{
  4280. int luaL_loadbuffer (lua_State *L,
  4281. const char *buff,
  4282. size_t sz,
  4283. const char *name);|
  4284. @apii{0,1,-}
  4285. Equivalent to @Lid{luaL_loadbufferx} with @id{mode} equal to @id{NULL}.
  4286. }
  4287. @APIEntry{
  4288. int luaL_loadbufferx (lua_State *L,
  4289. const char *buff,
  4290. size_t sz,
  4291. const char *name,
  4292. const char *mode);|
  4293. @apii{0,1,-}
  4294. Loads a buffer as a Lua chunk.
  4295. This function uses @Lid{lua_load} to load the chunk in the
  4296. buffer pointed to by @id{buff} with size @id{sz}.
  4297. This function returns the same results as @Lid{lua_load}.
  4298. @id{name} is the chunk name,
  4299. used for debug information and error messages.
  4300. The string @id{mode} works as in function @Lid{lua_load}.
  4301. }
  4302. @APIEntry{int luaL_loadfile (lua_State *L, const char *filename);|
  4303. @apii{0,1,m}
  4304. Equivalent to @Lid{luaL_loadfilex} with @id{mode} equal to @id{NULL}.
  4305. }
  4306. @APIEntry{int luaL_loadfilex (lua_State *L, const char *filename,
  4307. const char *mode);|
  4308. @apii{0,1,m}
  4309. Loads a file as a Lua chunk.
  4310. This function uses @Lid{lua_load} to load the chunk in the file
  4311. named @id{filename}.
  4312. If @id{filename} is @id{NULL},
  4313. then it loads from the standard input.
  4314. The first line in the file is ignored if it starts with a @T{#}.
  4315. The string @id{mode} works as in function @Lid{lua_load}.
  4316. This function returns the same results as @Lid{lua_load},
  4317. but it has an extra error code @defid{LUA_ERRFILE}
  4318. for file-related errors
  4319. (e.g., it cannot open or read the file).
  4320. As @Lid{lua_load}, this function only loads the chunk;
  4321. it does not run it.
  4322. }
  4323. @APIEntry{int luaL_loadstring (lua_State *L, const char *s);|
  4324. @apii{0,1,-}
  4325. Loads a string as a Lua chunk.
  4326. This function uses @Lid{lua_load} to load the chunk in
  4327. the zero-terminated string @id{s}.
  4328. This function returns the same results as @Lid{lua_load}.
  4329. Also as @Lid{lua_load}, this function only loads the chunk;
  4330. it does not run it.
  4331. }
  4332. @APIEntry{void luaL_newlib (lua_State *L, const luaL_Reg l[]);|
  4333. @apii{0,1,m}
  4334. Creates a new table and registers there
  4335. the functions in list @id{l}.
  4336. It is implemented as the following macro:
  4337. @verbatim{
  4338. (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
  4339. }
  4340. The array @id{l} must be the actual array,
  4341. not a pointer to it.
  4342. }
  4343. @APIEntry{void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);|
  4344. @apii{0,1,m}
  4345. Creates a new table with a size optimized
  4346. to store all entries in the array @id{l}
  4347. (but does not actually store them).
  4348. It is intended to be used in conjunction with @Lid{luaL_setfuncs}
  4349. @seeF{luaL_newlib}.
  4350. It is implemented as a macro.
  4351. The array @id{l} must be the actual array,
  4352. not a pointer to it.
  4353. }
  4354. @APIEntry{int luaL_newmetatable (lua_State *L, const char *tname);|
  4355. @apii{0,1,m}
  4356. If the registry already has the key @id{tname},
  4357. returns 0.
  4358. Otherwise,
  4359. creates a new table to be used as a metatable for userdata,
  4360. adds to this new table the pair @T{__name = tname},
  4361. adds to the registry the pair @T{[tname] = new table},
  4362. and returns 1.
  4363. (The entry @idx{__name} is used by some error-reporting functions.)
  4364. In both cases pushes onto the stack the final value associated
  4365. with @id{tname} in the registry.
  4366. }
  4367. @APIEntry{lua_State *luaL_newstate (void);|
  4368. @apii{0,0,-}
  4369. Creates a new Lua state.
  4370. It calls @Lid{lua_newstate} with an
  4371. allocator based on the @N{standard C} @id{realloc} function
  4372. and then sets a panic function @see{C-error} that prints
  4373. an error message to the standard error output in case of fatal
  4374. errors.
  4375. Returns the new state,
  4376. or @id{NULL} if there is a @x{memory allocation error}.
  4377. }
  4378. @APIEntry{void luaL_openlibs (lua_State *L);|
  4379. @apii{0,0,e}
  4380. Opens all standard Lua libraries into the given state.
  4381. }
  4382. @APIEntry{
  4383. T luaL_opt (L, func, arg, dflt);|
  4384. @apii{0,0,-}
  4385. This macro is defined as follows:
  4386. @verbatim{
  4387. (lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg)))
  4388. }
  4389. In words, if the argument @id{arg} is nil or absent,
  4390. the macro results in the default @id{dflt}.
  4391. Otherwise, it results in the result of calling @id{func}
  4392. with the state @id{L} and the argument index @id{arg} as
  4393. arguments.
  4394. Note that it evaluates the expression @id{dflt} only if needed.
  4395. }
  4396. @APIEntry{
  4397. lua_Integer luaL_optinteger (lua_State *L,
  4398. int arg,
  4399. lua_Integer d);|
  4400. @apii{0,0,v}
  4401. If the function argument @id{arg} is an integer
  4402. (or convertible to an integer),
  4403. returns this integer.
  4404. If this argument is absent or is @nil,
  4405. returns @id{d}.
  4406. Otherwise, raises an error.
  4407. }
  4408. @APIEntry{
  4409. const char *luaL_optlstring (lua_State *L,
  4410. int arg,
  4411. const char *d,
  4412. size_t *l);|
  4413. @apii{0,0,v}
  4414. If the function argument @id{arg} is a string,
  4415. returns this string.
  4416. If this argument is absent or is @nil,
  4417. returns @id{d}.
  4418. Otherwise, raises an error.
  4419. If @id{l} is not @id{NULL},
  4420. fills the position @T{*l} with the result's length.
  4421. If the result is @id{NULL}
  4422. (only possible when returning @id{d} and @T{d == NULL}),
  4423. its length is considered zero.
  4424. This function uses @Lid{lua_tolstring} to get its result,
  4425. so all conversions and caveats of that function apply here.
  4426. }
  4427. @APIEntry{lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);|
  4428. @apii{0,0,v}
  4429. If the function argument @id{arg} is a number,
  4430. returns this number.
  4431. If this argument is absent or is @nil,
  4432. returns @id{d}.
  4433. Otherwise, raises an error.
  4434. }
  4435. @APIEntry{
  4436. const char *luaL_optstring (lua_State *L,
  4437. int arg,
  4438. const char *d);|
  4439. @apii{0,0,v}
  4440. If the function argument @id{arg} is a string,
  4441. returns this string.
  4442. If this argument is absent or is @nil,
  4443. returns @id{d}.
  4444. Otherwise, raises an error.
  4445. }
  4446. @APIEntry{char *luaL_prepbuffer (luaL_Buffer *B);|
  4447. @apii{?,?,m}
  4448. Equivalent to @Lid{luaL_prepbuffsize}
  4449. with the predefined size @defid{LUAL_BUFFERSIZE}.
  4450. }
  4451. @APIEntry{char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);|
  4452. @apii{?,?,m}
  4453. Returns an address to a space of size @id{sz}
  4454. where you can copy a string to be added to buffer @id{B}
  4455. @seeC{luaL_Buffer}.
  4456. After copying the string into this space you must call
  4457. @Lid{luaL_addsize} with the size of the string to actually add
  4458. it to the buffer.
  4459. }
  4460. @APIEntry{void luaL_pushresult (luaL_Buffer *B);|
  4461. @apii{?,1,m}
  4462. Finishes the use of buffer @id{B} leaving the final string on
  4463. the top of the stack.
  4464. }
  4465. @APIEntry{void luaL_pushresultsize (luaL_Buffer *B, size_t sz);|
  4466. @apii{?,1,m}
  4467. Equivalent to the sequence @Lid{luaL_addsize}, @Lid{luaL_pushresult}.
  4468. }
  4469. @APIEntry{int luaL_ref (lua_State *L, int t);|
  4470. @apii{1,0,m}
  4471. Creates and returns a @def{reference},
  4472. in the table at index @id{t},
  4473. for the object on the top of the stack (and pops the object).
  4474. A reference is a unique integer key.
  4475. As long as you do not manually add integer keys into table @id{t},
  4476. @Lid{luaL_ref} ensures the uniqueness of the key it returns.
  4477. You can retrieve an object referred by reference @id{r}
  4478. by calling @T{lua_rawgeti(L, t, r)}.
  4479. Function @Lid{luaL_unref} frees a reference and its associated object.
  4480. If the object on the top of the stack is @nil,
  4481. @Lid{luaL_ref} returns the constant @defid{LUA_REFNIL}.
  4482. The constant @defid{LUA_NOREF} is guaranteed to be different
  4483. from any reference returned by @Lid{luaL_ref}.
  4484. }
  4485. @APIEntry{
  4486. typedef struct luaL_Reg {
  4487. const char *name;
  4488. lua_CFunction func;
  4489. } luaL_Reg;
  4490. |
  4491. Type for arrays of functions to be registered by
  4492. @Lid{luaL_setfuncs}.
  4493. @id{name} is the function name and @id{func} is a pointer to
  4494. the function.
  4495. Any array of @Lid{luaL_Reg} must end with a sentinel entry
  4496. in which both @id{name} and @id{func} are @id{NULL}.
  4497. }
  4498. @APIEntry{
  4499. void luaL_requiref (lua_State *L, const char *modname,
  4500. lua_CFunction openf, int glb);|
  4501. @apii{0,1,e}
  4502. If @T{package.loaded[modname]} is not true,
  4503. calls function @id{openf} with string @id{modname} as an argument
  4504. and sets the call result to @T{package.loaded[modname]},
  4505. as if that function has been called through @Lid{require}.
  4506. If @id{glb} is true,
  4507. also stores the module into global @id{modname}.
  4508. Leaves a copy of the module on the stack.
  4509. }
  4510. @APIEntry{void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);|
  4511. @apii{nup,0,m}
  4512. Registers all functions in the array @id{l}
  4513. @seeC{luaL_Reg} into the table on the top of the stack
  4514. (below optional upvalues, see next).
  4515. When @id{nup} is not zero,
  4516. all functions are created with @id{nup} upvalues,
  4517. initialized with copies of the @id{nup} values
  4518. previously pushed on the stack
  4519. on top of the library table.
  4520. These values are popped from the stack after the registration.
  4521. }
  4522. @APIEntry{void luaL_setmetatable (lua_State *L, const char *tname);|
  4523. @apii{0,0,-}
  4524. Sets the metatable of the object on the top of the stack
  4525. as the metatable associated with name @id{tname}
  4526. in the registry @seeC{luaL_newmetatable}.
  4527. }
  4528. @APIEntry{
  4529. typedef struct luaL_Stream {
  4530. FILE *f;
  4531. lua_CFunction closef;
  4532. } luaL_Stream;
  4533. |
  4534. The standard representation for @x{file handles},
  4535. which is used by the standard I/O library.
  4536. A file handle is implemented as a full userdata,
  4537. with a metatable called @id{LUA_FILEHANDLE}
  4538. (where @id{LUA_FILEHANDLE} is a macro with the actual metatable's name).
  4539. The metatable is created by the I/O library
  4540. @seeF{luaL_newmetatable}.
  4541. This userdata must start with the structure @id{luaL_Stream};
  4542. it can contain other data after this initial structure.
  4543. Field @id{f} points to the corresponding C stream
  4544. (or it can be @id{NULL} to indicate an incompletely created handle).
  4545. Field @id{closef} points to a Lua function
  4546. that will be called to close the stream
  4547. when the handle is closed or collected;
  4548. this function receives the file handle as its sole argument and
  4549. must return either @true (in case of success)
  4550. or @nil plus an error message (in case of error).
  4551. Once Lua calls this field,
  4552. it changes the field value to @id{NULL}
  4553. to signal that the handle is closed.
  4554. }
  4555. @APIEntry{void *luaL_testudata (lua_State *L, int arg, const char *tname);|
  4556. @apii{0,0,m}
  4557. This function works like @Lid{luaL_checkudata},
  4558. except that, when the test fails,
  4559. it returns @id{NULL} instead of raising an error.
  4560. }
  4561. @APIEntry{const char *luaL_tolstring (lua_State *L, int idx, size_t *len);|
  4562. @apii{0,1,e}
  4563. Converts any Lua value at the given index to a @N{C string}
  4564. in a reasonable format.
  4565. The resulting string is pushed onto the stack and also
  4566. returned by the function.
  4567. If @id{len} is not @id{NULL},
  4568. the function also sets @T{*len} with the string length.
  4569. If the value has a metatable with a @idx{__tostring} field,
  4570. then @id{luaL_tolstring} calls the corresponding metamethod
  4571. with the value as argument,
  4572. and uses the result of the call as its result.
  4573. }
  4574. @APIEntry{
  4575. void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
  4576. int level);|
  4577. @apii{0,1,m}
  4578. Creates and pushes a traceback of the stack @id{L1}.
  4579. If @id{msg} is not @id{NULL} it is appended
  4580. at the beginning of the traceback.
  4581. The @id{level} parameter tells at which level
  4582. to start the traceback.
  4583. }
  4584. @APIEntry{const char *luaL_typeerror (lua_State *L,
  4585. int arg,
  4586. const char *tname);|
  4587. @apii{0,0,v}
  4588. Raises a type error for argument @id{arg}
  4589. of the @N{C function} that called it,
  4590. using a standard message;
  4591. @id{tname} is a @Q{name} for the expected type.
  4592. This function never returns.
  4593. }
  4594. @APIEntry{const char *luaL_typename (lua_State *L, int index);|
  4595. @apii{0,0,-}
  4596. Returns the name of the type of the value at the given index.
  4597. }
  4598. @APIEntry{void luaL_unref (lua_State *L, int t, int ref);|
  4599. @apii{0,0,-}
  4600. Releases reference @id{ref} from the table at index @id{t}
  4601. @seeC{luaL_ref}.
  4602. The entry is removed from the table,
  4603. so that the referred object can be collected.
  4604. The reference @id{ref} is also freed to be used again.
  4605. If @id{ref} is @Lid{LUA_NOREF} or @Lid{LUA_REFNIL},
  4606. @Lid{luaL_unref} does nothing.
  4607. }
  4608. @APIEntry{void luaL_where (lua_State *L, int lvl);|
  4609. @apii{0,1,m}
  4610. Pushes onto the stack a string identifying the current position
  4611. of the control at level @id{lvl} in the call stack.
  4612. Typically this string has the following format:
  4613. @verbatim{
  4614. @rep{chunkname}:@rep{currentline}:
  4615. }
  4616. @N{Level 0} is the running function,
  4617. @N{level 1} is the function that called the running function,
  4618. etc.
  4619. This function is used to build a prefix for error messages.
  4620. }
  4621. }
  4622. }
  4623. @C{-------------------------------------------------------------------------}
  4624. @sect1{libraries| @title{Standard Libraries}
  4625. The standard Lua libraries provide useful functions
  4626. that are implemented directly through the @N{C API}.
  4627. Some of these functions provide essential services to the language
  4628. (e.g., @Lid{type} and @Lid{getmetatable});
  4629. others provide access to @Q{outside} services (e.g., I/O);
  4630. and others could be implemented in Lua itself,
  4631. but are quite useful or have critical performance requirements that
  4632. deserve an implementation in C (e.g., @Lid{table.sort}).
  4633. All libraries are implemented through the official @N{C API}
  4634. and are provided as separate @N{C modules}.
  4635. Unless otherwise noted,
  4636. these library functions do not adjust its number of arguments
  4637. to its expected parameters.
  4638. For instance, a function documented as @T{foo(arg)}
  4639. should not be called without an argument.
  4640. Currently, Lua has the following standard libraries:
  4641. @itemize{
  4642. @item{@link{predefined|basic library};}
  4643. @item{@link{corolib|coroutine library};}
  4644. @item{@link{packlib|package library};}
  4645. @item{@link{strlib|string manipulation};}
  4646. @item{@link{utf8|basic UTF-8 support};}
  4647. @item{@link{tablib|table manipulation};}
  4648. @item{@link{mathlib|mathematical functions} (sin, log, etc.);}
  4649. @item{@link{iolib|input and output};}
  4650. @item{@link{oslib|operating system facilities};}
  4651. @item{@link{debuglib|debug facilities}.}
  4652. }
  4653. Except for the basic and the package libraries,
  4654. each library provides all its functions as fields of a global table
  4655. or as methods of its objects.
  4656. To have access to these libraries,
  4657. the @N{C host} program should call the @Lid{luaL_openlibs} function,
  4658. which opens all standard libraries.
  4659. Alternatively,
  4660. the host program can open them individually by using
  4661. @Lid{luaL_requiref} to call
  4662. @defid{luaopen_base} (for the basic library),
  4663. @defid{luaopen_package} (for the package library),
  4664. @defid{luaopen_coroutine} (for the coroutine library),
  4665. @defid{luaopen_string} (for the string library),
  4666. @defid{luaopen_utf8} (for the UTF8 library),
  4667. @defid{luaopen_table} (for the table library),
  4668. @defid{luaopen_math} (for the mathematical library),
  4669. @defid{luaopen_io} (for the I/O library),
  4670. @defid{luaopen_os} (for the operating system library),
  4671. and @defid{luaopen_debug} (for the debug library).
  4672. These functions are declared in @defid{lualib.h}.
  4673. @sect2{predefined| @title{Basic Functions}
  4674. The basic library provides core functions to Lua.
  4675. If you do not include this library in your application,
  4676. you should check carefully whether you need to provide
  4677. implementations for some of its facilities.
  4678. @LibEntry{assert (v [, message])|
  4679. Calls @Lid{error} if
  4680. the value of its argument @id{v} is false (i.e., @nil or @false);
  4681. otherwise, returns all its arguments.
  4682. In case of error,
  4683. @id{message} is the error object;
  4684. when absent, it defaults to @St{assertion failed!}
  4685. }
  4686. @LibEntry{collectgarbage ([opt [, arg]])|
  4687. This function is a generic interface to the garbage collector.
  4688. It performs different functions according to its first argument, @id{opt}:
  4689. @description{
  4690. @item{@St{collect}|
  4691. performs a full garbage-collection cycle.
  4692. This is the default option.
  4693. }
  4694. @item{@St{stop}|
  4695. stops automatic execution of the garbage collector.
  4696. The collector will run only when explicitly invoked,
  4697. until a call to restart it.
  4698. }
  4699. @item{@St{restart}|
  4700. restarts automatic execution of the garbage collector.
  4701. }
  4702. @item{@St{count}|
  4703. returns the total memory in use by Lua in Kbytes.
  4704. The value has a fractional part,
  4705. so that it multiplied by 1024
  4706. gives the exact number of bytes in use by Lua
  4707. (except for overflows).
  4708. }
  4709. @item{@St{step}|
  4710. performs a garbage-collection step.
  4711. The step @Q{size} is controlled by @id{arg}.
  4712. With a zero value,
  4713. the collector will perform one basic (indivisible) step.
  4714. For non-zero values,
  4715. the collector will perform as if that amount of memory
  4716. (in KBytes) had been allocated by Lua.
  4717. Returns @true if the step finished a collection cycle.
  4718. }
  4719. @item{@St{setpause}|
  4720. sets @id{arg} as the new value for the @emph{pause} of
  4721. the collector @see{GC}.
  4722. Returns the previous value for @emph{pause}.
  4723. }
  4724. @item{@St{incremental}|
  4725. Change the collector mode to incremental.
  4726. This option can be followed by three numbers:
  4727. the garbage-collector pause,
  4728. the step multiplier,
  4729. and the step size.
  4730. }
  4731. @item{@St{generational}|
  4732. Change the collector mode to generational.
  4733. This option can be followed by two numbers:
  4734. the garbage-collector minor multiplier
  4735. and the major multiplier.
  4736. }
  4737. @item{@St{isrunning}|
  4738. returns a boolean that tells whether the collector is running
  4739. (i.e., not stopped).
  4740. }
  4741. }
  4742. }
  4743. @LibEntry{dofile ([filename])|
  4744. Opens the named file and executes its contents as a Lua chunk.
  4745. When called without arguments,
  4746. @id{dofile} executes the contents of the standard input (@id{stdin}).
  4747. Returns all values returned by the chunk.
  4748. In case of errors, @id{dofile} propagates the error
  4749. to its caller (that is, @id{dofile} does not run in protected mode).
  4750. }
  4751. @LibEntry{error (message [, level])|
  4752. Terminates the last protected function called
  4753. and returns @id{message} as the error object.
  4754. Function @id{error} never returns.
  4755. Usually, @id{error} adds some information about the error position
  4756. at the beginning of the message, if the message is a string.
  4757. The @id{level} argument specifies how to get the error position.
  4758. With @N{level 1} (the default), the error position is where the
  4759. @id{error} function was called.
  4760. @N{Level 2} points the error to where the function
  4761. that called @id{error} was called; and so on.
  4762. Passing a @N{level 0} avoids the addition of error position information
  4763. to the message.
  4764. }
  4765. @LibEntry{_G|
  4766. A global variable (not a function) that
  4767. holds the @x{global environment} @see{globalenv}.
  4768. Lua itself does not use this variable;
  4769. changing its value does not affect any environment,
  4770. nor vice versa.
  4771. }
  4772. @LibEntry{getmetatable (object)|
  4773. If @id{object} does not have a metatable, returns @nil.
  4774. Otherwise,
  4775. if the object's metatable has a @idx{__metatable} field,
  4776. returns the associated value.
  4777. Otherwise, returns the metatable of the given object.
  4778. }
  4779. @LibEntry{ipairs (t)|
  4780. Returns three values (an iterator function, the table @id{t}, and 0)
  4781. so that the construction
  4782. @verbatim{
  4783. for i,v in ipairs(t) do @rep{body} end
  4784. }
  4785. will iterate over the key@En{}value pairs
  4786. (@T{1,t[1]}), (@T{2,t[2]}), @ldots,
  4787. up to the first absent index.
  4788. }
  4789. @LibEntry{load (chunk [, chunkname [, mode [, env]]])|
  4790. Loads a chunk.
  4791. If @id{chunk} is a string, the chunk is this string.
  4792. If @id{chunk} is a function,
  4793. @id{load} calls it repeatedly to get the chunk pieces.
  4794. Each call to @id{chunk} must return a string that concatenates
  4795. with previous results.
  4796. A return of an empty string, @nil, or no value signals the end of the chunk.
  4797. If there are no syntactic errors,
  4798. returns the compiled chunk as a function;
  4799. otherwise, returns @nil plus the error message.
  4800. When you load a main chunk,
  4801. the resulting function will always have exactly one upvalue,
  4802. the @id{_ENV} variable @see{globalenv}.
  4803. However,
  4804. when you load a binary chunk created from a function @seeF{string.dump},
  4805. the resulting function can have an arbitrary number of upvalues,
  4806. and there is no guarantee that its first upvalue will be
  4807. the @id{_ENV} variable.
  4808. (A non-main function may not even have an @id{_ENV} upvalue.)
  4809. Regardless, if the resulting function has any upvalues,
  4810. its first upvalue is set to the value of @id{env},
  4811. if that parameter is given,
  4812. or to the value of the @x{global environment}.
  4813. Other upvalues are initialized with @nil.
  4814. All upvalues are fresh, that is,
  4815. they are not shared with any other function.
  4816. @id{chunkname} is used as the name of the chunk for error messages
  4817. and debug information @see{debugI}.
  4818. When absent,
  4819. it defaults to @id{chunk}, if @id{chunk} is a string,
  4820. or to @St{=(load)} otherwise.
  4821. The string @id{mode} controls whether the chunk can be text or binary
  4822. (that is, a precompiled chunk).
  4823. It may be the string @St{b} (only @x{binary chunk}s),
  4824. @St{t} (only text chunks),
  4825. or @St{bt} (both binary and text).
  4826. The default is @St{bt}.
  4827. Lua does not check the consistency of binary chunks.
  4828. Maliciously crafted binary chunks can crash
  4829. the interpreter.
  4830. }
  4831. @LibEntry{loadfile ([filename [, mode [, env]]])|
  4832. Similar to @Lid{load},
  4833. but gets the chunk from file @id{filename}
  4834. or from the standard input,
  4835. if no file name is given.
  4836. }
  4837. @LibEntry{next (table [, index])|
  4838. Allows a program to traverse all fields of a table.
  4839. Its first argument is a table and its second argument
  4840. is an index in this table.
  4841. @id{next} returns the next index of the table
  4842. and its associated value.
  4843. When called with @nil as its second argument,
  4844. @id{next} returns an initial index
  4845. and its associated value.
  4846. When called with the last index,
  4847. or with @nil in an empty table,
  4848. @id{next} returns @nil.
  4849. If the second argument is absent, then it is interpreted as @nil.
  4850. In particular,
  4851. you can use @T{next(t)} to check whether a table is empty.
  4852. The order in which the indices are enumerated is not specified,
  4853. @emph{even for numeric indices}.
  4854. (To traverse a table in numerical order,
  4855. use a numerical @Rw{for}.)
  4856. The behavior of @id{next} is undefined if,
  4857. during the traversal,
  4858. you assign any value to a non-existent field in the table.
  4859. You may however modify existing fields.
  4860. In particular, you may set existing fields to nil.
  4861. }
  4862. @LibEntry{pairs (t)|
  4863. If @id{t} has a metamethod @idx{__pairs},
  4864. calls it with @id{t} as argument and returns the first three
  4865. results from the call.
  4866. Otherwise,
  4867. returns three values: the @Lid{next} function, the table @id{t}, and @nil,
  4868. so that the construction
  4869. @verbatim{
  4870. for k,v in pairs(t) do @rep{body} end
  4871. }
  4872. will iterate over all key@En{}value pairs of table @id{t}.
  4873. See function @Lid{next} for the caveats of modifying
  4874. the table during its traversal.
  4875. }
  4876. @LibEntry{pcall (f [, arg1, @Cdots])|
  4877. Calls function @id{f} with
  4878. the given arguments in @def{protected mode}.
  4879. This means that any error @N{inside @T{f}} is not propagated;
  4880. instead, @id{pcall} catches the error
  4881. and returns a status code.
  4882. Its first result is the status code (a boolean),
  4883. which is true if the call succeeds without errors.
  4884. In such case, @id{pcall} also returns all results from the call,
  4885. after this first result.
  4886. In case of any error, @id{pcall} returns @false plus the error message.
  4887. }
  4888. @LibEntry{print (@Cdots)|
  4889. Receives any number of arguments
  4890. and prints their values to @id{stdout},
  4891. using the @Lid{tostring} function to convert each argument to a string.
  4892. @id{print} is not intended for formatted output,
  4893. but only as a quick way to show a value,
  4894. for instance for debugging.
  4895. For complete control over the output,
  4896. use @Lid{string.format} and @Lid{io.write}.
  4897. }
  4898. @LibEntry{rawequal (v1, v2)|
  4899. Checks whether @id{v1} is equal to @id{v2},
  4900. without invoking the @idx{__eq} metamethod.
  4901. Returns a boolean.
  4902. }
  4903. @LibEntry{rawget (table, index)|
  4904. Gets the real value of @T{table[index]},
  4905. without invoking the @idx{__index} metamethod.
  4906. @id{table} must be a table;
  4907. @id{index} may be any value.
  4908. }
  4909. @LibEntry{rawlen (v)|
  4910. Returns the length of the object @id{v},
  4911. which must be a table or a string,
  4912. without invoking the @idx{__len} metamethod.
  4913. Returns an integer.
  4914. }
  4915. @LibEntry{rawset (table, index, value)|
  4916. Sets the real value of @T{table[index]} to @id{value},
  4917. without invoking the @idx{__newindex} metamethod.
  4918. @id{table} must be a table,
  4919. @id{index} any value different from @nil and @x{NaN},
  4920. and @id{value} any Lua value.
  4921. This function returns @id{table}.
  4922. }
  4923. @LibEntry{select (index, @Cdots)|
  4924. If @id{index} is a number,
  4925. returns all arguments after argument number @id{index};
  4926. a negative number indexes from the end (@num{-1} is the last argument).
  4927. Otherwise, @id{index} must be the string @T{"#"},
  4928. and @id{select} returns the total number of extra arguments it received.
  4929. }
  4930. @LibEntry{setmetatable (table, metatable)|
  4931. Sets the metatable for the given table.
  4932. (To change the metatable of other types from Lua code,
  4933. you must use the @link{debuglib|debug library}.)
  4934. If @id{metatable} is @nil,
  4935. removes the metatable of the given table.
  4936. If the original metatable has a @idx{__metatable} field,
  4937. raises an error.
  4938. This function returns @id{table}.
  4939. }
  4940. @LibEntry{tonumber (e [, base])|
  4941. When called with no @id{base},
  4942. @id{tonumber} tries to convert its argument to a number.
  4943. If the argument is already a number or
  4944. a string convertible to a number,
  4945. then @id{tonumber} returns this number;
  4946. otherwise, it returns @nil.
  4947. The conversion of strings can result in integers or floats,
  4948. according to the lexical conventions of Lua @see{lexical}.
  4949. (The string may have leading and trailing spaces and a sign.)
  4950. When called with @id{base},
  4951. then @id{e} must be a string to be interpreted as
  4952. an integer numeral in that base.
  4953. The base may be any integer between 2 and 36, inclusive.
  4954. In bases @N{above 10}, the letter @Char{A} (in either upper or lower case)
  4955. @N{represents 10}, @Char{B} @N{represents 11}, and so forth,
  4956. with @Char{Z} representing 35.
  4957. If the string @id{e} is not a valid numeral in the given base,
  4958. the function returns @nil.
  4959. }
  4960. @LibEntry{tostring (v)|
  4961. Receives a value of any type and
  4962. converts it to a string in a human-readable format.
  4963. (For complete control of how numbers are converted,
  4964. use @Lid{string.format}.)
  4965. If the metatable of @id{v} has a @idx{__tostring} field,
  4966. then @id{tostring} calls the corresponding value
  4967. with @id{v} as argument,
  4968. and uses the result of the call as its result.
  4969. }
  4970. @LibEntry{type (v)|
  4971. Returns the type of its only argument, coded as a string.
  4972. The possible results of this function are
  4973. @St{nil} (a string, not the value @nil),
  4974. @St{number},
  4975. @St{string},
  4976. @St{boolean},
  4977. @St{table},
  4978. @St{function},
  4979. @St{thread},
  4980. and @St{userdata}.
  4981. }
  4982. @LibEntry{_VERSION|
  4983. A global variable (not a function) that
  4984. holds a string containing the running Lua version.
  4985. The current value of this variable is @St{Lua 5.4}.
  4986. }
  4987. @LibEntry{warn (message [, tocont])|
  4988. Emits a warning with the given message.
  4989. A message in a call with @id{tocont} true should be
  4990. continued in another call to this function.
  4991. The default for @id{tocont} is false.
  4992. }
  4993. @LibEntry{xpcall (f, msgh [, arg1, @Cdots])|
  4994. This function is similar to @Lid{pcall},
  4995. except that it sets a new @x{message handler} @id{msgh}.
  4996. }
  4997. }
  4998. @sect2{corolib| @title{Coroutine Manipulation}
  4999. This library comprises the operations to manipulate coroutines,
  5000. which come inside the table @defid{coroutine}.
  5001. See @See{coroutine} for a general description of coroutines.
  5002. @LibEntry{coroutine.create (f)|
  5003. Creates a new coroutine, with body @id{f}.
  5004. @id{f} must be a function.
  5005. Returns this new coroutine,
  5006. an object with type @T{"thread"}.
  5007. }
  5008. @LibEntry{coroutine.isyieldable ()|
  5009. Returns true when the running coroutine can yield.
  5010. A running coroutine is yieldable if it is not the main thread and
  5011. it is not inside a non-yieldable @N{C function}.
  5012. }
  5013. @LibEntry{coroutine.kill(co)|
  5014. Kills coroutine @id{co},
  5015. closing all its pending to-be-closed variables
  5016. and putting the coroutine in a dead state.
  5017. In case of error closing some variable,
  5018. returns @false plus the error object;
  5019. otherwise returns @true.
  5020. }
  5021. @LibEntry{coroutine.resume (co [, val1, @Cdots])|
  5022. Starts or continues the execution of coroutine @id{co}.
  5023. The first time you resume a coroutine,
  5024. it starts running its body.
  5025. The values @id{val1}, @ldots are passed
  5026. as the arguments to the body function.
  5027. If the coroutine has yielded,
  5028. @id{resume} restarts it;
  5029. the values @id{val1}, @ldots are passed
  5030. as the results from the yield.
  5031. If the coroutine runs without any errors,
  5032. @id{resume} returns @true plus any values passed to @id{yield}
  5033. (when the coroutine yields) or any values returned by the body function
  5034. (when the coroutine terminates).
  5035. If there is any error,
  5036. @id{resume} returns @false plus the error message.
  5037. }
  5038. @LibEntry{coroutine.running ()|
  5039. Returns the running coroutine plus a boolean,
  5040. true when the running coroutine is the main one.
  5041. }
  5042. @LibEntry{coroutine.status (co)|
  5043. Returns the status of coroutine @id{co}, as a string:
  5044. @T{"running"},
  5045. if the coroutine is running (that is, it called @id{status});
  5046. @T{"suspended"}, if the coroutine is suspended in a call to @id{yield},
  5047. or if it has not started running yet;
  5048. @T{"normal"} if the coroutine is active but not running
  5049. (that is, it has resumed another coroutine);
  5050. and @T{"dead"} if the coroutine has finished its body function,
  5051. or if it has stopped with an error.
  5052. }
  5053. @LibEntry{coroutine.wrap (f)|
  5054. Creates a new coroutine, with body @id{f}.
  5055. @id{f} must be a function.
  5056. Returns a function that resumes the coroutine each time it is called.
  5057. Any arguments passed to the function behave as the
  5058. extra arguments to @id{resume}.
  5059. Returns the same values returned by @id{resume},
  5060. except the first boolean.
  5061. In case of error, propagates the error.
  5062. }
  5063. @LibEntry{coroutine.yield (@Cdots)|
  5064. Suspends the execution of the calling coroutine.
  5065. Any arguments to @id{yield} are passed as extra results to @id{resume}.
  5066. }
  5067. }
  5068. @sect2{packlib| @title{Modules}
  5069. The package library provides basic
  5070. facilities for loading modules in Lua.
  5071. It exports one function directly in the global environment:
  5072. @Lid{require}.
  5073. Everything else is exported in a table @defid{package}.
  5074. @LibEntry{require (modname)|
  5075. Loads the given module.
  5076. The function starts by looking into the @Lid{package.loaded} table
  5077. to determine whether @id{modname} is already loaded.
  5078. If it is, then @id{require} returns the value stored
  5079. at @T{package.loaded[modname]}.
  5080. Otherwise, it tries to find a @emph{loader} for the module.
  5081. To find a loader,
  5082. @id{require} is guided by the @Lid{package.searchers} sequence.
  5083. By changing this sequence,
  5084. we can change how @id{require} looks for a module.
  5085. The following explanation is based on the default configuration
  5086. for @Lid{package.searchers}.
  5087. First @id{require} queries @T{package.preload[modname]}.
  5088. If it has a value,
  5089. this value (which must be a function) is the loader.
  5090. Otherwise @id{require} searches for a Lua loader using the
  5091. path stored in @Lid{package.path}.
  5092. If that also fails, it searches for a @N{C loader} using the
  5093. path stored in @Lid{package.cpath}.
  5094. If that also fails,
  5095. it tries an @emph{all-in-one} loader @seeF{package.searchers}.
  5096. Once a loader is found,
  5097. @id{require} calls the loader with two arguments:
  5098. @id{modname} and an extra value dependent on how it got the loader.
  5099. (If the loader came from a file,
  5100. this extra value is the file name.)
  5101. If the loader returns any non-nil value,
  5102. @id{require} assigns the returned value to @T{package.loaded[modname]}.
  5103. If the loader does not return a non-nil value and
  5104. has not assigned any value to @T{package.loaded[modname]},
  5105. then @id{require} assigns @Rw{true} to this entry.
  5106. In any case, @id{require} returns the
  5107. final value of @T{package.loaded[modname]}.
  5108. If there is any error loading or running the module,
  5109. or if it cannot find any loader for the module,
  5110. then @id{require} raises an error.
  5111. }
  5112. @LibEntry{package.config|
  5113. A string describing some compile-time configurations for packages.
  5114. This string is a sequence of lines:
  5115. @itemize{
  5116. @item{The first line is the @x{directory separator} string.
  5117. Default is @Char{\} for @x{Windows} and @Char{/} for all other systems.}
  5118. @item{The second line is the character that separates templates in a path.
  5119. Default is @Char{;}.}
  5120. @item{The third line is the string that marks the
  5121. substitution points in a template.
  5122. Default is @Char{?}.}
  5123. @item{The fourth line is a string that, in a path in @x{Windows},
  5124. is replaced by the executable's directory.
  5125. Default is @Char{!}.}
  5126. @item{The fifth line is a mark to ignore all text after it
  5127. when building the @id{luaopen_} function name.
  5128. Default is @Char{-}.}
  5129. }
  5130. }
  5131. @LibEntry{package.cpath|
  5132. The path used by @Lid{require} to search for a @N{C loader}.
  5133. Lua initializes the @N{C path} @Lid{package.cpath} in the same way
  5134. it initializes the Lua path @Lid{package.path},
  5135. using the environment variable @defid{LUA_CPATH_5_4},
  5136. or the environment variable @defid{LUA_CPATH},
  5137. or a default path defined in @id{luaconf.h}.
  5138. }
  5139. @LibEntry{package.loaded|
  5140. A table used by @Lid{require} to control which
  5141. modules are already loaded.
  5142. When you require a module @id{modname} and
  5143. @T{package.loaded[modname]} is not false,
  5144. @Lid{require} simply returns the value stored there.
  5145. This variable is only a reference to the real table;
  5146. assignments to this variable do not change the
  5147. table used by @Lid{require}.
  5148. }
  5149. @LibEntry{package.loadlib (libname, funcname)|
  5150. Dynamically links the host program with the @N{C library} @id{libname}.
  5151. If @id{funcname} is @St{*},
  5152. then it only links with the library,
  5153. making the symbols exported by the library
  5154. available to other dynamically linked libraries.
  5155. Otherwise,
  5156. it looks for a function @id{funcname} inside the library
  5157. and returns this function as a @N{C function}.
  5158. So, @id{funcname} must follow the @Lid{lua_CFunction} prototype
  5159. @seeC{lua_CFunction}.
  5160. This is a low-level function.
  5161. It completely bypasses the package and module system.
  5162. Unlike @Lid{require},
  5163. it does not perform any path searching and
  5164. does not automatically adds extensions.
  5165. @id{libname} must be the complete file name of the @N{C library},
  5166. including if necessary a path and an extension.
  5167. @id{funcname} must be the exact name exported by the @N{C library}
  5168. (which may depend on the @N{C compiler} and linker used).
  5169. This function is not supported by @N{Standard C}.
  5170. As such, it is only available on some platforms
  5171. (Windows, Linux, Mac OS X, Solaris, BSD,
  5172. plus other Unix systems that support the @id{dlfcn} standard).
  5173. }
  5174. @LibEntry{package.path|
  5175. The path used by @Lid{require} to search for a Lua loader.
  5176. At start-up, Lua initializes this variable with
  5177. the value of the environment variable @defid{LUA_PATH_5_4} or
  5178. the environment variable @defid{LUA_PATH} or
  5179. with a default path defined in @id{luaconf.h},
  5180. if those environment variables are not defined.
  5181. Any @St{;;} in the value of the environment variable
  5182. is replaced by the default path.
  5183. }
  5184. @LibEntry{package.preload|
  5185. A table to store loaders for specific modules
  5186. @seeF{require}.
  5187. This variable is only a reference to the real table;
  5188. assignments to this variable do not change the
  5189. table used by @Lid{require}.
  5190. }
  5191. @LibEntry{package.searchers|
  5192. A table used by @Lid{require} to control how to load modules.
  5193. Each entry in this table is a @def{searcher function}.
  5194. When looking for a module,
  5195. @Lid{require} calls each of these searchers in ascending order,
  5196. with the module name (the argument given to @Lid{require}) as its
  5197. sole argument.
  5198. The function can return another function (the module @def{loader})
  5199. plus an extra value that will be passed to that loader,
  5200. or a string explaining why it did not find that module
  5201. (or @nil if it has nothing to say).
  5202. Lua initializes this table with four searcher functions.
  5203. The first searcher simply looks for a loader in the
  5204. @Lid{package.preload} table.
  5205. The second searcher looks for a loader as a Lua library,
  5206. using the path stored at @Lid{package.path}.
  5207. The search is done as described in function @Lid{package.searchpath}.
  5208. The third searcher looks for a loader as a @N{C library},
  5209. using the path given by the variable @Lid{package.cpath}.
  5210. Again,
  5211. the search is done as described in function @Lid{package.searchpath}.
  5212. For instance,
  5213. if the @N{C path} is the string
  5214. @verbatim{
  5215. "./?.so;./?.dll;/usr/local/?/init.so"
  5216. }
  5217. the searcher for module @id{foo}
  5218. will try to open the files @T{./foo.so}, @T{./foo.dll},
  5219. and @T{/usr/local/foo/init.so}, in that order.
  5220. Once it finds a @N{C library},
  5221. this searcher first uses a dynamic link facility to link the
  5222. application with the library.
  5223. Then it tries to find a @N{C function} inside the library to
  5224. be used as the loader.
  5225. The name of this @N{C function} is the string @St{luaopen_}
  5226. concatenated with a copy of the module name where each dot
  5227. is replaced by an underscore.
  5228. Moreover, if the module name has a hyphen,
  5229. its suffix after (and including) the first hyphen is removed.
  5230. For instance, if the module name is @id{a.b.c-v2.1},
  5231. the function name will be @id{luaopen_a_b_c}.
  5232. The fourth searcher tries an @def{all-in-one loader}.
  5233. It searches the @N{C path} for a library for
  5234. the root name of the given module.
  5235. For instance, when requiring @id{a.b.c},
  5236. it will search for a @N{C library} for @id{a}.
  5237. If found, it looks into it for an open function for
  5238. the submodule;
  5239. in our example, that would be @id{luaopen_a_b_c}.
  5240. With this facility, a package can pack several @N{C submodules}
  5241. into one single library,
  5242. with each submodule keeping its original open function.
  5243. All searchers except the first one (preload) return as the extra value
  5244. the file name where the module was found,
  5245. as returned by @Lid{package.searchpath}.
  5246. The first searcher returns no extra value.
  5247. }
  5248. @LibEntry{package.searchpath (name, path [, sep [, rep]])|
  5249. Searches for the given @id{name} in the given @id{path}.
  5250. A path is a string containing a sequence of
  5251. @emph{templates} separated by semicolons.
  5252. For each template,
  5253. the function replaces each interrogation mark (if any)
  5254. in the template with a copy of @id{name}
  5255. wherein all occurrences of @id{sep}
  5256. (a dot, by default)
  5257. were replaced by @id{rep}
  5258. (the system's directory separator, by default),
  5259. and then tries to open the resulting file name.
  5260. For instance, if the path is the string
  5261. @verbatim{
  5262. "./?.lua;./?.lc;/usr/local/?/init.lua"
  5263. }
  5264. the search for the name @id{foo.a}
  5265. will try to open the files
  5266. @T{./foo/a.lua}, @T{./foo/a.lc}, and
  5267. @T{/usr/local/foo/a/init.lua}, in that order.
  5268. Returns the resulting name of the first file that it can
  5269. open in read mode (after closing the file),
  5270. or @nil plus an error message if none succeeds.
  5271. (This error message lists all file names it tried to open.)
  5272. }
  5273. }
  5274. @sect2{strlib| @title{String Manipulation}
  5275. This library provides generic functions for string manipulation,
  5276. such as finding and extracting substrings, and pattern matching.
  5277. When indexing a string in Lua, the first character is at @N{position 1}
  5278. (not @N{at 0}, as in C).
  5279. Indices are allowed to be negative and are interpreted as indexing backwards,
  5280. from the end of the string.
  5281. Thus, the last character is at position @num{-1}, and so on.
  5282. The string library provides all its functions inside the table
  5283. @defid{string}.
  5284. It also sets a @x{metatable for strings}
  5285. where the @idx{__index} field points to the @id{string} table.
  5286. Therefore, you can use the string functions in object-oriented style.
  5287. For instance, @T{string.byte(s,i)}
  5288. can be written as @T{s:byte(i)}.
  5289. The string library assumes one-byte character encodings.
  5290. @LibEntry{string.byte (s [, i [, j]])|
  5291. Returns the internal numeric codes of the characters @T{s[i]},
  5292. @T{s[i+1]}, @ldots, @T{s[j]}.
  5293. The default value for @id{i} @N{is 1};
  5294. the default value for @id{j} @N{is @id{i}}.
  5295. These indices are corrected
  5296. following the same rules of function @Lid{string.sub}.
  5297. Numeric codes are not necessarily portable across platforms.
  5298. }
  5299. @LibEntry{string.char (@Cdots)|
  5300. Receives zero or more integers.
  5301. Returns a string with length equal to the number of arguments,
  5302. in which each character has the internal numeric code equal
  5303. to its corresponding argument.
  5304. Numeric codes are not necessarily portable across platforms.
  5305. }
  5306. @LibEntry{string.dump (function [, strip])|
  5307. Returns a string containing a binary representation
  5308. (a @emph{binary chunk})
  5309. of the given function,
  5310. so that a later @Lid{load} on this string returns
  5311. a copy of the function (but with new upvalues).
  5312. If @id{strip} is a true value,
  5313. the binary representation may not include all debug information
  5314. about the function,
  5315. to save space.
  5316. Functions with upvalues have only their number of upvalues saved.
  5317. When (re)loaded,
  5318. those upvalues receive fresh instances.
  5319. (See the @Lid{load} function for details about
  5320. how these upvalues are initialized.
  5321. You can use the debug library to serialize
  5322. and reload the upvalues of a function
  5323. in a way adequate to your needs.)
  5324. }
  5325. @LibEntry{string.find (s, pattern [, init [, plain]])|
  5326. Looks for the first match of
  5327. @id{pattern} @see{pm} in the string @id{s}.
  5328. If it finds a match, then @id{find} returns the indices @N{of @T{s}}
  5329. where this occurrence starts and ends;
  5330. otherwise, it returns @nil.
  5331. A third, optional numeric argument @id{init} specifies
  5332. where to start the search;
  5333. its default value @N{is 1} and can be negative.
  5334. A value of @true as a fourth, optional argument @id{plain}
  5335. turns off the pattern matching facilities,
  5336. so the function does a plain @Q{find substring} operation,
  5337. with no characters in @id{pattern} being considered magic.
  5338. Note that if @id{plain} is given, then @id{init} must be given as well.
  5339. If the pattern has captures,
  5340. then in a successful match
  5341. the captured values are also returned,
  5342. after the two indices.
  5343. }
  5344. @LibEntry{string.format (formatstring, @Cdots)|
  5345. Returns a formatted version of its variable number of arguments
  5346. following the description given in its first argument (which must be a string).
  5347. The format string follows the same rules as the @ANSI{sprintf}.
  5348. The only differences are that the conversion specifiers and modifiers
  5349. @T{*}, @id{h}, @id{L}, @id{l}, and @id{n} are not supported
  5350. and that there is an extra specifier, @id{q}.
  5351. The specifier @id{q} formats booleans, nil, numbers, and strings
  5352. in a way that the result is a valid constant in Lua source code.
  5353. Booleans and nil are written in the obvious way
  5354. (@id{true}, @id{false}, @id{nil}).
  5355. Floats are written in hexadecimal,
  5356. to preserve full precision.
  5357. A string is written between double quotes,
  5358. using escape sequences when necessary to ensure that
  5359. it can safely be read back by the Lua interpreter.
  5360. For instance, the call
  5361. @verbatim{
  5362. string.format('%q', 'a string with "quotes" and \n new line')
  5363. }
  5364. may produce the string:
  5365. @verbatim{
  5366. "a string with \"quotes\" and \
  5367. new line"
  5368. }
  5369. This specifier does not support modifiers (flags, width, length).
  5370. The conversion specifiers
  5371. @id{A}, @id{a}, @id{E}, @id{e}, @id{f},
  5372. @id{G}, and @id{g} all expect a number as argument.
  5373. The specifiers @id{c}, @id{d},
  5374. @id{i}, @id{o}, @id{u}, @id{X}, and @id{x}
  5375. expect an integer.
  5376. When Lua is compiled with a C89 compiler,
  5377. the specifiers @id{A} and @id{a} (hexadecimal floats)
  5378. do not support modifiers.
  5379. The specifier @id{s} expects a string;
  5380. if its argument is not a string,
  5381. it is converted to one following the same rules of @Lid{tostring}.
  5382. If the specifier has any modifier,
  5383. the corresponding string argument should not contain @x{embedded zeros}.
  5384. The specifier @id{p} formats the pointer
  5385. returned by @Lid{lua_topointer}.
  5386. That gives a unique string identifier for tables, userdata,
  5387. threads, strings, and functions.
  5388. For other values (numbers, nil, booleans),
  5389. this specifier results in a string representing
  5390. the pointer @id{NULL}.
  5391. }
  5392. @LibEntry{string.gmatch (s, pattern [, init])|
  5393. Returns an iterator function that,
  5394. each time it is called,
  5395. returns the next captures from @id{pattern} @see{pm}
  5396. over the string @id{s}.
  5397. If @id{pattern} specifies no captures,
  5398. then the whole match is produced in each call.
  5399. A third, optional numeric argument @id{init} specifies
  5400. where to start the search;
  5401. its default value @N{is 1} and can be negative.
  5402. As an example, the following loop
  5403. will iterate over all the words from string @id{s},
  5404. printing one per line:
  5405. @verbatim{
  5406. s = "hello world from Lua"
  5407. for w in string.gmatch(s, "%a+") do
  5408. print(w)
  5409. end
  5410. }
  5411. The next example collects all pairs @T{key=value} from the
  5412. given string into a table:
  5413. @verbatim{
  5414. t = {}
  5415. s = "from=world, to=Lua"
  5416. for k, v in string.gmatch(s, "(%w+)=(%w+)") do
  5417. t[k] = v
  5418. end
  5419. }
  5420. For this function, a caret @Char{^} at the start of a pattern does not
  5421. work as an anchor, as this would prevent the iteration.
  5422. }
  5423. @LibEntry{string.gsub (s, pattern, repl [, n])|
  5424. Returns a copy of @id{s}
  5425. in which all (or the first @id{n}, if given)
  5426. occurrences of the @id{pattern} @see{pm} have been
  5427. replaced by a replacement string specified by @id{repl},
  5428. which can be a string, a table, or a function.
  5429. @id{gsub} also returns, as its second value,
  5430. the total number of matches that occurred.
  5431. The name @id{gsub} comes from @emph{Global SUBstitution}.
  5432. If @id{repl} is a string, then its value is used for replacement.
  5433. The @N{character @T{%}} works as an escape character:
  5434. any sequence in @id{repl} of the form @T{%@rep{d}},
  5435. with @rep{d} between 1 and 9,
  5436. stands for the value of the @rep{d}-th captured substring.
  5437. The sequence @T{%0} stands for the whole match.
  5438. The sequence @T{%%} stands for a @N{single @T{%}}.
  5439. If @id{repl} is a table, then the table is queried for every match,
  5440. using the first capture as the key.
  5441. If @id{repl} is a function, then this function is called every time a
  5442. match occurs, with all captured substrings passed as arguments,
  5443. in order.
  5444. In any case,
  5445. if the pattern specifies no captures,
  5446. then it behaves as if the whole pattern was inside a capture.
  5447. If the value returned by the table query or by the function call
  5448. is a string or a number,
  5449. then it is used as the replacement string;
  5450. otherwise, if it is @Rw{false} or @nil,
  5451. then there is no replacement
  5452. (that is, the original match is kept in the string).
  5453. Here are some examples:
  5454. @verbatim{
  5455. x = string.gsub("hello world", "(%w+)", "%1 %1")
  5456. --> x="hello hello world world"
  5457. x = string.gsub("hello world", "%w+", "%0 %0", 1)
  5458. --> x="hello hello world"
  5459. x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
  5460. --> x="world hello Lua from"
  5461. x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
  5462. --> x="home = /home/roberto, user = roberto"
  5463. x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
  5464. return load(s)()
  5465. end)
  5466. --> x="4+5 = 9"
  5467. local t = {name="lua", version="5.4"}
  5468. x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
  5469. --> x="lua-5.4.tar.gz"
  5470. }
  5471. }
  5472. @LibEntry{string.len (s)|
  5473. Receives a string and returns its length.
  5474. The empty string @T{""} has length 0.
  5475. Embedded zeros are counted,
  5476. so @T{"a\000bc\000"} has length 5.
  5477. }
  5478. @LibEntry{string.lower (s)|
  5479. Receives a string and returns a copy of this string with all
  5480. uppercase letters changed to lowercase.
  5481. All other characters are left unchanged.
  5482. The definition of what an uppercase letter is depends on the current locale.
  5483. }
  5484. @LibEntry{string.match (s, pattern [, init])|
  5485. Looks for the first @emph{match} of
  5486. @id{pattern} @see{pm} in the string @id{s}.
  5487. If it finds one, then @id{match} returns
  5488. the captures from the pattern;
  5489. otherwise it returns @nil.
  5490. If @id{pattern} specifies no captures,
  5491. then the whole match is returned.
  5492. A third, optional numeric argument @id{init} specifies
  5493. where to start the search;
  5494. its default value @N{is 1} and can be negative.
  5495. }
  5496. @LibEntry{string.pack (fmt, v1, v2, @Cdots)|
  5497. Returns a binary string containing the values @id{v1}, @id{v2}, etc.
  5498. packed (that is, serialized in binary form)
  5499. according to the format string @id{fmt} @see{pack}.
  5500. }
  5501. @LibEntry{string.packsize (fmt)|
  5502. Returns the size of a string resulting from @Lid{string.pack}
  5503. with the given format.
  5504. The format string cannot have the variable-length options
  5505. @Char{s} or @Char{z} @see{pack}.
  5506. }
  5507. @LibEntry{string.rep (s, n [, sep])|
  5508. Returns a string that is the concatenation of @id{n} copies of
  5509. the string @id{s} separated by the string @id{sep}.
  5510. The default value for @id{sep} is the empty string
  5511. (that is, no separator).
  5512. Returns the empty string if @id{n} is not positive.
  5513. (Note that it is very easy to exhaust the memory of your machine
  5514. with a single call to this function.)
  5515. }
  5516. @LibEntry{string.reverse (s)|
  5517. Returns a string that is the string @id{s} reversed.
  5518. }
  5519. @LibEntry{string.sub (s, i [, j])|
  5520. Returns the substring of @id{s} that
  5521. starts at @id{i} and continues until @id{j};
  5522. @id{i} and @id{j} can be negative.
  5523. If @id{j} is absent, then it is assumed to be equal to @num{-1}
  5524. (which is the same as the string length).
  5525. In particular,
  5526. the call @T{string.sub(s,1,j)} returns a prefix of @id{s}
  5527. with length @id{j},
  5528. and @T{string.sub(s, -i)} (for a positive @id{i})
  5529. returns a suffix of @id{s}
  5530. with length @id{i}.
  5531. If, after the translation of negative indices,
  5532. @id{i} is less than 1,
  5533. it is corrected to 1.
  5534. If @id{j} is greater than the string length,
  5535. it is corrected to that length.
  5536. If, after these corrections,
  5537. @id{i} is greater than @id{j},
  5538. the function returns the empty string.
  5539. }
  5540. @LibEntry{string.unpack (fmt, s [, pos])|
  5541. Returns the values packed in string @id{s} @seeF{string.pack}
  5542. according to the format string @id{fmt} @see{pack}.
  5543. An optional @id{pos} marks where
  5544. to start reading in @id{s} (default is 1).
  5545. After the read values,
  5546. this function also returns the index of the first unread byte in @id{s}.
  5547. }
  5548. @LibEntry{string.upper (s)|
  5549. Receives a string and returns a copy of this string with all
  5550. lowercase letters changed to uppercase.
  5551. All other characters are left unchanged.
  5552. The definition of what a lowercase letter is depends on the current locale.
  5553. }
  5554. @sect3{pm| @title{Patterns}
  5555. Patterns in Lua are described by regular strings,
  5556. which are interpreted as patterns by the pattern-matching functions
  5557. @Lid{string.find},
  5558. @Lid{string.gmatch},
  5559. @Lid{string.gsub},
  5560. and @Lid{string.match}.
  5561. This section describes the syntax and the meaning
  5562. (that is, what they match) of these strings.
  5563. @sect4{@title{Character Class:}
  5564. A @def{character class} is used to represent a set of characters.
  5565. The following combinations are allowed in describing a character class:
  5566. @description{
  5567. @item{@rep{x}|
  5568. (where @rep{x} is not one of the @emphx{magic characters}
  5569. @T{^$()%.[]*+-?})
  5570. represents the character @emph{x} itself.
  5571. }
  5572. @item{@T{.}| (a dot) represents all characters.}
  5573. @item{@T{%a}| represents all letters.}
  5574. @item{@T{%c}| represents all control characters.}
  5575. @item{@T{%d}| represents all digits.}
  5576. @item{@T{%g}| represents all printable characters except space.}
  5577. @item{@T{%l}| represents all lowercase letters.}
  5578. @item{@T{%p}| represents all punctuation characters.}
  5579. @item{@T{%s}| represents all space characters.}
  5580. @item{@T{%u}| represents all uppercase letters.}
  5581. @item{@T{%w}| represents all alphanumeric characters.}
  5582. @item{@T{%x}| represents all hexadecimal digits.}
  5583. @item{@T{%@rep{x}}| (where @rep{x} is any non-alphanumeric character)
  5584. represents the character @rep{x}.
  5585. This is the standard way to escape the magic characters.
  5586. Any non-alphanumeric character
  5587. (including all punctuation characters, even the non-magical)
  5588. can be preceded by a @Char{%}
  5589. when used to represent itself in a pattern.
  5590. }
  5591. @item{@T{[@rep{set}]}|
  5592. represents the class which is the union of all
  5593. characters in @rep{set}.
  5594. A range of characters can be specified by
  5595. separating the end characters of the range,
  5596. in ascending order, with a @Char{-}.
  5597. All classes @T{%}@emph{x} described above can also be used as
  5598. components in @rep{set}.
  5599. All other characters in @rep{set} represent themselves.
  5600. For example, @T{[%w_]} (or @T{[_%w]})
  5601. represents all alphanumeric characters plus the underscore,
  5602. @T{[0-7]} represents the octal digits,
  5603. and @T{[0-7%l%-]} represents the octal digits plus
  5604. the lowercase letters plus the @Char{-} character.
  5605. You can put a closing square bracket in a set
  5606. by positioning it as the first character in the set.
  5607. You can put a hyphen in a set
  5608. by positioning it as the first or the last character in the set.
  5609. (You can also use an escape for both cases.)
  5610. The interaction between ranges and classes is not defined.
  5611. Therefore, patterns like @T{[%a-z]} or @T{[a-%%]}
  5612. have no meaning.
  5613. }
  5614. @item{@T{[^@rep{set}]}|
  5615. represents the complement of @rep{set},
  5616. where @rep{set} is interpreted as above.
  5617. }
  5618. }
  5619. For all classes represented by single letters (@T{%a}, @T{%c}, etc.),
  5620. the corresponding uppercase letter represents the complement of the class.
  5621. For instance, @T{%S} represents all non-space characters.
  5622. The definitions of letter, space, and other character groups
  5623. depend on the current locale.
  5624. In particular, the class @T{[a-z]} may not be equivalent to @T{%l}.
  5625. }
  5626. @sect4{@title{Pattern Item:}
  5627. A @def{pattern item} can be
  5628. @itemize{
  5629. @item{
  5630. a single character class,
  5631. which matches any single character in the class;
  5632. }
  5633. @item{
  5634. a single character class followed by @Char{*},
  5635. which matches zero or more repetitions of characters in the class.
  5636. These repetition items will always match the longest possible sequence;
  5637. }
  5638. @item{
  5639. a single character class followed by @Char{+},
  5640. which matches one or more repetitions of characters in the class.
  5641. These repetition items will always match the longest possible sequence;
  5642. }
  5643. @item{
  5644. a single character class followed by @Char{-},
  5645. which also matches zero or more repetitions of characters in the class.
  5646. Unlike @Char{*},
  5647. these repetition items will always match the shortest possible sequence;
  5648. }
  5649. @item{
  5650. a single character class followed by @Char{?},
  5651. which matches zero or one occurrence of a character in the class.
  5652. It always matches one occurrence if possible;
  5653. }
  5654. @item{
  5655. @T{%@rep{n}}, for @rep{n} between 1 and 9;
  5656. such item matches a substring equal to the @rep{n}-th captured string
  5657. (see below);
  5658. }
  5659. @item{
  5660. @T{%b@rep{xy}}, where @rep{x} and @rep{y} are two distinct characters;
  5661. such item matches strings that start @N{with @rep{x}}, end @N{with @rep{y}},
  5662. and where the @rep{x} and @rep{y} are @emph{balanced}.
  5663. This means that, if one reads the string from left to right,
  5664. counting @M{+1} for an @rep{x} and @M{-1} for a @rep{y},
  5665. the ending @rep{y} is the first @rep{y} where the count reaches 0.
  5666. For instance, the item @T{%b()} matches expressions with
  5667. balanced parentheses.
  5668. }
  5669. @item{
  5670. @T{%f[@rep{set}]}, a @def{frontier pattern};
  5671. such item matches an empty string at any position such that
  5672. the next character belongs to @rep{set}
  5673. and the previous character does not belong to @rep{set}.
  5674. The set @rep{set} is interpreted as previously described.
  5675. The beginning and the end of the subject are handled as if
  5676. they were the character @Char{\0}.
  5677. }
  5678. }
  5679. }
  5680. @sect4{@title{Pattern:}
  5681. A @def{pattern} is a sequence of pattern items.
  5682. A caret @Char{^} at the beginning of a pattern anchors the match at the
  5683. beginning of the subject string.
  5684. A @Char{$} at the end of a pattern anchors the match at the
  5685. end of the subject string.
  5686. At other positions,
  5687. @Char{^} and @Char{$} have no special meaning and represent themselves.
  5688. }
  5689. @sect4{@title{Captures:}
  5690. A pattern can contain sub-patterns enclosed in parentheses;
  5691. they describe @def{captures}.
  5692. When a match succeeds, the substrings of the subject string
  5693. that match captures are stored (@emph{captured}) for future use.
  5694. Captures are numbered according to their left parentheses.
  5695. For instance, in the pattern @T{"(a*(.)%w(%s*))"},
  5696. the part of the string matching @T{"a*(.)%w(%s*)"} is
  5697. stored as the first capture (and therefore has @N{number 1});
  5698. the character matching @St{.} is captured with @N{number 2},
  5699. and the part matching @St{%s*} has @N{number 3}.
  5700. As a special case, the empty capture @T{()} captures
  5701. the current string position (a number).
  5702. For instance, if we apply the pattern @T{"()aa()"} on the
  5703. string @T{"flaaap"}, there will be two captures: @N{3 and 5}.
  5704. }
  5705. @sect4{@title{Multiple matches:}
  5706. The function @Lid{string.gsub} and the iterator @Lid{string.gmatch}
  5707. match multiple occurrences of the given pattern in the subject.
  5708. For these functions,
  5709. a new match is considered valid only
  5710. if it ends at least one byte after the previous match.
  5711. In other words, the pattern machine never accepts the
  5712. empty string as a match immediately after another match.
  5713. As an example,
  5714. consider the results of the following code:
  5715. @verbatim{
  5716. > string.gsub("abc", "()a*()", print);
  5717. --> 1 2
  5718. --> 3 3
  5719. --> 4 4
  5720. }
  5721. The second and third results come from Lua matching an empty
  5722. string after @Char{b} and another one after @Char{c}.
  5723. Lua does not match an empty string after @Char{a},
  5724. because it would end at the same position of the previous match.
  5725. }
  5726. }
  5727. @sect3{pack| @title{Format Strings for Pack and Unpack}
  5728. The first argument to @Lid{string.pack},
  5729. @Lid{string.packsize}, and @Lid{string.unpack}
  5730. is a format string,
  5731. which describes the layout of the structure being created or read.
  5732. A format string is a sequence of conversion options.
  5733. The conversion options are as follows:
  5734. @description{
  5735. @item{@T{<}|sets little endian}
  5736. @item{@T{>}|sets big endian}
  5737. @item{@T{=}|sets native endian}
  5738. @item{@T{![@rep{n}]}|sets maximum alignment to @id{n}
  5739. (default is native alignment)}
  5740. @item{@T{b}|a signed byte (@id{char})}
  5741. @item{@T{B}|an unsigned byte (@id{char})}
  5742. @item{@T{h}|a signed @id{short} (native size)}
  5743. @item{@T{H}|an unsigned @id{short} (native size)}
  5744. @item{@T{l}|a signed @id{long} (native size)}
  5745. @item{@T{L}|an unsigned @id{long} (native size)}
  5746. @item{@T{j}|a @id{lua_Integer}}
  5747. @item{@T{J}|a @id{lua_Unsigned}}
  5748. @item{@T{T}|a @id{size_t} (native size)}
  5749. @item{@T{i[@rep{n}]}|a signed @id{int} with @id{n} bytes
  5750. (default is native size)}
  5751. @item{@T{I[@rep{n}]}|an unsigned @id{int} with @id{n} bytes
  5752. (default is native size)}
  5753. @item{@T{f}|a @id{float} (native size)}
  5754. @item{@T{d}|a @id{double} (native size)}
  5755. @item{@T{n}|a @id{lua_Number}}
  5756. @item{@T{c@rep{n}}|a fixed-sized string with @id{n} bytes}
  5757. @item{@T{z}|a zero-terminated string}
  5758. @item{@T{s[@emph{n}]}|a string preceded by its length
  5759. coded as an unsigned integer with @id{n} bytes
  5760. (default is a @id{size_t})}
  5761. @item{@T{x}|one byte of padding}
  5762. @item{@T{X@rep{op}}|an empty item that aligns
  5763. according to option @id{op}
  5764. (which is otherwise ignored)}
  5765. @item{@Char{ }|(empty space) ignored}
  5766. }
  5767. (A @St{[@rep{n}]} means an optional integral numeral.)
  5768. Except for padding, spaces, and configurations
  5769. (options @St{xX <=>!}),
  5770. each option corresponds to an argument (in @Lid{string.pack})
  5771. or a result (in @Lid{string.unpack}).
  5772. For options @St{!@rep{n}}, @St{s@rep{n}}, @St{i@rep{n}}, and @St{I@rep{n}},
  5773. @id{n} can be any integer between 1 and 16.
  5774. All integral options check overflows;
  5775. @Lid{string.pack} checks whether the given value fits in the given size;
  5776. @Lid{string.unpack} checks whether the read value fits in a Lua integer.
  5777. Any format string starts as if prefixed by @St{!1=},
  5778. that is,
  5779. with maximum alignment of 1 (no alignment)
  5780. and native endianness.
  5781. Alignment works as follows:
  5782. For each option,
  5783. the format gets extra padding until the data starts
  5784. at an offset that is a multiple of the minimum between the
  5785. option size and the maximum alignment;
  5786. this minimum must be a power of 2.
  5787. Options @St{c} and @St{z} are not aligned;
  5788. option @St{s} follows the alignment of its starting integer.
  5789. All padding is filled with zeros by @Lid{string.pack}
  5790. (and ignored by @Lid{string.unpack}).
  5791. }
  5792. }
  5793. @sect2{utf8| @title{UTF-8 Support}
  5794. This library provides basic support for @x{UTF-8} encoding.
  5795. It provides all its functions inside the table @defid{utf8}.
  5796. This library does not provide any support for @x{Unicode} other
  5797. than the handling of the encoding.
  5798. Any operation that needs the meaning of a character,
  5799. such as character classification, is outside its scope.
  5800. Unless stated otherwise,
  5801. all functions that expect a byte position as a parameter
  5802. assume that the given position is either the start of a byte sequence
  5803. or one plus the length of the subject string.
  5804. As in the string library,
  5805. negative indices count from the end of the string.
  5806. @LibEntry{utf8.char (@Cdots)|
  5807. Receives zero or more integers,
  5808. converts each one to its corresponding UTF-8 byte sequence
  5809. and returns a string with the concatenation of all these sequences.
  5810. }
  5811. @LibEntry{utf8.charpattern|
  5812. The pattern (a string, not a function) @St{[\0-\x7F\xC2-\xF4][\x80-\xBF]*}
  5813. @see{pm},
  5814. which matches exactly one UTF-8 byte sequence,
  5815. assuming that the subject is a valid UTF-8 string.
  5816. }
  5817. @LibEntry{utf8.codes (s)|
  5818. Returns values so that the construction
  5819. @verbatim{
  5820. for p, c in utf8.codes(s) do @rep{body} end
  5821. }
  5822. will iterate over all characters in string @id{s},
  5823. with @id{p} being the position (in bytes) and @id{c} the code point
  5824. of each character.
  5825. It raises an error if it meets any invalid byte sequence.
  5826. }
  5827. @LibEntry{utf8.codepoint (s [, i [, j]])|
  5828. Returns the codepoints (as integers) from all characters in @id{s}
  5829. that start between byte position @id{i} and @id{j} (both included).
  5830. The default for @id{i} is 1 and for @id{j} is @id{i}.
  5831. It raises an error if it meets any invalid byte sequence.
  5832. }
  5833. @LibEntry{utf8.len (s [, i [, j]])|
  5834. Returns the number of UTF-8 characters in string @id{s}
  5835. that start between positions @id{i} and @id{j} (both inclusive).
  5836. The default for @id{i} is @num{1} and for @id{j} is @num{-1}.
  5837. If it finds any invalid byte sequence,
  5838. returns a false value plus the position of the first invalid byte.
  5839. }
  5840. @LibEntry{utf8.offset (s, n [, i])|
  5841. Returns the position (in bytes) where the encoding of the
  5842. @id{n}-th character of @id{s}
  5843. (counting from position @id{i}) starts.
  5844. A negative @id{n} gets characters before position @id{i}.
  5845. The default for @id{i} is 1 when @id{n} is non-negative
  5846. and @T{#s + 1} otherwise,
  5847. so that @T{utf8.offset(s, -n)} gets the offset of the
  5848. @id{n}-th character from the end of the string.
  5849. If the specified character is neither in the subject
  5850. nor right after its end,
  5851. the function returns @nil.
  5852. As a special case,
  5853. when @id{n} is 0 the function returns the start of the encoding
  5854. of the character that contains the @id{i}-th byte of @id{s}.
  5855. This function assumes that @id{s} is a valid UTF-8 string.
  5856. }
  5857. }
  5858. @sect2{tablib| @title{Table Manipulation}
  5859. This library provides generic functions for table manipulation.
  5860. It provides all its functions inside the table @defid{table}.
  5861. Remember that, whenever an operation needs the length of a table,
  5862. all caveats about the length operator apply @see{len-op}.
  5863. All functions ignore non-numeric keys
  5864. in the tables given as arguments.
  5865. @LibEntry{table.concat (list [, sep [, i [, j]]])|
  5866. Given a list where all elements are strings or numbers,
  5867. returns the string @T{list[i]..sep..list[i+1] @Cdots sep..list[j]}.
  5868. The default value for @id{sep} is the empty string,
  5869. the default for @id{i} is 1,
  5870. and the default for @id{j} is @T{#list}.
  5871. If @id{i} is greater than @id{j}, returns the empty string.
  5872. }
  5873. @LibEntry{table.insert (list, [pos,] value)|
  5874. Inserts element @id{value} at position @id{pos} in @id{list},
  5875. shifting up the elements
  5876. @T{list[pos], list[pos+1], @Cdots, list[#list]}.
  5877. The default value for @id{pos} is @T{#list+1},
  5878. so that a call @T{table.insert(t,x)} inserts @id{x} at the end
  5879. of list @id{t}.
  5880. }
  5881. @LibEntry{table.move (a1, f, e, t [,a2])|
  5882. Moves elements from table @id{a1} to table @id{a2},
  5883. performing the equivalent to the following
  5884. multiple assignment:
  5885. @T{a2[t],@Cdots = a1[f],@Cdots,a1[e]}.
  5886. The default for @id{a2} is @id{a1}.
  5887. The destination range can overlap with the source range.
  5888. The number of elements to be moved must fit in a Lua integer.
  5889. Returns the destination table @id{a2}.
  5890. }
  5891. @LibEntry{table.pack (@Cdots)|
  5892. Returns a new table with all arguments stored into keys 1, 2, etc.
  5893. and with a field @St{n} with the total number of arguments.
  5894. Note that the resulting table may not be a sequence,
  5895. if some arguments are @nil.
  5896. }
  5897. @LibEntry{table.remove (list [, pos])|
  5898. Removes from @id{list} the element at position @id{pos},
  5899. returning the value of the removed element.
  5900. When @id{pos} is an integer between 1 and @T{#list},
  5901. it shifts down the elements
  5902. @T{list[pos+1], list[pos+2], @Cdots, list[#list]}
  5903. and erases element @T{list[#list]};
  5904. The index @id{pos} can also be 0 when @T{#list} is 0,
  5905. or @T{#list + 1}.
  5906. The default value for @id{pos} is @T{#list},
  5907. so that a call @T{table.remove(l)} removes the last element
  5908. of list @id{l}.
  5909. }
  5910. @LibEntry{table.sort (list [, comp])|
  5911. Sorts list elements in a given order, @emph{in-place},
  5912. from @T{list[1]} to @T{list[#list]}.
  5913. If @id{comp} is given,
  5914. then it must be a function that receives two list elements
  5915. and returns true when the first element must come
  5916. before the second in the final order
  5917. (so that, after the sort,
  5918. @T{i < j} implies @T{not comp(list[j],list[i])}).
  5919. If @id{comp} is not given,
  5920. then the standard Lua operator @T{<} is used instead.
  5921. Note that the @id{comp} function must define
  5922. a strict partial order over the elements in the list;
  5923. that is, it must be asymmetric and transitive.
  5924. Otherwise, no valid sort may be possible.
  5925. The sort algorithm is not stable:
  5926. elements considered equal by the given order
  5927. may have their relative positions changed by the sort.
  5928. }
  5929. @LibEntry{table.unpack (list [, i [, j]])|
  5930. Returns the elements from the given list.
  5931. This function is equivalent to
  5932. @verbatim{
  5933. return list[i], list[i+1], @Cdots, list[j]
  5934. }
  5935. By default, @id{i} @N{is 1} and @id{j} is @T{#list}.
  5936. }
  5937. }
  5938. @sect2{mathlib| @title{Mathematical Functions}
  5939. This library provides basic mathematical functions.
  5940. It provides all its functions and constants inside the table @defid{math}.
  5941. Functions with the annotation @St{integer/float} give
  5942. integer results for integer arguments
  5943. and float results for float (or mixed) arguments.
  5944. Rounding functions
  5945. (@Lid{math.ceil}, @Lid{math.floor}, and @Lid{math.modf})
  5946. return an integer when the result fits in the range of an integer,
  5947. or a float otherwise.
  5948. @LibEntry{math.abs (x)|
  5949. Returns the absolute value of @id{x}. (integer/float)
  5950. }
  5951. @LibEntry{math.acos (x)|
  5952. Returns the arc cosine of @id{x} (in radians).
  5953. }
  5954. @LibEntry{math.asin (x)|
  5955. Returns the arc sine of @id{x} (in radians).
  5956. }
  5957. @LibEntry{math.atan (y [, x])|
  5958. @index{atan2}
  5959. Returns the arc tangent of @T{y/x} (in radians),
  5960. but uses the signs of both arguments to find the
  5961. quadrant of the result.
  5962. (It also handles correctly the case of @id{x} being zero.)
  5963. The default value for @id{x} is 1,
  5964. so that the call @T{math.atan(y)}
  5965. returns the arc tangent of @id{y}.
  5966. }
  5967. @LibEntry{math.ceil (x)|
  5968. Returns the smallest integral value larger than or equal to @id{x}.
  5969. }
  5970. @LibEntry{math.cos (x)|
  5971. Returns the cosine of @id{x} (assumed to be in radians).
  5972. }
  5973. @LibEntry{math.deg (x)|
  5974. Converts the angle @id{x} from radians to degrees.
  5975. }
  5976. @LibEntry{math.exp (x)|
  5977. Returns the value @M{e@sp{x}}
  5978. (where @id{e} is the base of natural logarithms).
  5979. }
  5980. @LibEntry{math.floor (x)|
  5981. Returns the largest integral value smaller than or equal to @id{x}.
  5982. }
  5983. @LibEntry{math.fmod (x, y)|
  5984. Returns the remainder of the division of @id{x} by @id{y}
  5985. that rounds the quotient towards zero. (integer/float)
  5986. }
  5987. @LibEntry{math.huge|
  5988. The float value @idx{HUGE_VAL},
  5989. a value larger than any other numeric value.
  5990. }
  5991. @LibEntry{math.log (x [, base])|
  5992. Returns the logarithm of @id{x} in the given base.
  5993. The default for @id{base} is @M{e}
  5994. (so that the function returns the natural logarithm of @id{x}).
  5995. }
  5996. @LibEntry{math.max (x, @Cdots)|
  5997. Returns the argument with the maximum value,
  5998. according to the Lua operator @T{<}. (integer/float)
  5999. }
  6000. @LibEntry{math.maxinteger|
  6001. An integer with the maximum value for an integer.
  6002. }
  6003. @LibEntry{math.min (x, @Cdots)|
  6004. Returns the argument with the minimum value,
  6005. according to the Lua operator @T{<}. (integer/float)
  6006. }
  6007. @LibEntry{math.mininteger|
  6008. An integer with the minimum value for an integer.
  6009. }
  6010. @LibEntry{math.modf (x)|
  6011. Returns the integral part of @id{x} and the fractional part of @id{x}.
  6012. Its second result is always a float.
  6013. }
  6014. @LibEntry{math.pi|
  6015. The value of @M{@pi}.
  6016. }
  6017. @LibEntry{math.rad (x)|
  6018. Converts the angle @id{x} from degrees to radians.
  6019. }
  6020. @LibEntry{math.random ([m [, n]])|
  6021. When called without arguments,
  6022. returns a pseudo-random float with uniform distribution
  6023. in the range @C{(} @M{[0,1)}. @C{]}
  6024. When called with two integers @id{m} and @id{n},
  6025. @id{math.random} returns a pseudo-random integer
  6026. with uniform distribution in the range @M{[m, n]}.
  6027. The call @T{math.random(n)}, for a positive @id{n},
  6028. is equivalent to @T{math.random(1,n)}.
  6029. The call @T{math.random(0)} produces an integer with
  6030. all bits (pseudo)random.
  6031. Lua initializes its pseudo-random generator with the equivalent of
  6032. a call to @Lid{math.randomseed} with no arguments,
  6033. so that @id{math.random} should generate
  6034. different sequences of results each time the program runs.
  6035. The results from this function have good statistical qualities,
  6036. but they are not cryptographically secure.
  6037. (For instance, there are no guarantees that it is hard
  6038. to predict future results based on the observation of
  6039. some number of previous results.)
  6040. }
  6041. @LibEntry{math.randomseed ([x [, y]])|
  6042. When called with at least one argument,
  6043. the integer parameters @id{x} and @id{y} are
  6044. concatenated into a 128-bit @emphx{seed} that
  6045. is used to reinitialize the pseudo-random generator;
  6046. equal seeds produce equal sequences of numbers.
  6047. The default for @id{y} is zero.
  6048. When called with no arguments,
  6049. Lua generates a seed with
  6050. a weak attempt for randomness.
  6051. To ensure a required level of randomness to the initial state
  6052. (or contrarily, to have a deterministic sequence,
  6053. for instance when debugging a program),
  6054. you should call @Lid{math.randomseed} with explicit arguments.
  6055. }
  6056. @LibEntry{math.sin (x)|
  6057. Returns the sine of @id{x} (assumed to be in radians).
  6058. }
  6059. @LibEntry{math.sqrt (x)|
  6060. Returns the square root of @id{x}.
  6061. (You can also use the expression @T{x^0.5} to compute this value.)
  6062. }
  6063. @LibEntry{math.tan (x)|
  6064. Returns the tangent of @id{x} (assumed to be in radians).
  6065. }
  6066. @LibEntry{math.tointeger (x)|
  6067. If the value @id{x} is convertible to an integer,
  6068. returns that integer.
  6069. Otherwise, returns @nil.
  6070. }
  6071. @LibEntry{math.type (x)|
  6072. Returns @St{integer} if @id{x} is an integer,
  6073. @St{float} if it is a float,
  6074. or @nil if @id{x} is not a number.
  6075. }
  6076. @LibEntry{math.ult (m, n)|
  6077. Returns a boolean,
  6078. true if and only if integer @id{m} is below integer @id{n} when
  6079. they are compared as @x{unsigned integers}.
  6080. }
  6081. }
  6082. @sect2{iolib| @title{Input and Output Facilities}
  6083. The I/O library provides two different styles for file manipulation.
  6084. The first one uses implicit file handles;
  6085. that is, there are operations to set a default input file and a
  6086. default output file,
  6087. and all input/output operations are over these default files.
  6088. The second style uses explicit file handles.
  6089. When using implicit file handles,
  6090. all operations are supplied by table @defid{io}.
  6091. When using explicit file handles,
  6092. the operation @Lid{io.open} returns a file handle
  6093. and then all operations are supplied as methods of the file handle.
  6094. The table @id{io} also provides
  6095. three predefined file handles with their usual meanings from C:
  6096. @defid{io.stdin}, @defid{io.stdout}, and @defid{io.stderr}.
  6097. The I/O library never closes these files.
  6098. The metatable for file handles provides metamethods
  6099. for @idx{__gc} and @idx{__close} that try
  6100. to close the file when called.
  6101. Unless otherwise stated,
  6102. all I/O functions return @nil on failure
  6103. (plus an error message as a second result and
  6104. a system-dependent error code as a third result)
  6105. and some value different from @nil on success.
  6106. On non-POSIX systems,
  6107. the computation of the error message and error code
  6108. in case of errors
  6109. may be not @x{thread safe},
  6110. because they rely on the global C variable @id{errno}.
  6111. @LibEntry{io.close ([file])|
  6112. Equivalent to @T{file:close()}.
  6113. Without a @id{file}, closes the default output file.
  6114. }
  6115. @LibEntry{io.flush ()|
  6116. Equivalent to @T{io.output():flush()}.
  6117. }
  6118. @LibEntry{io.input ([file])|
  6119. When called with a file name, it opens the named file (in text mode),
  6120. and sets its handle as the default input file.
  6121. When called with a file handle,
  6122. it simply sets this file handle as the default input file.
  6123. When called without arguments,
  6124. it returns the current default input file.
  6125. In case of errors this function raises the error,
  6126. instead of returning an error code.
  6127. }
  6128. @LibEntry{io.lines ([filename, @Cdots])|
  6129. Opens the given file name in read mode
  6130. and returns an iterator function that
  6131. works like @T{file:lines(@Cdots)} over the opened file.
  6132. When the iterator function detects the end of file,
  6133. it returns no values (to finish the loop) and automatically closes the file.
  6134. Besides the iterator function,
  6135. @id{io.lines} returns three other values:
  6136. two @nil values as placeholders,
  6137. plus the created file handle.
  6138. Therefore, when used in a generic @Rw{for} loop,
  6139. the file is closed also if the loop is interrupted by an
  6140. error or a @Rw{break}.
  6141. The call @T{io.lines()} (with no file name) is equivalent
  6142. to @T{io.input():lines("l")};
  6143. that is, it iterates over the lines of the default input file.
  6144. In this case, the iterator does not close the file when the loop ends.
  6145. In case of errors this function raises the error,
  6146. instead of returning an error code.
  6147. }
  6148. @LibEntry{io.open (filename [, mode])|
  6149. This function opens a file,
  6150. in the mode specified in the string @id{mode}.
  6151. In case of success,
  6152. it returns a new file handle.
  6153. The @id{mode} string can be any of the following:
  6154. @description{
  6155. @item{@St{r}| read mode (the default);}
  6156. @item{@St{w}| write mode;}
  6157. @item{@St{a}| append mode;}
  6158. @item{@St{r+}| update mode, all previous data is preserved;}
  6159. @item{@St{w+}| update mode, all previous data is erased;}
  6160. @item{@St{a+}| append update mode, previous data is preserved,
  6161. writing is only allowed at the end of file.}
  6162. }
  6163. The @id{mode} string can also have a @Char{b} at the end,
  6164. which is needed in some systems to open the file in binary mode.
  6165. }
  6166. @LibEntry{io.output ([file])|
  6167. Similar to @Lid{io.input}, but operates over the default output file.
  6168. }
  6169. @LibEntry{io.popen (prog [, mode])|
  6170. This function is system dependent and is not available
  6171. on all platforms.
  6172. Starts program @id{prog} in a separated process and returns
  6173. a file handle that you can use to read data from this program
  6174. (if @id{mode} is @T{"r"}, the default)
  6175. or to write data to this program
  6176. (if @id{mode} is @T{"w"}).
  6177. }
  6178. @LibEntry{io.read (@Cdots)|
  6179. Equivalent to @T{io.input():read(@Cdots)}.
  6180. }
  6181. @LibEntry{io.tmpfile ()|
  6182. In case of success,
  6183. returns a handle for a temporary file.
  6184. This file is opened in update mode
  6185. and it is automatically removed when the program ends.
  6186. }
  6187. @LibEntry{io.type (obj)|
  6188. Checks whether @id{obj} is a valid file handle.
  6189. Returns the string @T{"file"} if @id{obj} is an open file handle,
  6190. @T{"closed file"} if @id{obj} is a closed file handle,
  6191. or @nil if @id{obj} is not a file handle.
  6192. }
  6193. @LibEntry{io.write (@Cdots)|
  6194. Equivalent to @T{io.output():write(@Cdots)}.
  6195. }
  6196. @LibEntry{file:close ()|
  6197. Closes @id{file}.
  6198. Note that files are automatically closed when
  6199. their handles are garbage collected,
  6200. but that takes an unpredictable amount of time to happen.
  6201. When closing a file handle created with @Lid{io.popen},
  6202. @Lid{file:close} returns the same values
  6203. returned by @Lid{os.execute}.
  6204. }
  6205. @LibEntry{file:flush ()|
  6206. Saves any written data to @id{file}.
  6207. }
  6208. @LibEntry{file:lines (@Cdots)|
  6209. Returns an iterator function that,
  6210. each time it is called,
  6211. reads the file according to the given formats.
  6212. When no format is given,
  6213. uses @St{l} as a default.
  6214. As an example, the construction
  6215. @verbatim{
  6216. for c in file:lines(1) do @rep{body} end
  6217. }
  6218. will iterate over all characters of the file,
  6219. starting at the current position.
  6220. Unlike @Lid{io.lines}, this function does not close the file
  6221. when the loop ends.
  6222. In case of errors this function raises the error,
  6223. instead of returning an error code.
  6224. }
  6225. @LibEntry{file:read (@Cdots)|
  6226. Reads the file @id{file},
  6227. according to the given formats, which specify what to read.
  6228. For each format,
  6229. the function returns a string or a number with the characters read,
  6230. or @nil if it cannot read data with the specified format.
  6231. (In this latter case,
  6232. the function does not read subsequent formats.)
  6233. When called without arguments,
  6234. it uses a default format that reads the next line
  6235. (see below).
  6236. The available formats are
  6237. @description{
  6238. @item{@St{n}|
  6239. reads a numeral and returns it as a float or an integer,
  6240. following the lexical conventions of Lua.
  6241. (The numeral may have leading spaces and a sign.)
  6242. This format always reads the longest input sequence that
  6243. is a valid prefix for a numeral;
  6244. if that prefix does not form a valid numeral
  6245. (e.g., an empty string, @St{0x}, or @St{3.4e-}),
  6246. it is discarded and the format returns @nil.
  6247. }
  6248. @item{@St{a}|
  6249. reads the whole file, starting at the current position.
  6250. On end of file, it returns the empty string.
  6251. }
  6252. @item{@St{l}|
  6253. reads the next line skipping the end of line,
  6254. returning @nil on end of file.
  6255. This is the default format.
  6256. }
  6257. @item{@St{L}|
  6258. reads the next line keeping the end-of-line character (if present),
  6259. returning @nil on end of file.
  6260. }
  6261. @item{@emph{number}|
  6262. reads a string with up to this number of bytes,
  6263. returning @nil on end of file.
  6264. If @id{number} is zero,
  6265. it reads nothing and returns an empty string,
  6266. or @nil on end of file.
  6267. }
  6268. }
  6269. The formats @St{l} and @St{L} should be used only for text files.
  6270. }
  6271. @LibEntry{file:seek ([whence [, offset]])|
  6272. Sets and gets the file position,
  6273. measured from the beginning of the file,
  6274. to the position given by @id{offset} plus a base
  6275. specified by the string @id{whence}, as follows:
  6276. @description{
  6277. @item{@St{set}| base is position 0 (beginning of the file);}
  6278. @item{@St{cur}| base is current position;}
  6279. @item{@St{end}| base is end of file;}
  6280. }
  6281. In case of success, @id{seek} returns the final file position,
  6282. measured in bytes from the beginning of the file.
  6283. If @id{seek} fails, it returns @nil,
  6284. plus a string describing the error.
  6285. The default value for @id{whence} is @T{"cur"},
  6286. and for @id{offset} is 0.
  6287. Therefore, the call @T{file:seek()} returns the current
  6288. file position, without changing it;
  6289. the call @T{file:seek("set")} sets the position to the
  6290. beginning of the file (and returns 0);
  6291. and the call @T{file:seek("end")} sets the position to the
  6292. end of the file, and returns its size.
  6293. }
  6294. @LibEntry{file:setvbuf (mode [, size])|
  6295. Sets the buffering mode for an output file.
  6296. There are three available modes:
  6297. @description{
  6298. @item{@St{no}|
  6299. no buffering; the result of any output operation appears immediately.
  6300. }
  6301. @item{@St{full}|
  6302. full buffering; output operation is performed only
  6303. when the buffer is full or when
  6304. you explicitly @T{flush} the file @seeF{io.flush}.
  6305. }
  6306. @item{@St{line}|
  6307. line buffering; output is buffered until a newline is output
  6308. or there is any input from some special files
  6309. (such as a terminal device).
  6310. }
  6311. }
  6312. For the last two cases,
  6313. @id{size} is a hint for the size of the buffer, in bytes.
  6314. The default is an appropriate size.
  6315. }
  6316. @LibEntry{file:write (@Cdots)|
  6317. Writes the value of each of its arguments to @id{file}.
  6318. The arguments must be strings or numbers.
  6319. In case of success, this function returns @id{file}.
  6320. Otherwise it returns @nil plus a string describing the error.
  6321. }
  6322. }
  6323. @sect2{oslib| @title{Operating System Facilities}
  6324. This library is implemented through table @defid{os}.
  6325. @LibEntry{os.clock ()|
  6326. Returns an approximation of the amount in seconds of CPU time
  6327. used by the program.
  6328. }
  6329. @LibEntry{os.date ([format [, time]])|
  6330. Returns a string or a table containing date and time,
  6331. formatted according to the given string @id{format}.
  6332. If the @id{time} argument is present,
  6333. this is the time to be formatted
  6334. (see the @Lid{os.time} function for a description of this value).
  6335. Otherwise, @id{date} formats the current time.
  6336. If @id{format} starts with @Char{!},
  6337. then the date is formatted in Coordinated Universal Time.
  6338. After this optional character,
  6339. if @id{format} is the string @St{*t},
  6340. then @id{date} returns a table with the following fields:
  6341. @id{year}, @id{month} (1@En{}12), @id{day} (1@En{}31),
  6342. @id{hour} (0@En{}23), @id{min} (0@En{}59),
  6343. @id{sec} (0@En{}61, due to leap seconds),
  6344. @id{wday} (weekday, 1@En{}7, Sunday @N{is 1}),
  6345. @id{yday} (day of the year, 1@En{}366),
  6346. and @id{isdst} (daylight saving flag, a boolean).
  6347. This last field may be absent
  6348. if the information is not available.
  6349. If @id{format} is not @St{*t},
  6350. then @id{date} returns the date as a string,
  6351. formatted according to the same rules as the @ANSI{strftime}.
  6352. When called without arguments,
  6353. @id{date} returns a reasonable date and time representation that depends on
  6354. the host system and on the current locale.
  6355. (More specifically, @T{os.date()} is equivalent to @T{os.date("%c")}.)
  6356. On non-POSIX systems,
  6357. this function may be not @x{thread safe}
  6358. because of its reliance on @CId{gmtime} and @CId{localtime}.
  6359. }
  6360. @LibEntry{os.difftime (t2, t1)|
  6361. Returns the difference, in seconds,
  6362. from time @id{t1} to time @id{t2}
  6363. (where the times are values returned by @Lid{os.time}).
  6364. In @x{POSIX}, @x{Windows}, and some other systems,
  6365. this value is exactly @id{t2}@M{-}@id{t1}.
  6366. }
  6367. @LibEntry{os.execute ([command])|
  6368. This function is equivalent to the @ANSI{system}.
  6369. It passes @id{command} to be executed by an operating system shell.
  6370. Its first result is @true
  6371. if the command terminated successfully,
  6372. or @nil otherwise.
  6373. After this first result
  6374. the function returns a string plus a number,
  6375. as follows:
  6376. @description{
  6377. @item{@St{exit}|
  6378. the command terminated normally;
  6379. the following number is the exit status of the command.
  6380. }
  6381. @item{@St{signal}|
  6382. the command was terminated by a signal;
  6383. the following number is the signal that terminated the command.
  6384. }
  6385. }
  6386. When called without a @id{command},
  6387. @id{os.execute} returns a boolean that is true if a shell is available.
  6388. }
  6389. @LibEntry{os.exit ([code [, close]])|
  6390. Calls the @ANSI{exit} to terminate the host program.
  6391. If @id{code} is @Rw{true},
  6392. the returned status is @idx{EXIT_SUCCESS};
  6393. if @id{code} is @Rw{false},
  6394. the returned status is @idx{EXIT_FAILURE};
  6395. if @id{code} is a number,
  6396. the returned status is this number.
  6397. The default value for @id{code} is @Rw{true}.
  6398. If the optional second argument @id{close} is true,
  6399. closes the Lua state before exiting.
  6400. }
  6401. @LibEntry{os.getenv (varname)|
  6402. Returns the value of the process environment variable @id{varname},
  6403. or @nil if the variable is not defined.
  6404. }
  6405. @LibEntry{os.remove (filename)|
  6406. Deletes the file (or empty directory, on @x{POSIX} systems)
  6407. with the given name.
  6408. If this function fails, it returns @nil,
  6409. plus a string describing the error and the error code.
  6410. Otherwise, it returns true.
  6411. }
  6412. @LibEntry{os.rename (oldname, newname)|
  6413. Renames the file or directory named @id{oldname} to @id{newname}.
  6414. If this function fails, it returns @nil,
  6415. plus a string describing the error and the error code.
  6416. Otherwise, it returns true.
  6417. }
  6418. @LibEntry{os.setlocale (locale [, category])|
  6419. Sets the current locale of the program.
  6420. @id{locale} is a system-dependent string specifying a locale;
  6421. @id{category} is an optional string describing which category to change:
  6422. @T{"all"}, @T{"collate"}, @T{"ctype"},
  6423. @T{"monetary"}, @T{"numeric"}, or @T{"time"};
  6424. the default category is @T{"all"}.
  6425. The function returns the name of the new locale,
  6426. or @nil if the request cannot be honored.
  6427. If @id{locale} is the empty string,
  6428. the current locale is set to an implementation-defined native locale.
  6429. If @id{locale} is the string @St{C},
  6430. the current locale is set to the standard C locale.
  6431. When called with @nil as the first argument,
  6432. this function only returns the name of the current locale
  6433. for the given category.
  6434. This function may be not @x{thread safe}
  6435. because of its reliance on @CId{setlocale}.
  6436. }
  6437. @LibEntry{os.time ([table])|
  6438. Returns the current time when called without arguments,
  6439. or a time representing the local date and time specified by the given table.
  6440. This table must have fields @id{year}, @id{month}, and @id{day},
  6441. and may have fields
  6442. @id{hour} (default is 12),
  6443. @id{min} (default is 0),
  6444. @id{sec} (default is 0),
  6445. and @id{isdst} (default is @nil).
  6446. Other fields are ignored.
  6447. For a description of these fields, see the @Lid{os.date} function.
  6448. When the function is called,
  6449. the values in these fields do not need to be inside their valid ranges.
  6450. For instance, if @id{sec} is -10,
  6451. it means 10 seconds before the time specified by the other fields;
  6452. if @id{hour} is 1000,
  6453. it means 1000 hours after the time specified by the other fields.
  6454. The returned value is a number, whose meaning depends on your system.
  6455. In @x{POSIX}, @x{Windows}, and some other systems,
  6456. this number counts the number
  6457. of seconds since some given start time (the @Q{epoch}).
  6458. In other systems, the meaning is not specified,
  6459. and the number returned by @id{time} can be used only as an argument to
  6460. @Lid{os.date} and @Lid{os.difftime}.
  6461. When called with a table,
  6462. @id{os.time} also normalizes all the fields
  6463. documented in the @Lid{os.date} function,
  6464. so that they represent the same time as before the call
  6465. but with values inside their valid ranges.
  6466. }
  6467. @LibEntry{os.tmpname ()|
  6468. Returns a string with a file name that can
  6469. be used for a temporary file.
  6470. The file must be explicitly opened before its use
  6471. and explicitly removed when no longer needed.
  6472. In @x{POSIX} systems,
  6473. this function also creates a file with that name,
  6474. to avoid security risks.
  6475. (Someone else might create the file with wrong permissions
  6476. in the time between getting the name and creating the file.)
  6477. You still have to open the file to use it
  6478. and to remove it (even if you do not use it).
  6479. When possible,
  6480. you may prefer to use @Lid{io.tmpfile},
  6481. which automatically removes the file when the program ends.
  6482. }
  6483. }
  6484. @sect2{debuglib| @title{The Debug Library}
  6485. This library provides
  6486. the functionality of the @link{debugI|debug interface} to Lua programs.
  6487. You should exert care when using this library.
  6488. Several of its functions
  6489. violate basic assumptions about Lua code
  6490. (e.g., that variables local to a function
  6491. cannot be accessed from outside;
  6492. that userdata metatables cannot be changed by Lua code;
  6493. that Lua programs do not crash)
  6494. and therefore can compromise otherwise secure code.
  6495. Moreover, some functions in this library may be slow.
  6496. All functions in this library are provided
  6497. inside the @defid{debug} table.
  6498. All functions that operate over a thread
  6499. have an optional first argument which is the
  6500. thread to operate over.
  6501. The default is always the current thread.
  6502. @LibEntry{debug.debug ()|
  6503. Enters an interactive mode with the user,
  6504. running each string that the user enters.
  6505. Using simple commands and other debug facilities,
  6506. the user can inspect global and local variables,
  6507. change their values, evaluate expressions, and so on.
  6508. A line containing only the word @id{cont} finishes this function,
  6509. so that the caller continues its execution.
  6510. Note that commands for @id{debug.debug} are not lexically nested
  6511. within any function and so have no direct access to local variables.
  6512. }
  6513. @LibEntry{debug.gethook ([thread])|
  6514. Returns the current hook settings of the thread, as three values:
  6515. the current hook function, the current hook mask,
  6516. and the current hook count
  6517. (as set by the @Lid{debug.sethook} function).
  6518. }
  6519. @LibEntry{debug.getinfo ([thread,] f [, what])|
  6520. Returns a table with information about a function.
  6521. You can give the function directly
  6522. or you can give a number as the value of @id{f},
  6523. which means the function running at level @id{f} of the call stack
  6524. of the given thread:
  6525. @N{level 0} is the current function (@id{getinfo} itself);
  6526. @N{level 1} is the function that called @id{getinfo}
  6527. (except for tail calls, which do not count on the stack);
  6528. and so on.
  6529. If @id{f} is a number larger than the number of active functions,
  6530. then @id{getinfo} returns @nil.
  6531. The returned table can contain all the fields returned by @Lid{lua_getinfo},
  6532. with the string @id{what} describing which fields to fill in.
  6533. The default for @id{what} is to get all information available,
  6534. except the table of valid lines.
  6535. If present,
  6536. the option @Char{f}
  6537. adds a field named @id{func} with the function itself.
  6538. If present,
  6539. the option @Char{L}
  6540. adds a field named @id{activelines} with the table of
  6541. valid lines.
  6542. For instance, the expression @T{debug.getinfo(1,"n").name} returns
  6543. a name for the current function,
  6544. if a reasonable name can be found,
  6545. and the expression @T{debug.getinfo(print)}
  6546. returns a table with all available information
  6547. about the @Lid{print} function.
  6548. }
  6549. @LibEntry{debug.getlocal ([thread,] f, local)|
  6550. This function returns the name and the value of the local variable
  6551. with index @id{local} of the function at level @id{f} of the stack.
  6552. This function accesses not only explicit local variables,
  6553. but also parameters, temporaries, etc.
  6554. The first parameter or local variable has @N{index 1}, and so on,
  6555. following the order that they are declared in the code,
  6556. counting only the variables that are active
  6557. in the current scope of the function.
  6558. Negative indices refer to vararg arguments;
  6559. @num{-1} is the first vararg argument.
  6560. The function returns @nil if there is no variable with the given index,
  6561. and raises an error when called with a level out of range.
  6562. (You can call @Lid{debug.getinfo} to check whether the level is valid.)
  6563. Variable names starting with @Char{(} (open parenthesis) @C{)}
  6564. represent variables with no known names
  6565. (internal variables such as loop control variables,
  6566. and variables from chunks saved without debug information).
  6567. The parameter @id{f} may also be a function.
  6568. In that case, @id{getlocal} returns only the name of function parameters.
  6569. }
  6570. @LibEntry{debug.getmetatable (value)|
  6571. Returns the metatable of the given @id{value}
  6572. or @nil if it does not have a metatable.
  6573. }
  6574. @LibEntry{debug.getregistry ()|
  6575. Returns the registry table @see{registry}.
  6576. }
  6577. @LibEntry{debug.getupvalue (f, up)|
  6578. This function returns the name and the value of the upvalue
  6579. with index @id{up} of the function @id{f}.
  6580. The function returns @nil if there is no upvalue with the given index.
  6581. Variable names starting with @Char{(} (open parenthesis) @C{)}
  6582. represent variables with no known names
  6583. (variables from chunks saved without debug information).
  6584. }
  6585. @LibEntry{debug.getuservalue (u, n)|
  6586. Returns the @id{n}-th user value associated
  6587. to the userdata @id{u} plus a boolean,
  6588. @false if the userdata does not have that value.
  6589. }
  6590. @LibEntry{debug.sethook ([thread,] hook, mask [, count])|
  6591. Sets the given function as a hook.
  6592. The string @id{mask} and the number @id{count} describe
  6593. when the hook will be called.
  6594. The string mask may have any combination of the following characters,
  6595. with the given meaning:
  6596. @description{
  6597. @item{@Char{c}| the hook is called every time Lua calls a function;}
  6598. @item{@Char{r}| the hook is called every time Lua returns from a function;}
  6599. @item{@Char{l}| the hook is called every time Lua enters a new line of code.}
  6600. }
  6601. Moreover,
  6602. with a @id{count} different from zero,
  6603. the hook is called also after every @id{count} instructions.
  6604. When called without arguments,
  6605. @Lid{debug.sethook} turns off the hook.
  6606. When the hook is called, its first parameter is a string
  6607. describing the event that has triggered its call:
  6608. @T{"call"} (or @T{"tail call"}),
  6609. @T{"return"},
  6610. @T{"line"}, and @T{"count"}.
  6611. For line events,
  6612. the hook also gets the new line number as its second parameter.
  6613. Inside a hook,
  6614. you can call @id{getinfo} with @N{level 2} to get more information about
  6615. the running function
  6616. (@N{level 0} is the @id{getinfo} function,
  6617. and @N{level 1} is the hook function).
  6618. }
  6619. @LibEntry{debug.setlocal ([thread,] level, local, value)|
  6620. This function assigns the value @id{value} to the local variable
  6621. with index @id{local} of the function at level @id{level} of the stack.
  6622. The function returns @nil if there is no local
  6623. variable with the given index,
  6624. and raises an error when called with a @id{level} out of range.
  6625. (You can call @id{getinfo} to check whether the level is valid.)
  6626. Otherwise, it returns the name of the local variable.
  6627. See @Lid{debug.getlocal} for more information about
  6628. variable indices and names.
  6629. }
  6630. @LibEntry{debug.setmetatable (value, table)|
  6631. Sets the metatable for the given @id{value} to the given @id{table}
  6632. (which can be @nil).
  6633. Returns @id{value}.
  6634. }
  6635. @LibEntry{debug.setupvalue (f, up, value)|
  6636. This function assigns the value @id{value} to the upvalue
  6637. with index @id{up} of the function @id{f}.
  6638. The function returns @nil if there is no upvalue
  6639. with the given index.
  6640. Otherwise, it returns the name of the upvalue.
  6641. }
  6642. @LibEntry{debug.setuservalue (udata, value, n)|
  6643. Sets the given @id{value} as
  6644. the @id{n}-th user value associated to the given @id{udata}.
  6645. @id{udata} must be a full userdata.
  6646. Returns @id{udata},
  6647. or @nil if the userdata does not have that value.
  6648. }
  6649. @LibEntry{debug.traceback ([thread,] [message [, level]])|
  6650. If @id{message} is present but is neither a string nor @nil,
  6651. this function returns @id{message} without further processing.
  6652. Otherwise,
  6653. it returns a string with a traceback of the call stack.
  6654. The optional @id{message} string is appended
  6655. at the beginning of the traceback.
  6656. An optional @id{level} number tells at which level
  6657. to start the traceback
  6658. (default is 1, the function calling @id{traceback}).
  6659. }
  6660. @LibEntry{debug.upvalueid (f, n)|
  6661. Returns a unique identifier (as a light userdata)
  6662. for the upvalue numbered @id{n}
  6663. from the given function.
  6664. These unique identifiers allow a program to check whether different
  6665. closures share upvalues.
  6666. Lua closures that share an upvalue
  6667. (that is, that access a same external local variable)
  6668. will return identical ids for those upvalue indices.
  6669. }
  6670. @LibEntry{debug.upvaluejoin (f1, n1, f2, n2)|
  6671. Make the @id{n1}-th upvalue of the Lua closure @id{f1}
  6672. refer to the @id{n2}-th upvalue of the Lua closure @id{f2}.
  6673. }
  6674. }
  6675. }
  6676. @C{-------------------------------------------------------------------------}
  6677. @sect1{lua-sa| @title{Lua Standalone}
  6678. Although Lua has been designed as an extension language,
  6679. to be embedded in a host @N{C program},
  6680. it is also frequently used as a standalone language.
  6681. An interpreter for Lua as a standalone language,
  6682. called simply @id{lua},
  6683. is provided with the standard distribution.
  6684. The @x{standalone interpreter} includes
  6685. all standard libraries, including the debug library.
  6686. Its usage is:
  6687. @verbatim{
  6688. lua [options] [script [args]]
  6689. }
  6690. The options are:
  6691. @description{
  6692. @item{@T{-e @rep{stat}}| executes string @rep{stat};}
  6693. @item{@T{-l @rep{mod}}| @Q{requires} @rep{mod} and assigns the
  6694. result to global @rep{mod};}
  6695. @item{@T{-i}| enters interactive mode after running @rep{script};}
  6696. @item{@T{-v}| prints version information;}
  6697. @item{@T{-E}| ignores environment variables;}
  6698. @item{@T{--}| stops handling options;}
  6699. @item{@T{-}| executes @id{stdin} as a file and stops handling options.}
  6700. }
  6701. After handling its options, @id{lua} runs the given @emph{script}.
  6702. When called without arguments,
  6703. @id{lua} behaves as @T{lua -v -i}
  6704. when the standard input (@id{stdin}) is a terminal,
  6705. and as @T{lua -} otherwise.
  6706. When called without option @T{-E},
  6707. the interpreter checks for an environment variable @defid{LUA_INIT_5_4}
  6708. (or @defid{LUA_INIT} if the versioned name is not defined)
  6709. before running any argument.
  6710. If the variable content has the format @T{@At@rep{filename}},
  6711. then @id{lua} executes the file.
  6712. Otherwise, @id{lua} executes the string itself.
  6713. When called with option @T{-E},
  6714. besides ignoring @id{LUA_INIT},
  6715. Lua also ignores
  6716. the values of @id{LUA_PATH} and @id{LUA_CPATH},
  6717. setting the values of
  6718. @Lid{package.path} and @Lid{package.cpath}
  6719. with the default paths defined in @id{luaconf.h}.
  6720. All options are handled in order, except @T{-i} and @T{-E}.
  6721. For instance, an invocation like
  6722. @verbatim{
  6723. $ lua -e'a=1' -e 'print(a)' script.lua
  6724. }
  6725. will first set @id{a} to 1, then print the value of @id{a},
  6726. and finally run the file @id{script.lua} with no arguments.
  6727. (Here @T{$} is the shell prompt. Your prompt may be different.)
  6728. Before running any code,
  6729. @id{lua} collects all command-line arguments
  6730. in a global table called @id{arg}.
  6731. The script name goes to index 0,
  6732. the first argument after the script name goes to index 1,
  6733. and so on.
  6734. Any arguments before the script name
  6735. (that is, the interpreter name plus its options)
  6736. go to negative indices.
  6737. For instance, in the call
  6738. @verbatim{
  6739. $ lua -la b.lua t1 t2
  6740. }
  6741. the table is like this:
  6742. @verbatim{
  6743. arg = { [-2] = "lua", [-1] = "-la",
  6744. [0] = "b.lua",
  6745. [1] = "t1", [2] = "t2" }
  6746. }
  6747. If there is no script in the call,
  6748. the interpreter name goes to index 0,
  6749. followed by the other arguments.
  6750. For instance, the call
  6751. @verbatim{
  6752. $ lua -e "print(arg[1])"
  6753. }
  6754. will print @St{-e}.
  6755. If there is a script,
  6756. the script is called with arguments
  6757. @T{arg[1]}, @Cdots, @T{arg[#arg]}.
  6758. (Like all chunks in Lua,
  6759. the script is compiled as a vararg function.)
  6760. In interactive mode,
  6761. Lua repeatedly prompts and waits for a line.
  6762. After reading a line,
  6763. Lua first try to interpret the line as an expression.
  6764. If it succeeds, it prints its value.
  6765. Otherwise, it interprets the line as a statement.
  6766. If you write an incomplete statement,
  6767. the interpreter waits for its completion
  6768. by issuing a different prompt.
  6769. If the global variable @defid{_PROMPT} contains a string,
  6770. then its value is used as the prompt.
  6771. Similarly, if the global variable @defid{_PROMPT2} contains a string,
  6772. its value is used as the secondary prompt
  6773. (issued during incomplete statements).
  6774. In case of unprotected errors in the script,
  6775. the interpreter reports the error to the standard error stream.
  6776. If the error object is not a string but
  6777. has a metamethod @idx{__tostring},
  6778. the interpreter calls this metamethod to produce the final message.
  6779. Otherwise, the interpreter converts the error object to a string
  6780. and adds a stack traceback to it.
  6781. When finishing normally,
  6782. the interpreter closes its main Lua state
  6783. @seeF{lua_close}.
  6784. The script can avoid this step by
  6785. calling @Lid{os.exit} to terminate.
  6786. To allow the use of Lua as a
  6787. script interpreter in Unix systems,
  6788. the standalone interpreter skips
  6789. the first line of a chunk if it starts with @T{#}.
  6790. Therefore, Lua scripts can be made into executable programs
  6791. by using @T{chmod +x} and @N{the @T{#!}} form,
  6792. as in
  6793. @verbatim{
  6794. #!/usr/local/bin/lua
  6795. }
  6796. (Of course,
  6797. the location of the Lua interpreter may be different in your machine.
  6798. If @id{lua} is in your @id{PATH},
  6799. then
  6800. @verbatim{
  6801. #!/usr/bin/env lua
  6802. }
  6803. is a more portable solution.)
  6804. }
  6805. @sect1{incompat| @title{Incompatibilities with the Previous Version}
  6806. Here we list the incompatibilities that you may find when moving a program
  6807. from @N{Lua 5.3} to @N{Lua 5.4}.
  6808. You can avoid some incompatibilities by compiling Lua with
  6809. appropriate options (see file @id{luaconf.h}).
  6810. However,
  6811. all these compatibility options will be removed in the future.
  6812. Lua versions can always change the C API in ways that
  6813. do not imply source-code changes in a program,
  6814. such as the numeric values for constants
  6815. or the implementation of functions as macros.
  6816. Therefore,
  6817. you should not assume that binaries are compatible between
  6818. different Lua versions.
  6819. Always recompile clients of the Lua API when
  6820. using a new version.
  6821. Similarly, Lua versions can always change the internal representation
  6822. of precompiled chunks;
  6823. precompiled chunks are not compatible between different Lua versions.
  6824. The standard paths in the official distribution may
  6825. change between versions.
  6826. @sect2{@title{Changes in the Language}
  6827. @itemize{
  6828. @item{
  6829. The coercion of strings to numbers in
  6830. arithmetic and bitwise operations
  6831. has been removed from the core language.
  6832. The string library does a similar job
  6833. for arithmetic (but not for bitwise) operations
  6834. using the string metamethods.
  6835. However, unlike in previous versions,
  6836. the new implementation preserves the implicit type of the numeral
  6837. in the string.
  6838. For instance, the result of @T{"1" + "2"} now is an integer,
  6839. not a float.
  6840. }
  6841. @item{
  6842. The use of the @idx{__lt} metamethod to emulate @id{__le}
  6843. has been removed.
  6844. When needed, this metamethod must be explicitly defined.
  6845. }
  6846. @item{
  6847. When a coroutine finishes with an error,
  6848. its stack is unwound (to run any pending closing methods).
  6849. }
  6850. @item{
  6851. A label for a @Rw{goto} cannot be declared where a label with the same
  6852. name is visible, even if this other label is declared in an enclosing
  6853. block.
  6854. }
  6855. }
  6856. }
  6857. @sect2{@title{Changes in the Libraries}
  6858. @itemize{
  6859. @item{
  6860. The pseudo-random number generator used by the function @Lid{math.random}
  6861. now starts with a somewhat random seed.
  6862. Moreover, it uses a different algorithm.
  6863. }
  6864. @item{
  6865. The function @Lid{io.lines} now returns three extra values,
  6866. besides the iterator function.
  6867. You can enclose the call in parentheses if you need to
  6868. discard these extra results.
  6869. }
  6870. }
  6871. }
  6872. @sect2{@title{Changes in the API}
  6873. @itemize{
  6874. @item{
  6875. Full userdata now has an arbitrary number of associated user values.
  6876. Therefore, the functions @id{lua_newuserdata},
  6877. @id{lua_setuservalue}, and @id{lua_getuservalue} were
  6878. replaced by @Lid{lua_newuserdatauv},
  6879. @Lid{lua_setiuservalue}, and @Lid{lua_getiuservalue},
  6880. which have an extra argument.
  6881. For compatibility, the old names still work as macros assuming
  6882. one single user value.
  6883. Note, however, that the call @T{lua_newuserdatauv(L,size,0)}
  6884. produces a smaller userdata.
  6885. }
  6886. @item{
  6887. The function @Lid{lua_resume} has an extra parameter.
  6888. This out parameter returns the number of values on
  6889. the top of the stack that were yielded or returned by the coroutine.
  6890. (In previous versions,
  6891. those values were the entire stack.)
  6892. }
  6893. @item{
  6894. The function @Lid{lua_version} returns the version number,
  6895. instead of an address of the version number.
  6896. (The Lua core should work correctly with libraries using their
  6897. own static copies of the same core,
  6898. so there is no need to check whether they are using the same
  6899. address space.)
  6900. }
  6901. @item{
  6902. The constant @id{LUA_ERRGCMM} was removed.
  6903. Errors in finalizers are never propagated;
  6904. instead, they generate a warning.
  6905. }
  6906. }
  6907. }
  6908. }
  6909. @C{[===============================================================}
  6910. @sect1{BNF| @title{The Complete Syntax of Lua}
  6911. Here is the complete syntax of Lua in extended BNF.
  6912. As usual in extended BNF,
  6913. @bnfNter{{A}} means 0 or more @bnfNter{A}s,
  6914. and @bnfNter{[A]} means an optional @bnfNter{A}.
  6915. (For operator precedences, see @See{prec};
  6916. for a description of the terminals
  6917. @bnfNter{Name}, @bnfNter{Numeral},
  6918. and @bnfNter{LiteralString}, see @See{lexical}.)
  6919. @index{grammar}
  6920. @Produc{
  6921. @producname{chunk}@producbody{block}
  6922. @producname{block}@producbody{@bnfrep{stat} @bnfopt{retstat}}
  6923. @producname{stat}@producbody{
  6924. @bnfter{;}
  6925. @OrNL varlist @bnfter{=} explist
  6926. @OrNL functioncall
  6927. @OrNL label
  6928. @OrNL @Rw{break}
  6929. @OrNL @Rw{goto} Name
  6930. @OrNL @Rw{do} block @Rw{end}
  6931. @OrNL @Rw{while} exp @Rw{do} block @Rw{end}
  6932. @OrNL @Rw{repeat} block @Rw{until} exp
  6933. @OrNL @Rw{if} exp @Rw{then} block
  6934. @bnfrep{@Rw{elseif} exp @Rw{then} block}
  6935. @bnfopt{@Rw{else} block} @Rw{end}
  6936. @OrNL @Rw{for} @bnfNter{Name} @bnfter{=} exp @bnfter{,} exp @bnfopt{@bnfter{,} exp}
  6937. @Rw{do} block @Rw{end}
  6938. @OrNL @Rw{for} namelist @Rw{in} explist @Rw{do} block @Rw{end}
  6939. @OrNL @Rw{function} funcname funcbody
  6940. @OrNL @Rw{local} @Rw{function} @bnfNter{Name} funcbody
  6941. @OrNL @Rw{local} namelist @bnfopt{@bnfter{=} explist}
  6942. @OrNL @Rw{local} @bnfter{*} @bnfter{toclose} Name @bnfter{=} exp
  6943. }
  6944. @producname{retstat}@producbody{@Rw{return}
  6945. @bnfopt{explist} @bnfopt{@bnfter{;}}}
  6946. @producname{label}@producbody{@bnfter{::} Name @bnfter{::}}
  6947. @producname{funcname}@producbody{@bnfNter{Name} @bnfrep{@bnfter{.} @bnfNter{Name}}
  6948. @bnfopt{@bnfter{:} @bnfNter{Name}}}
  6949. @producname{varlist}@producbody{var @bnfrep{@bnfter{,} var}}
  6950. @producname{var}@producbody{
  6951. @bnfNter{Name}
  6952. @Or prefixexp @bnfter{[} exp @bnfter{]}
  6953. @Or prefixexp @bnfter{.} @bnfNter{Name}
  6954. }
  6955. @producname{namelist}@producbody{@bnfNter{Name} @bnfrep{@bnfter{,} @bnfNter{Name}}}
  6956. @producname{explist}@producbody{exp @bnfrep{@bnfter{,} exp}}
  6957. @producname{exp}@producbody{
  6958. @Rw{nil}
  6959. @Or @Rw{false}
  6960. @Or @Rw{true}
  6961. @Or @bnfNter{Numeral}
  6962. @Or @bnfNter{LiteralString}
  6963. @Or @bnfter{...}
  6964. @Or functiondef
  6965. @OrNL prefixexp
  6966. @Or tableconstructor
  6967. @Or exp binop exp
  6968. @Or unop exp
  6969. }
  6970. @producname{prefixexp}@producbody{var @Or functioncall @Or @bnfter{(} exp @bnfter{)}}
  6971. @producname{functioncall}@producbody{
  6972. prefixexp args
  6973. @Or prefixexp @bnfter{:} @bnfNter{Name} args
  6974. }
  6975. @producname{args}@producbody{
  6976. @bnfter{(} @bnfopt{explist} @bnfter{)}
  6977. @Or tableconstructor
  6978. @Or @bnfNter{LiteralString}
  6979. }
  6980. @producname{functiondef}@producbody{@Rw{function} funcbody}
  6981. @producname{funcbody}@producbody{@bnfter{(} @bnfopt{parlist} @bnfter{)} block @Rw{end}}
  6982. @producname{parlist}@producbody{namelist @bnfopt{@bnfter{,} @bnfter{...}}
  6983. @Or @bnfter{...}}
  6984. @producname{tableconstructor}@producbody{@bnfter{@Open} @bnfopt{fieldlist} @bnfter{@Close}}
  6985. @producname{fieldlist}@producbody{field @bnfrep{fieldsep field} @bnfopt{fieldsep}}
  6986. @producname{field}@producbody{@bnfter{[} exp @bnfter{]} @bnfter{=} exp @Or @bnfNter{Name} @bnfter{=} exp @Or exp}
  6987. @producname{fieldsep}@producbody{@bnfter{,} @Or @bnfter{;}}
  6988. @producname{binop}@producbody{
  6989. @bnfter{+} @Or @bnfter{-} @Or @bnfter{*} @Or @bnfter{/} @Or @bnfter{//}
  6990. @Or @bnfter{^} @Or @bnfter{%}
  6991. @OrNL
  6992. @bnfter{&} @Or @bnfter{~} @Or @bnfter{|} @Or @bnfter{>>} @Or @bnfter{<<}
  6993. @Or @bnfter{..}
  6994. @OrNL
  6995. @bnfter{<} @Or @bnfter{<=} @Or @bnfter{>} @Or @bnfter{>=}
  6996. @Or @bnfter{==} @Or @bnfter{~=}
  6997. @OrNL
  6998. @Rw{and} @Or @Rw{or}}
  6999. @producname{unop}@producbody{@bnfter{-} @Or @Rw{not} @Or @bnfter{#} @Or
  7000. @bnfter{~}}
  7001. }
  7002. }
  7003. @C{]===============================================================}
  7004. }
  7005. @C{)]-------------------------------------------------------------------------}