manual.of 292 KB

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