manual.of 292 KB

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