luaref.txt 222 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889
  1. *luaref.txt* Nvim
  2. *luaref*
  3. LUA REFERENCE MANUAL
  4. Version 0.3.0
  5. August 7th, 2022
  6. Vimdoc version (c) 2006 by Luis Carvalho
  7. <lexcarvalho at gmail dot com>
  8. Adapted from "Lua: 5.1 reference manual"
  9. R. Ierusalimschy, L. H. de Figueiredo, W. Celes
  10. Copyright (c) 2006 Lua.org, PUC-Rio.
  11. See |lua-ref-doc| for information on this manual.
  12. See |lua-ref-copyright| for copyright and licenses.
  13. Type |gO| to see the table of contents.
  14. ==============================================================================
  15. 1 INTRODUCTION *luaref-intro*
  16. Lua is an extension programming language designed to support general
  17. procedural programming with data description facilities. It also offers good
  18. support for object-oriented programming, functional programming, and
  19. data-driven programming. Lua is intended to be used as a powerful,
  20. light-weight scripting language for any program that needs one. Lua is
  21. implemented as a library, written in clean C (that is, in the common subset of
  22. ANSI C and C++).
  23. Being an extension language, Lua has no notion of a "main" program: it only
  24. works embedded in a host client, called the embedding program or simply the
  25. host. This host program can invoke functions to execute a piece of Lua code,
  26. can write and read Lua variables, and can register C functions to be called by
  27. Lua code. Through the use of C functions, Lua can be augmented to cope with a
  28. wide range of different domains, thus creating customized programming
  29. languages sharing a syntactical framework.
  30. Lua is free software, and is provided as usual with no guarantees, as stated
  31. in its license. The implementation described in this manual is available at
  32. Lua's official web site, www.lua.org.
  33. Like any other reference manual, this document is dry in places. For a
  34. discussion of the decisions behind the design of Lua, see references at
  35. |lua-ref-bibliography|. For a detailed introduction to programming in Lua, see
  36. Roberto's book, Programming in Lua.
  37. Lua means "moon" in Portuguese and is pronounced LOO-ah.
  38. ==============================================================================
  39. 2 THE LANGUAGE *lua-language*
  40. This section describes the lexis, the syntax, and the semantics of Lua. In
  41. other words, this section describes which tokens are valid, how they can be
  42. combined, and what their combinations mean.
  43. The language constructs will be explained using the usual extended BNF
  44. notation, in which `{ a }` means 0 or more `a`'s, and `[ a ]` means an optional `a`.
  45. ==============================================================================
  46. 2.1 Lexical Conventions *lua-lexical*
  47. *lua-names* *lua-identifiers*
  48. Names (also called identifiers) in Lua can be any string of letters, digits,
  49. and underscores, not beginning with a digit. This coincides with the
  50. definition of identifiers in most languages. (The definition of letter depends
  51. on the current locale: any character considered alphabetic by the current
  52. locale can be used in an identifier.) Identifiers are used to name variables
  53. and table fields.
  54. The following keywords are reserved and cannot be used as names:
  55. >
  56. and break do else elseif
  57. end false for function if
  58. in local nil not or
  59. repeat return then true until while
  60. <
  61. Lua is a case-sensitive language: `and` is a reserved word, but `And` and `AND` are
  62. two different, valid names. As a convention, names starting with an underscore
  63. followed by uppercase letters (such as `_VERSION`) are reserved for internal
  64. global variables used by Lua.
  65. The following strings denote other tokens:
  66. >
  67. + - * / % ^ #
  68. == ~= <= >= < > =
  69. ( ) { } [ ]
  70. ; : , . .. ...
  71. <
  72. *lua-literal*
  73. Literal strings can be delimited by matching single or double quotes, and can
  74. contain the following C-like escape sequences:
  75. - `\a` bell
  76. - `\b` backspace
  77. - `\f` form feed
  78. - `\n` newline
  79. - `\r` carriage return
  80. - `\t` horizontal tab
  81. - `\v` vertical tab
  82. - `\\` backslash
  83. - `\"` quotation mark (double quote)
  84. - `\'` apostrophe (single quote)
  85. Moreover, a backslash followed by a real newline results in a newline in the
  86. string. A character in a string may also be specified by its numerical value
  87. using the escape sequence `\ddd`, where `ddd` is a sequence of up to three
  88. decimal digits. (Note that if a numerical escape is to be followed by a digit,
  89. it must be expressed using exactly three digits.) Strings in Lua may contain
  90. any 8-bit value, including embedded zeros, which can be specified as `\0`.
  91. To put a double (single) quote, a newline, a backslash, or an embedded zero
  92. inside a literal string enclosed by double (single) quotes you must use an
  93. escape sequence. Any other character may be directly inserted into the
  94. literal. (Some control characters may cause problems for the file system, but
  95. Lua has no problem with them.)
  96. Literal strings can also be defined using a long format enclosed by long
  97. brackets. We define an opening long bracket of level n as an opening square
  98. bracket followed by n equal signs followed by another opening square bracket.
  99. So, an opening long bracket of level 0 is written as `[[`, an opening long
  100. bracket of level 1 is written as `[=[`, and so on.
  101. A closing long bracket is defined similarly; for instance, a closing long
  102. bracket of level 4 is written as `]====]`. A long string starts with an
  103. opening long bracket of any level and ends at the first closing long bracket
  104. of the same level. Literals in this bracketed form may run for several lines,
  105. do not interpret any escape sequences, and ignore long brackets of any other
  106. level. They may contain anything except a closing bracket of the proper level.
  107. For convenience, when the opening long bracket is immediately followed by a
  108. newline, the newline is not included in the string. As an example, in a system
  109. using ASCII (in which `a` is coded as 97, newline is coded as 10, and `1` is
  110. coded as 49), the five literals below denote the same string:
  111. >lua
  112. a = 'alo\n123"'
  113. a = "alo\n123\""
  114. a = '\97lo\10\04923"'
  115. a = [[alo
  116. 123"]]
  117. a = [==[
  118. alo
  119. 123"]==]
  120. <
  121. *lua-numconstant*
  122. A numerical constant may be written with an optional decimal part and an
  123. optional decimal exponent. Lua also accepts integer hexadecimal constants, by
  124. prefixing them with `0x`. Examples of valid numerical constants are
  125. >
  126. 3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56
  127. <
  128. *lua-comment*
  129. A comment starts with a double hyphen (`--`) anywhere outside a string. If the
  130. text immediately after `--` is not an opening long bracket, the comment is a
  131. short comment, which runs until the end of the line. Otherwise, it is a long
  132. comment, which runs until the corresponding closing long bracket. Long
  133. comments are frequently used to disable code temporarily.
  134. ==============================================================================
  135. 2.2 Values and Types *lua-values*
  136. Lua is a dynamically typed language. This means that variables do not have
  137. types; only values do. There are no type definitions in the language. All
  138. values carry their own type.
  139. All values in Lua are first-class values. This means that all values can be
  140. stored in variables, passed as arguments to other functions, and returned as
  141. results.
  142. *lua-types* *lua-nil*
  143. *lua-true* *lua-false*
  144. *lua-number* *lua-string*
  145. There are eight basic types in Lua: `nil`, `boolean`, `number`, `string`,
  146. `function`, `userdata`, `thread`, and `table`. Nil is the type of the value
  147. `nil`, whose main property is to be different from any other value; it usually
  148. represents the absence of a useful value. Boolean is the type of the values
  149. `false` and `true`. Both `nil` and `false` make a condition false; any other
  150. value makes it true. Number represents real (double-precision floating-point)
  151. numbers. (It is easy to build Lua interpreters that use other internal
  152. representations for numbers, such as single-precision float or long integers;
  153. see file `luaconf.h`.) String represents arrays of characters. Lua is 8-bit
  154. clean: strings may contain any 8-bit character, including embedded zeros
  155. (`\0`) (see |lua-literal|).
  156. Lua can call (and manipulate) functions written in Lua and functions written
  157. in C (see |lua-function|).
  158. *lua-userdatatype*
  159. The type userdata is provided to allow arbitrary C data to be stored in Lua
  160. variables. This type corresponds to a block of raw memory and has no
  161. pre-defined operations in Lua, except assignment and identity test. However,
  162. by using metatables, the programmer can define operations for userdata values
  163. (see |lua-metatable|). Userdata values cannot be created or modified in Lua,
  164. only through the C API. This guarantees the integrity of data owned by the
  165. host program.
  166. *lua-thread*
  167. The type `thread` represents independent threads of execution and it is used to
  168. implement coroutines (see |lua-coroutine|). Do not confuse Lua threads with
  169. operating-system threads. Lua supports coroutines on all systems, even those
  170. that do not support threads.
  171. *lua-table*
  172. The type `table` implements associative arrays, that is, arrays that can be
  173. indexed not only with numbers, but with any value (except `nil`). Tables can
  174. be heterogeneous; that is, they can contain values of all types (except
  175. `nil`). Tables are the sole data structuring mechanism in Lua; they may be
  176. used to represent ordinary arrays, symbol tables, sets, records, graphs,
  177. trees, etc. To represent records, Lua uses the field name as an index. The
  178. language supports this representation by providing `a.name` as syntactic sugar
  179. for `a["name"]`. There are several convenient ways to create tables in Lua
  180. (see |lua-tableconstructor|).
  181. Like indices, the value of a table field can be of any type (except `nil`). In
  182. particular, because functions are first-class values, table fields may contain
  183. functions. Thus tables may also carry methods (see |lua-function-define|).
  184. Tables, functions, threads and (full) userdata values are objects: variables
  185. do not actually contain these values, only references to them. Assignment,
  186. parameter passing, and function returns always manipulate references to such
  187. values; these operations do not imply any kind of copy.
  188. The library function `type` returns a string describing the type of a given
  189. value (see |lua-type()|).
  190. ------------------------------------------------------------------------------
  191. 2.2.1 Coercion *lua-coercion*
  192. Lua provides automatic conversion between string and number values at run
  193. time. Any arithmetic operation applied to a string tries to convert that
  194. string to a number, following the usual conversion rules. Conversely, whenever
  195. a number is used where a string is expected, the number is converted to a
  196. string, in a reasonable format. For complete control of how numbers are
  197. converted to strings, use the `format` function from the string library (see
  198. |string.format()|).
  199. ==============================================================================
  200. 2.3 Variables *lua-variables*
  201. Variables are places that store values. There are three kinds of variables in
  202. Lua: global variables, local variables, and table fields.
  203. A single name can denote a global variable or a local variable (or a
  204. function's formal parameter, which is a particular form of local variable):
  205. >
  206. var ::= Name
  207. <
  208. Name denotes identifiers, as defined in |lua-lexical|.
  209. Any variable is assumed to be global unless explicitly declared as a local
  210. (see |lua-local|). Local variables are lexically scoped: local
  211. variables can be freely accessed by functions defined inside their scope (see
  212. |lua-visibility|).
  213. Before the first assignment to a variable, its value is `nil`.
  214. Square brackets are used to index a table:
  215. >
  216. var ::= prefixexp [ exp ]
  217. <
  218. The first expression (`prefixexp`) should result in a table value; the second
  219. expression (`exp`) identifies a specific entry inside that table. The
  220. expression denoting the table to be indexed has a restricted syntax; see
  221. |lua-expressions| for details.
  222. The syntax `var.NAME` is just syntactic sugar for `var["NAME"]` :
  223. >
  224. var ::= prefixexp . Name
  225. <
  226. All global variables live as fields in ordinary Lua tables, called environment
  227. tables or simply environments (see |lua-environments|). Each function
  228. has its own reference to an environment, so that all global variables in this
  229. function will refer to this environment table. When a function is created, it
  230. inherits the environment from the function that created it. To get the
  231. environment table of a Lua function, you call `getfenv` (see
  232. |lua_getfenv()|). To replace it, you call `setfenv` (see |setfenv()|).
  233. (You can only manipulate the environment of C functions through the debug
  234. library; see |lua-lib-debug|.)
  235. An access to a global variable `x` is equivalent to `_env.x`, which in turn is
  236. equivalent to
  237. >lua
  238. gettable_event(_env, "x")
  239. <
  240. where `_env` is the environment of the running function. (The `_env` variable is
  241. not defined in Lua. We use it here only for explanatory purposes.)
  242. The meaning of accesses to global variables and table fields can be changed
  243. via metatables. An access to an indexed variable `t[i]` is equivalent to a
  244. call `gettable_event(t,i)`. (See |lua-metatable| for a complete description of
  245. the `gettable_event` function. This function is not defined or callable in
  246. Lua. We use it here only for explanatory purposes.)
  247. ==============================================================================
  248. 2.4 Statements *lua-statement*
  249. Lua supports an almost conventional set of statements, similar to those in
  250. Pascal or C. This set includes assignment, control structures, function
  251. calls, and variable declarations.
  252. ------------------------------------------------------------------------------
  253. 2.4.1 Chunks *lua-chunk*
  254. The unit of execution of Lua is called a chunk. A chunk is simply a sequence
  255. of statements, which are executed sequentially. Each statement can be
  256. optionally followed by a semicolon:
  257. >
  258. chunk ::= {stat [ ; ]}
  259. <
  260. There are no empty statements and thus `;;` is not legal.
  261. Lua handles a chunk as the body of an anonymous function with a variable
  262. number of arguments (see |lua-function-define|). As such, chunks can define
  263. local variables, receive arguments, and return values.
  264. A chunk may be stored in a file or in a string inside the host program. When a
  265. chunk is executed, first it is pre-compiled into instructions for a virtual
  266. machine, and then the compiled code is executed by an interpreter for the
  267. virtual machine.
  268. Chunks may also be pre-compiled into binary form; see program `luac` for
  269. details. Programs in source and compiled forms are interchangeable; Lua
  270. automatically detects the file type and acts accordingly.
  271. ------------------------------------------------------------------------------
  272. 2.4.2 Blocks *lua-block*
  273. A block is a list of statements; syntactically, a block is the same as a
  274. chunk:
  275. >
  276. block ::= chunk
  277. <
  278. *lua-do* *lua-end*
  279. A block may be explicitly delimited to produce a single statement:
  280. >
  281. stat ::= do block end
  282. <
  283. Explicit blocks are useful to control the scope of variable declarations.
  284. Explicit blocks are also sometimes used to add a `return` or `break` statement
  285. in the middle of another block (see |lua-control|).
  286. ------------------------------------------------------------------------------
  287. 2.4.3 Assignment *lua-assign*
  288. Lua allows multiple assignment. Therefore, the syntax for assignment defines a
  289. list of variables on the left side and a list of expressions on the right
  290. side. The elements in both lists are separated by commas:
  291. >
  292. stat ::= varlist1 = explist1
  293. varlist1 ::= var { , var }
  294. explist1 ::= exp { , exp }
  295. <
  296. Expressions are discussed in |lua-expressions|.
  297. Before the assignment, the list of values is adjusted to the length of the
  298. list of variables. If there are more values than needed, the excess values are
  299. thrown away. If there are fewer values than needed, the list is extended with
  300. as many `nil`s as needed. If the list of expressions ends with a function
  301. call, then all values returned by this call enter in the list of values,
  302. before the adjustment (except when the call is enclosed in parentheses; see
  303. |lua-expressions|).
  304. The assignment statement first evaluates all its expressions and only then are
  305. the assignments performed. Thus the code
  306. >lua
  307. i = 3
  308. i, a[i] = i+1, 20
  309. <
  310. sets `a[3]` to 20, without affecting `a[4]` because the `i` in `a[i]` is evaluated (to
  311. 3) before it is assigned 4. Similarly, the line
  312. >lua
  313. x, y = y, x
  314. <
  315. exchanges the values of `x` and `y`.
  316. The meaning of assignments to global variables and table fields can be changed
  317. via metatables. An assignment to an indexed variable `t[i] = val` is
  318. equivalent to `settable_event(t,i,val)`. (See |lua-metatable| for a complete
  319. description of the `settable_event` function. This function is not defined or
  320. callable in Lua. We use it here only for explanatory purposes.)
  321. An assignment to a global variable `x = val` is equivalent to the
  322. assignment `_env.x = val`, which in turn is equivalent to
  323. >lua
  324. settable_event(_env, "x", val)
  325. <
  326. where `_env` is the environment of the running function. (The `_env` variable is
  327. not defined in Lua. We use it here only for explanatory purposes.)
  328. ------------------------------------------------------------------------------
  329. 2.4.4 Control Structures *lua-control*
  330. *lua-if* *lua-then* *lua-else* *lua-elseif*
  331. *lua-while* *lua-repeat* *lua-until*
  332. The control structures `if`, `while`, and `repeat` have the usual meaning and
  333. familiar syntax:
  334. >
  335. stat ::= while exp do block end
  336. stat ::= repeat block until exp
  337. stat ::= if exp then block { elseif exp then block }
  338. [ else block ] end
  339. <
  340. Lua also has a `for` statement, in two flavors (see |lua-for|).
  341. The condition expression of a control structure may return any value.
  342. Both `false` and `nil` are considered false. All values different
  343. from `nil` and `false` are considered true (in particular, the number 0 and the
  344. empty string are also true).
  345. In the `repeat-until` loop, the inner block does not end at the `until` keyword,
  346. but only after the condition. So, the condition can refer to local variables
  347. declared inside the loop block.
  348. *lua-return*
  349. The `return` statement is used to return values from a function or a chunk
  350. (which is just a function). Functions and chunks may return more than one
  351. value, so the syntax for the `return` statement is
  352. `stat ::=` `return` `[explist1]`
  353. *lua-break*
  354. The `break` statement is used to terminate the execution of a `while`, `repeat`,
  355. or `for` loop, skipping to the next statement after the loop:
  356. `stat ::=` `break`
  357. A `break` ends the innermost enclosing loop.
  358. The `return` and `break` statements can only be written as the `last`
  359. statement of a block. If it is really necessary to `return` or `break` in the
  360. middle of a block, then an explicit inner block can be used, as in the idioms
  361. `do return end` and `do break end`, because now `return` and `break` are
  362. the last statements in their (inner) blocks.
  363. ------------------------------------------------------------------------------
  364. 2.4.5 For Statement *for* *lua-for*
  365. The `for` statement has two forms: one numeric and one generic.
  366. The numeric `for` loop repeats a block of code while a control variable runs
  367. through an arithmetic progression. It has the following syntax:
  368. >
  369. stat ::= for Name = exp , exp [ , exp ] do block end
  370. <
  371. The `block` is repeated for `name` starting at the value of the first `exp`, until
  372. it passes the second `exp` by steps of the third `exp`. More precisely,
  373. a `for` statement like
  374. `for var = e1, e2, e3 do block end`
  375. is equivalent to the code: >lua
  376. do
  377. local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3)
  378. if not ( var and limit and step ) then error() end
  379. while ( step >0 and var <= limit )
  380. or ( step <=0 and var >= limit ) do
  381. block
  382. var = var + step
  383. end
  384. end
  385. <
  386. Note the following:
  387. - All three control expressions are evaluated only once, before the loop
  388. starts. They must all result in numbers.
  389. - `var`, `limit` and `step` are invisible variables. The names are here for
  390. explanatory purposes only.
  391. - If the third expression (the step) is absent, then a step of 1 is used.
  392. - You can use `break` to exit a `for` loop.
  393. - The loop variable `var` is local to the loop; you cannot use its value
  394. after the `for` ends or is broken. If you need this value, assign it to
  395. another variable before breaking or exiting the loop.
  396. *for-in*
  397. The generic `for` statement works over functions, called |iterator|s. On each
  398. iteration, the iterator function is called to produce a new value, stopping
  399. when this new value is `nil`. The generic `for` loop has the following syntax:
  400. >
  401. stat ::= for namelist in explist1 do block end
  402. namelist ::= Name { , Name }
  403. <
  404. A `for` statement like
  405. `for` `var1, ..., varn` `in` `explist` `do` `block` `end`
  406. is equivalent to the code: >lua
  407. do
  408. local f, s, var = explist
  409. while true do
  410. local var1, ..., varn = f(s, var)
  411. var = var1
  412. if var == nil then break end
  413. block
  414. end
  415. end
  416. <
  417. Note the following:
  418. - `explist` is evaluated only once. Its results are an iterator function,
  419. a `state`, and an initial value for the first iterator variable.
  420. - `f`, `s`, and `var` are invisible variables. The names are here for
  421. explanatory purposes only.
  422. - You can use `break` to exit a `for` loop.
  423. - The loop variables `var1, ..., varn` are local to the loop; you cannot use
  424. their values after the `for` ends. If you need these values, then assign
  425. them to other variables before breaking or exiting the loop.
  426. ------------------------------------------------------------------------------
  427. 2.4.6 Function Calls as Statements *lua-funcstatement*
  428. To allow possible side-effects, function calls can be executed as statements:
  429. >
  430. stat ::= functioncall
  431. <
  432. In this case, all returned values are thrown away. Function calls are
  433. explained in |lua-function|.
  434. ------------------------------------------------------------------------------
  435. 2.4.7 Local Declarations *lua-local*
  436. Local variables may be declared anywhere inside a block. The declaration may
  437. include an initial assignment:
  438. >
  439. stat ::= local namelist [ = explist1 ]
  440. namelist ::= Name { , Name }
  441. <
  442. If present, an initial assignment has the same semantics of a multiple
  443. assignment (see |lua-assign|). Otherwise, all variables are initialized
  444. with `nil`.
  445. A chunk is also a block (see |lua-chunk|), and so local variables can be
  446. declared in a chunk outside any explicit block. The scope of such local
  447. variables extends until the end of the chunk.
  448. The visibility rules for local variables are explained in |lua-visibility|.
  449. ==============================================================================
  450. 2.5 Expressions *lua-expressions*
  451. The basic expressions in Lua are the following:
  452. >
  453. exp ::= prefixexp
  454. exp ::= nil | false | true
  455. exp ::= Number
  456. exp ::= String
  457. exp ::= function
  458. exp ::= tableconstructor
  459. exp ::= ...
  460. exp ::= exp binop exp
  461. exp ::= unop exp
  462. prefixexp ::= var | functioncall | ( exp )
  463. <
  464. Numbers and literal strings are explained in |lua-lexical|; variables are
  465. explained in |lua-variables|; function definitions are explained in
  466. |lua-function-define|; function calls are explained in |lua-function|;
  467. table constructors are explained in |lua-tableconstructor|. Vararg expressions,
  468. denoted by three dots (`...`), can only be used inside vararg functions;
  469. they are explained in |lua-function-define|.
  470. Binary operators comprise arithmetic operators (see |lua-arithmetic|),
  471. relational operators (see |lua-relational|), logical operators (see
  472. |lua-logicalop|), and the concatenation operator (see |lua-concat|).
  473. Unary operators comprise the unary minus (see |lua-arithmetic|), the unary
  474. `not` (see |lua-logicalop|), and the unary length operator (see |lua-length|).
  475. Both function calls and vararg expressions may result in multiple values. If
  476. the expression is used as a statement (see |lua-funcstatement|)
  477. (only possible for function calls), then its return list is adjusted to zero
  478. elements, thus discarding all returned values. If the expression is used as
  479. the last (or the only) element of a list of expressions, then no adjustment is
  480. made (unless the call is enclosed in parentheses). In all other contexts, Lua
  481. adjusts the result list to one element, discarding all values except the first
  482. one.
  483. Here are some examples:
  484. >lua
  485. f() -- adjusted to 0 results
  486. g(f(), x) -- f() is adjusted to 1 result
  487. g(x, f()) -- g gets x plus all results from f()
  488. a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
  489. a,b = ... -- a gets the first vararg parameter, b gets
  490. -- the second (both a and b may get nil if there
  491. -- is no corresponding vararg parameter)
  492. a,b,c = x, f() -- f() is adjusted to 2 results
  493. a,b,c = f() -- f() is adjusted to 3 results
  494. return f() -- returns all results from f()
  495. return ... -- returns all received vararg parameters
  496. return x,y,f() -- returns x, y, and all results from f()
  497. {f()} -- creates a list with all results from f()
  498. {...} -- creates a list with all vararg parameters
  499. {f(), nil} -- f() is adjusted to 1 result
  500. <
  501. An expression enclosed in parentheses always results in only one value. Thus,
  502. `(f(x,y,z))` is always a single value, even if `f` returns several values.
  503. (The value of `(f(x,y,z))` is the first value returned by `f` or `nil` if `f` does not
  504. return any values.)
  505. ------------------------------------------------------------------------------
  506. 2.5.1 Arithmetic Operators *lua-arithmetic*
  507. Lua supports the usual arithmetic operators: the binary `+` (addition),
  508. `-` (subtraction), `*` (multiplication), `/` (division), `%` (modulo)
  509. and `^` (exponentiation); and unary `-` (negation). If the operands are numbers,
  510. or strings that can be converted to numbers (see |lua-coercion|), then all
  511. operations have the usual meaning. Exponentiation works for any exponent. For
  512. instance, `x^(-0.5)` computes the inverse of the square root of `x`. Modulo is
  513. defined as
  514. >lua
  515. a % b == a - math.floor(a/b)*b
  516. <
  517. That is, it is the remainder of a division that rounds the quotient towards
  518. minus infinity.
  519. ------------------------------------------------------------------------------
  520. 2.5.2 Relational Operators *lua-relational*
  521. The relational operators in Lua are
  522. >
  523. == ~= < > <= >=
  524. <
  525. These operators always result in `false` or `true`.
  526. Equality (`==`) first compares the type of its operands. If the types are
  527. different, then the result is `false`. Otherwise, the values of the operands
  528. are compared. Numbers and strings are compared in the usual way. Objects
  529. (tables, userdata, threads, and functions) are compared by reference: two
  530. objects are considered equal only if they are the same object. Every time you
  531. create a new object (a table, userdata, or function), this new object is
  532. different from any previously existing object.
  533. You can change the way that Lua compares tables and userdata using the "eq"
  534. metamethod (see |lua-metatable|).
  535. The conversion rules of coercion |lua-coercion| do not apply to
  536. equality comparisons. Thus, `"0"==0` evaluates to `false`, and `t[0]` and
  537. `t["0"]` denote different entries in a table.
  538. The operator `~=` is exactly the negation of equality (`==`).
  539. The order operators work as follows. If both arguments are numbers, then they
  540. are compared as such. Otherwise, if both arguments are strings, then their
  541. values are compared according to the current locale. Otherwise, Lua tries to
  542. call the "lt" or the "le" metamethod (see |lua-metatable|).
  543. ------------------------------------------------------------------------------
  544. 2.5.3 Logical Operators *lua-logicalop*
  545. The logical operators in Lua are
  546. >
  547. and or not
  548. <
  549. Like the control structures (see |lua-control|), all logical operators
  550. consider both `false` and `nil` as false and anything else as true.
  551. *lua-not* *lua-and* *lua-or*
  552. The negation operator `not` always returns `false` or `true`. The conjunction
  553. operator `and` returns its first argument if this value is `false` or `nil`;
  554. otherwise, `and` returns its second argument. The disjunction
  555. operator `or` returns its first argument if this value is different
  556. from `nil` and `false`; otherwise, `or` returns its second argument.
  557. Both `and` and `or` use short-cut evaluation, that is, the second operand is
  558. evaluated only if necessary. Here are some examples:
  559. >
  560. 10 or 20 --> 10
  561. 10 or error() --> 10
  562. nil or "a" --> "a"
  563. nil and 10 --> nil
  564. false and error() --> false
  565. false and nil --> false
  566. false or nil --> nil
  567. 10 and 20 --> 20
  568. <
  569. (In this manual, `-->` indicates the result of the preceding expression.)
  570. ------------------------------------------------------------------------------
  571. 2.5.4 Concatenation *lua-concat*
  572. The string concatenation operator in Lua is denoted by two dots (`..`).
  573. If both operands are strings or numbers, then they are converted to strings
  574. according to the rules mentioned in |lua-coercion|. Otherwise, the
  575. "concat" metamethod is called (see |lua-metatable|).
  576. ------------------------------------------------------------------------------
  577. 2.5.5 The Length Operator *lua-#* *lua-length*
  578. The length operator is denoted by the unary operator `#`. The length of a
  579. string is its number of bytes (that is, the usual meaning of string length
  580. when each character is one byte).
  581. The length of a table `t` is defined to be any integer index `n` such that `t[n]` is
  582. not `nil` and `t[n+1]` is `nil`; moreover, if `t[1]` is `nil`, `n` may be zero. For a
  583. regular array, with non-nil values from 1 to a given `n`, its length is exactly
  584. that `n`, the index of its last value. If the array has "holes" (that
  585. is, `nil` values between other non-nil values), then `#t` may be any of the
  586. indices that directly precedes a `nil` value (that is, it may consider any
  587. such `nil` value as the end of the array).
  588. ------------------------------------------------------------------------------
  589. 2.5.6 Precedence *lua-precedence*
  590. Operator precedence in Lua follows the table below, from lower to higher
  591. priority:
  592. >
  593. or
  594. and
  595. < > <= >= ~= ==
  596. ..
  597. + -
  598. * /
  599. not # - (unary)
  600. ^
  601. <
  602. As usual, you can use parentheses to change the precedences in an expression.
  603. The concatenation (`..`) and exponentiation (`^`) operators are right
  604. associative. All other binary operators are left associative.
  605. ------------------------------------------------------------------------------
  606. 2.5.7 Table Constructors *lua-tableconstructor*
  607. Table constructors are expressions that create tables. Every time a
  608. constructor is evaluated, a new table is created. Constructors can be used to
  609. create empty tables, or to create a table and initialize some of its fields.
  610. The general syntax for constructors is
  611. >
  612. tableconstructor ::= { [ fieldlist ] }
  613. fieldlist ::= field { fieldsep field } [ fieldsep ]
  614. field ::= [ exp ] = exp | Name = exp | exp
  615. fieldsep ::= , | ;
  616. <
  617. Each field of the form `[exp1] = exp2` adds to the new table an entry with
  618. key `exp1` and value `exp2`. A field of the form `name = exp` is equivalent to
  619. `["name"] = exp`. Finally, fields of the form `exp` are equivalent to
  620. `[i] = exp`, where `i` are consecutive numerical integers, starting with 1.
  621. Fields in the other formats do not affect this counting. For example,
  622. >lua
  623. a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
  624. <
  625. is equivalent to
  626. >lua
  627. do
  628. local t = {}
  629. t[f(1)] = g
  630. t[1] = "x" -- 1st exp
  631. t[2] = "y" -- 2nd exp
  632. t.x = 1 -- temp["x"] = 1
  633. t[3] = f(x) -- 3rd exp
  634. t[30] = 23
  635. t[4] = 45 -- 4th exp
  636. a = t
  637. end
  638. <
  639. If the last field in the list has the form `exp` and the expression is a
  640. function call, then all values returned by the call enter the list
  641. consecutively (see |lua-function|). To avoid this, enclose the function
  642. call in parentheses (see |lua-expressions|).
  643. The field list may have an optional trailing separator, as a convenience for
  644. machine-generated code.
  645. ------------------------------------------------------------------------------
  646. 2.5.8 Function Calls *lua-function*
  647. A function call in Lua has the following syntax:
  648. >
  649. functioncall ::= prefixexp args
  650. <
  651. In a function call, first `prefixexp` and `args` are evaluated. If the value
  652. of `prefixexp` has type `function`, then this function is called with the given
  653. arguments. Otherwise, the `prefixexp` "call" metamethod is called, having as
  654. first parameter the value of `prefixexp`, followed by the original call
  655. arguments (see |lua-metatable|).
  656. The form
  657. >
  658. functioncall ::= prefixexp : Name args
  659. <
  660. can be used to call "methods". A call `v:name(` `args` `)` is syntactic sugar
  661. for `v.name(v,` `args` `)`, except that `v` is evaluated only once.
  662. Arguments have the following syntax:
  663. >
  664. args ::= ( [ explist1 ] )
  665. args ::= tableconstructor
  666. args ::= String
  667. <
  668. All argument expressions are evaluated before the call. A call of the
  669. form `f{` `fields` `}` is syntactic sugar for `f({` `fields` `})`, that is, the
  670. argument list is a single new table. A call of the form `f'` `string` `'`
  671. (or `f"` `string` `"` or `f[[` `string` `]]`) is syntactic sugar for
  672. `f('` `string` `')`, that is, the argument list is a single literal string.
  673. As an exception to the free-format syntax of Lua, you cannot put a line break
  674. before the `(` in a function call. This restriction avoids some ambiguities
  675. in the language. If you write
  676. >lua
  677. a = f
  678. (g).x(a)
  679. <
  680. Lua would see that as a single statement, `a = f(g).x(a)`. So, if you want two
  681. statements, you must add a semi-colon between them. If you actually want to
  682. call `f`, you must remove the line break before `(g)`.
  683. *lua-tailcall*
  684. A call of the form `return` `functioncall` is called a tail call. Lua
  685. implements proper tail calls (or proper tail recursion): in a tail call, the
  686. called function reuses the stack entry of the calling function. Therefore,
  687. there is no limit on the number of nested tail calls that a program can
  688. execute. However, a tail call erases any debug information about the calling
  689. function. Note that a tail call only happens with a particular syntax, where
  690. the `return` has one single function call as argument; this syntax makes the
  691. calling function return exactly the returns of the called function. So, none
  692. of the following examples are tail calls:
  693. >lua
  694. return (f(x)) -- results adjusted to 1
  695. return 2 * f(x)
  696. return x, f(x) -- additional results
  697. f(x); return -- results discarded
  698. return x or f(x) -- results adjusted to 1
  699. <
  700. ------------------------------------------------------------------------------
  701. 2.5.9 Function Definitions *lua-function-define*
  702. The syntax for function definition is
  703. >
  704. function ::= function funcbody
  705. funcbody ::= ( [ parlist1 ] ) block end
  706. <
  707. The following syntactic sugar simplifies function definitions:
  708. >
  709. stat ::= function funcname funcbody
  710. stat ::= local function Name funcbody
  711. funcname ::= Name { . Name } [ : Name ]
  712. <
  713. The statement
  714. `function f ()` `body` `end`
  715. translates to
  716. `f = function ()` `body` `end`
  717. The statement
  718. `function t.a.b.c.f ()` `body` `end`
  719. translates to
  720. `t.a.b.c.f = function ()` `body` `end`
  721. The statement
  722. `local function f ()` `body` `end`
  723. translates to
  724. `local f; f = function f ()` `body` `end`
  725. not to
  726. `local f = function f ()` `body` `end`
  727. (This only makes a difference when the body of the function contains
  728. references to `f`.)
  729. *lua-closure*
  730. A function definition is an executable expression, whose value has type
  731. `function`. When Lua pre-compiles a chunk, all its function bodies are
  732. pre-compiled too. Then, whenever Lua executes the function definition, the
  733. function is instantiated (or closed). This function instance (or closure) is
  734. the final value of the expression. Different instances of the same function
  735. may refer to different external local variables and may have different
  736. environment tables.
  737. Parameters act as local variables that are initialized with the argument
  738. values:
  739. >
  740. parlist1 ::= namelist [ , ... ] | ...
  741. <
  742. *lua-vararg*
  743. When a function is called, the list of arguments is adjusted to the length of
  744. the list of parameters, unless the function is a variadic or vararg function,
  745. which is indicated by three dots (`...`) at the end of its parameter list. A
  746. vararg function does not adjust its argument list; instead, it collects all
  747. extra arguments and supplies them to the function through a vararg expression,
  748. which is also written as three dots. The value of this expression is a list of
  749. all actual extra arguments, similar to a function with multiple results. If a
  750. vararg expression is used inside another expression or in the middle of a list
  751. of expressions, then its return list is adjusted to one element. If the
  752. expression is used as the last element of a list of expressions, then no
  753. adjustment is made (unless the call is enclosed in parentheses).
  754. As an example, consider the following definitions:
  755. >lua
  756. function f(a, b) end
  757. function g(a, b, ...) end
  758. function r() return 1,2,3 end
  759. <
  760. Then, we have the following mapping from arguments to parameters and to the
  761. vararg expression:
  762. >
  763. CALL PARAMETERS
  764. f(3) a=3, b=nil
  765. f(3, 4) a=3, b=4
  766. f(3, 4, 5) a=3, b=4
  767. f(r(), 10) a=1, b=10
  768. f(r()) a=1, b=2
  769. g(3) a=3, b=nil, ... --> (nothing)
  770. g(3, 4) a=3, b=4, ... --> (nothing)
  771. g(3, 4, 5, 8) a=3, b=4, ... --> 5 8
  772. g(5, r()) a=5, b=1, ... --> 2 3
  773. <
  774. Results are returned using the `return` statement (see |lua-control|).
  775. If control reaches the end of a function without encountering
  776. a `return` statement, then the function returns with no results.
  777. *lua-colonsyntax*
  778. The colon syntax is used for defining methods, that is, functions that have an
  779. implicit extra parameter `self`. Thus, the statement
  780. `function t.a.b.c:f (` `params` `)` `body` `end`
  781. is syntactic sugar for
  782. `t.a.b.c:f = function (` `self`, `params` `)` `body` `end`
  783. ==============================================================================
  784. 2.6 Visibility Rules *lua-visibility*
  785. Lua is a lexically scoped language. The scope of variables begins at the first
  786. statement after their declaration and lasts until the end of the innermost
  787. block that includes the declaration. Consider the following example:
  788. >lua
  789. x = 10 -- global variable
  790. do -- new block
  791. local x = x -- new `x`, with value 10
  792. print(x) --> 10
  793. x = x+1
  794. do -- another block
  795. local x = x+1 -- another `x`
  796. print(x) --> 12
  797. end
  798. print(x) --> 11
  799. end
  800. print(x) --> 10 (the global one)
  801. <
  802. Notice that, in a declaration like `local x = x`, the new `x` being declared is
  803. not in scope yet, and so the second `x` refers to the outside variable.
  804. *lua-upvalue*
  805. Because of the lexical scoping rules, local variables can be freely accessed
  806. by functions defined inside their scope. A local variable used by an inner
  807. function is called an upvalue, or external local variable, inside the inner
  808. function.
  809. Notice that each execution of a local statement defines new local variables.
  810. Consider the following example:
  811. >lua
  812. a = {}
  813. local x = 20
  814. for i=1,10 do
  815. local y = 0
  816. a[i] = function () y=y+1; return x+y end
  817. end
  818. <
  819. The loop creates ten closures (that is, ten instances of the anonymous
  820. function). Each of these closures uses a different `y` variable, while all of
  821. them share the same `x`.
  822. ==============================================================================
  823. 2.7 Error Handling *lua-errors*
  824. Because Lua is an embedded extension language, all Lua actions start from
  825. C code in the host program calling a function from the Lua library (see
  826. |lua_pcall()|). Whenever an error occurs during Lua compilation or
  827. execution, control returns to C, which can take appropriate measures (such as
  828. print an error message).
  829. Lua code can explicitly generate an error by calling the `error` function (see
  830. |error()|). If you need to catch errors in Lua, you can use the `pcall`
  831. function (see |pcall()|).
  832. ==============================================================================
  833. 2.8 Metatables *metatable* *lua-metatable*
  834. Every value in Lua may have a metatable. This metatable is an ordinary Lua
  835. table that defines the behavior of the original table and userdata under
  836. certain special operations. You can change several aspects of the behavior of
  837. an object by setting specific fields in its metatable. For instance, when a
  838. non-numeric value is the operand of an addition, Lua checks for a function in
  839. the field `"__add"` in its metatable. If it finds one, Lua calls that function
  840. to perform the addition.
  841. We call the keys in a metatable events and the values metamethods. In the
  842. previous example, the event is "add" and the metamethod is the function that
  843. performs the addition.
  844. You can query the metatable of any value through the `getmetatable` function
  845. (see |getmetatable()|).
  846. You can replace the metatable of tables through the `setmetatable` function (see
  847. |setmetatable()|). You cannot change the metatable of other types from Lua
  848. (except using the debug library); you must use the C API for that.
  849. Tables and userdata have individual metatables (although multiple tables and
  850. userdata can share a same table as their metatable); values of all other types
  851. share one single metatable per type. So, there is one single metatable for all
  852. numbers, and for all strings, etc.
  853. A metatable may control how an object behaves in arithmetic operations, order
  854. comparisons, concatenation, length operation, and indexing. A metatable can
  855. also define a function to be called when a userdata is garbage collected. For
  856. each of those operations Lua associates a specific key called an event. When
  857. Lua performs one of those operations over a value, it checks whether this
  858. value has a metatable with the corresponding event. If so, the value
  859. associated with that key (the metamethod) controls how Lua will perform the
  860. operation.
  861. Metatables control the operations listed next. Each operation is identified by
  862. its corresponding name. The key for each operation is a string with its name
  863. prefixed by two underscores, `__`; for instance, the key for operation "add"
  864. is the string "__add". The semantics of these operations is better explained
  865. by a Lua function describing how the interpreter executes that operation.
  866. The code shown here in Lua is only illustrative; the real behavior is hard
  867. coded in the interpreter and it is much more efficient than this simulation.
  868. All functions used in these descriptions (`rawget`, `tonumber`, etc.) are
  869. described in |lua-lib-core|. In particular, to retrieve the metamethod of a
  870. given object, we use the expression
  871. >
  872. metatable(obj)[event]
  873. <
  874. This should be read as
  875. >lua
  876. rawget(metatable(obj) or {}, event)
  877. <
  878. That is, the access to a metamethod does not invoke other metamethods, and the
  879. access to objects with no metatables does not fail (it simply results
  880. in `nil`).
  881. "add": *__add()*
  882. ------
  883. the `+` operation.
  884. The function `getbinhandler` below defines how Lua chooses a handler for a
  885. binary operation. First, Lua tries the first operand. If its type does not
  886. define a handler for the operation, then Lua tries the second operand.
  887. >lua
  888. function getbinhandler (op1, op2, event)
  889. return metatable(op1)[event] or metatable(op2)[event]
  890. end
  891. <
  892. By using this function, the behavior of the `op1 + op2` is
  893. >lua
  894. function add_event (op1, op2)
  895. local o1, o2 = tonumber(op1), tonumber(op2)
  896. if o1 and o2 then -- both operands are numeric?
  897. return o1 + o2 -- `+` here is the primitive `add`
  898. else -- at least one of the operands is not numeric
  899. local h = getbinhandler(op1, op2, "__add")
  900. if h then
  901. -- call the handler with both operands
  902. return h(op1, op2)
  903. else -- no handler available: default behavior
  904. error(...)
  905. end
  906. end
  907. end
  908. <
  909. "sub": *__sub()*
  910. ------
  911. the `-` operation. Behavior similar to the "add" operation.
  912. "mul": *__mul()*
  913. ------
  914. the `*` operation. Behavior similar to the "add" operation.
  915. "div": *__div()*
  916. ------
  917. the `/` operation. Behavior similar to the "add" operation.
  918. "mod": *__mod()*
  919. ------
  920. the `%` operation. Behavior similar to the "add" operation, with the
  921. operation `o1 - floor(o1/o2)*o2` as the primitive operation.
  922. "pow": *__pow()*
  923. ------
  924. the `^` (exponentiation) operation. Behavior similar to the "add" operation,
  925. with the function `pow` (from the C math library) as the primitive operation.
  926. "unm": *__unm()*
  927. ------
  928. the unary `-` operation.
  929. >lua
  930. function unm_event (op)
  931. local o = tonumber(op)
  932. if o then -- operand is numeric?
  933. return -o -- `-` here is the primitive `unm`
  934. else -- the operand is not numeric.
  935. -- Try to get a handler from the operand
  936. local h = metatable(op).__unm
  937. if h then
  938. -- call the handler with the operand
  939. return h(op)
  940. else -- no handler available: default behavior
  941. error(...)
  942. end
  943. end
  944. end
  945. <
  946. "concat": *__concat()*
  947. ---------
  948. the `..` (concatenation) operation.
  949. >lua
  950. function concat_event (op1, op2)
  951. if (type(op1) == "string" or type(op1) == "number") and
  952. (type(op2) == "string" or type(op2) == "number") then
  953. return op1 .. op2 -- primitive string concatenation
  954. else
  955. local h = getbinhandler(op1, op2, "__concat")
  956. if h then
  957. return h(op1, op2)
  958. else
  959. error(...)
  960. end
  961. end
  962. end
  963. <
  964. "len": *__len()*
  965. ------
  966. the `#` operation.
  967. >lua
  968. function len_event (op)
  969. if type(op) == "string" then
  970. return strlen(op) -- primitive string length
  971. elseif type(op) == "table" then
  972. return #op -- primitive table length
  973. else
  974. local h = metatable(op).__len
  975. if h then
  976. -- call the handler with the operand
  977. return h(op)
  978. else -- no handler available: default behavior
  979. error(...)
  980. end
  981. end
  982. end
  983. <
  984. "eq": *__eq()*
  985. -----
  986. the `==` operation.
  987. The function `getcomphandler` defines how Lua chooses a metamethod for
  988. comparison operators. A metamethod only is selected when both objects being
  989. compared have the same type and the same metamethod for the selected
  990. operation.
  991. >lua
  992. function getcomphandler (op1, op2, event)
  993. if type(op1) ~= type(op2) then return nil end
  994. local mm1 = metatable(op1)[event]
  995. local mm2 = metatable(op2)[event]
  996. if mm1 == mm2 then return mm1 else return nil end
  997. end
  998. <
  999. The "eq" event is defined as follows:
  1000. >lua
  1001. function eq_event (op1, op2)
  1002. if type(op1) ~= type(op2) then -- different types?
  1003. return false -- different objects
  1004. end
  1005. if op1 == op2 then -- primitive equal?
  1006. return true -- objects are equal
  1007. end
  1008. -- try metamethod
  1009. local h = getcomphandler(op1, op2, "__eq")
  1010. if h then
  1011. return h(op1, op2)
  1012. else
  1013. return false
  1014. end
  1015. end
  1016. <
  1017. `a ~= b` is equivalent to `not (a == b)`.
  1018. "lt": *__lt()*
  1019. -----
  1020. the `<` operation.
  1021. >lua
  1022. function lt_event (op1, op2)
  1023. if type(op1) == "number" and type(op2) == "number" then
  1024. return op1 < op2 -- numeric comparison
  1025. elseif type(op1) == "string" and type(op2) == "string" then
  1026. return op1 < op2 -- lexicographic comparison
  1027. else
  1028. local h = getcomphandler(op1, op2, "__lt")
  1029. if h then
  1030. return h(op1, op2)
  1031. else
  1032. error(...);
  1033. end
  1034. end
  1035. end
  1036. <
  1037. `a > b` is equivalent to `b < a`.
  1038. "le": *__le()*
  1039. -----
  1040. the `<=` operation.
  1041. >lua
  1042. function le_event (op1, op2)
  1043. if type(op1) == "number" and type(op2) == "number" then
  1044. return op1 <= op2 -- numeric comparison
  1045. elseif type(op1) == "string" and type(op2) == "string" then
  1046. return op1 <= op2 -- lexicographic comparison
  1047. else
  1048. local h = getcomphandler(op1, op2, "__le")
  1049. if h then
  1050. return h(op1, op2)
  1051. else
  1052. h = getcomphandler(op1, op2, "__lt")
  1053. if h then
  1054. return not h(op2, op1)
  1055. else
  1056. error(...);
  1057. end
  1058. end
  1059. end
  1060. end
  1061. <
  1062. `a >= b` is equivalent to `b <= a`. Note that, in the absence of a "le"
  1063. metamethod, Lua tries the "lt", assuming that `a <= b` is equivalent
  1064. to `not (b < a)`.
  1065. "index": *__index()*
  1066. --------
  1067. The indexing access `table[key]`.
  1068. >lua
  1069. function gettable_event (table, key)
  1070. local h
  1071. if type(table) == "table" then
  1072. local v = rawget(table, key)
  1073. if v ~= nil then return v end
  1074. h = metatable(table).__index
  1075. if h == nil then return nil end
  1076. else
  1077. h = metatable(table).__index
  1078. if h == nil then
  1079. error(...);
  1080. end
  1081. end
  1082. if type(h) == "function" then
  1083. return h(table, key) -- call the handler
  1084. else return h[key] -- or repeat operation on it
  1085. end
  1086. <
  1087. "newindex": *__newindex()*
  1088. -----------
  1089. The indexing assignment `table[key] = value`.
  1090. >lua
  1091. function settable_event (table, key, value)
  1092. local h
  1093. if type(table) == "table" then
  1094. local v = rawget(table, key)
  1095. if v ~= nil then rawset(table, key, value); return end
  1096. h = metatable(table).__newindex
  1097. if h == nil then rawset(table, key, value); return end
  1098. else
  1099. h = metatable(table).__newindex
  1100. if h == nil then
  1101. error(...);
  1102. end
  1103. end
  1104. if type(h) == "function" then
  1105. return h(table, key,value) -- call the handler
  1106. else h[key] = value -- or repeat operation on it
  1107. end
  1108. <
  1109. "call": *__call()*
  1110. -------
  1111. called when Lua calls a value.
  1112. >lua
  1113. function function_event (func, ...)
  1114. if type(func) == "function" then
  1115. return func(...) -- primitive call
  1116. else
  1117. local h = metatable(func).__call
  1118. if h then
  1119. return h(func, ...)
  1120. else
  1121. error(...)
  1122. end
  1123. end
  1124. end
  1125. <
  1126. ==============================================================================
  1127. 2.9 Environments *lua-environments*
  1128. Besides metatables, objects of types thread, function, and userdata have
  1129. another table associated with them, called their environment. Like metatables,
  1130. environments are regular tables and multiple objects can share the same
  1131. environment.
  1132. Environments associated with userdata have no meaning for Lua. It is only a
  1133. convenience feature for programmers to associate a table to a userdata.
  1134. Environments associated with threads are called global environments. They are
  1135. used as the default environment for their threads and non-nested functions
  1136. created by the thread (through |loadfile()|, |loadstring()| or |load()|) and
  1137. can be directly accessed by C code (see |lua-pseudoindex|).
  1138. Environments associated with C functions can be directly accessed by C code
  1139. (see |lua-pseudoindex|). They are used as the default environment for
  1140. other C functions created by the function.
  1141. Environments associated with Lua functions are used to resolve all accesses to
  1142. global variables within the function (see |lua-variables|). They are
  1143. used as the default environment for other Lua functions created by the
  1144. function.
  1145. You can change the environment of a Lua function or the running thread by
  1146. calling `setfenv`. You can get the environment of a Lua function or the
  1147. running thread by calling `getfenv` (see |lua_getfenv()|). To manipulate the
  1148. environment of other objects (userdata, C functions, other threads) you must
  1149. use the C API.
  1150. ==============================================================================
  1151. 2.10 Garbage Collection *lua-gc*
  1152. Lua performs automatic memory management. This means that you do not have to
  1153. worry neither about allocating memory for new objects nor about freeing it
  1154. when the objects are no longer needed. Lua manages memory automatically by
  1155. running a garbage collector from time to time to collect all dead objects
  1156. (that is, these objects that are no longer accessible from Lua). All objects
  1157. in Lua are subject to automatic management: tables, userdata, functions,
  1158. threads, and strings.
  1159. Lua implements an incremental mark-and-sweep collector. It uses two numbers to
  1160. control its garbage-collection cycles: the garbage-collector pause and the
  1161. garbage-collector step multiplier.
  1162. The garbage-collector pause controls how long the collector waits before
  1163. starting a new cycle. Larger values make the collector less aggressive. Values
  1164. smaller than 1 mean the collector will not wait to start a new cycle. A value
  1165. of 2 means that the collector waits for the total memory in use to double
  1166. before starting a new cycle.
  1167. The step multiplier controls the relative speed of the collector relative to
  1168. memory allocation. Larger values make the collector more aggressive but also
  1169. increase the size of each incremental step. Values smaller than 1 make the
  1170. collector too slow and may result in the collector never finishing a cycle.
  1171. The default, 2, means that the collector runs at "twice" the speed of memory
  1172. allocation.
  1173. You can change these numbers by calling `lua_gc` (see |lua_gc()|) in C or
  1174. `collectgarbage` (see |collectgarbage()|) in Lua. Both get percentage points
  1175. as arguments (so an argument of 100 means a real value of 1). With these
  1176. functions you can also control the collector directly (e.g., stop and restart
  1177. it).
  1178. ------------------------------------------------------------------------------
  1179. 2.10.1 Garbage-Collection Metamethods *lua-gc-meta*
  1180. Using the C API, you can set garbage-collector metamethods for userdata (see
  1181. |lua-metatable|). These metamethods are also called finalizers.
  1182. Finalizers allow you to coordinate Lua's garbage collection with external
  1183. resource management (such as closing files, network or database connections,
  1184. or freeing your own memory).
  1185. *__gc*
  1186. Garbage userdata with a field `__gc` in their metatables are not collected
  1187. immediately by the garbage collector. Instead, Lua puts them in a list. After
  1188. the collection, Lua does the equivalent of the following function for each
  1189. userdata in that list:
  1190. >lua
  1191. function gc_event (udata)
  1192. local h = metatable(udata).__gc
  1193. if h then
  1194. h(udata)
  1195. end
  1196. end
  1197. <
  1198. At the end of each garbage-collection cycle, the finalizers for userdata are
  1199. called in reverse order of their creation, among these collected in that
  1200. cycle. That is, the first finalizer to be called is the one associated with
  1201. the userdata created last in the program.
  1202. ------------------------------------------------------------------------------
  1203. 2.10.2 - Weak Tables *lua-weaktable*
  1204. A weak table is a table whose elements are weak references. A weak reference
  1205. is ignored by the garbage collector. In other words, if the only references to
  1206. an object are weak references, then the garbage collector will collect this
  1207. object.
  1208. *__mode*
  1209. A weak table can have weak keys, weak values, or both. A table with weak keys
  1210. allows the collection of its keys, but prevents the collection of its values.
  1211. A table with both weak keys and weak values allows the collection of both keys
  1212. and values. In any case, if either the key or the value is collected, the
  1213. whole pair is removed from the table. The weakness of a table is controlled by
  1214. the value of the `__mode` field of its metatable. If the `__mode` field is a
  1215. string containing the character `k`, the keys in the table are weak.
  1216. If `__mode` contains `v`, the values in the table are weak.
  1217. After you use a table as a metatable, you should not change the value of its
  1218. field `__mode`. Otherwise, the weak behavior of the tables controlled by this
  1219. metatable is undefined.
  1220. ==============================================================================
  1221. 2.11 Coroutines *lua-coroutine*
  1222. Lua supports coroutines, also called collaborative multithreading. A coroutine
  1223. in Lua represents an independent thread of execution. Unlike threads in
  1224. multithread systems, however, a coroutine only suspends its execution by
  1225. explicitly calling a yield function.
  1226. You create a coroutine with a call to `coroutine.create` (see
  1227. |coroutine.create()|). Its sole argument is a function that is the main
  1228. function of the coroutine. The `create` function only creates a new coroutine
  1229. and returns a handle to it (an object of type `thread`); it does not start the
  1230. coroutine execution.
  1231. When you first call `coroutine.resume` (see |coroutine.resume()|),
  1232. passing as its first argument the thread returned by `coroutine.create`, the
  1233. coroutine starts its execution, at the first line of its main function. Extra
  1234. arguments passed to `coroutine.resume` are passed on to the coroutine main
  1235. function. After the coroutine starts running, it runs until it terminates or
  1236. `yields`.
  1237. A coroutine can terminate its execution in two ways: normally, when its main
  1238. function returns (explicitly or implicitly, after the last instruction); and
  1239. abnormally, if there is an unprotected error. In the first case,
  1240. `coroutine.resume` returns `true`, plus any values returned by the coroutine
  1241. main function. In case of errors, `coroutine.resume` returns `false` plus an
  1242. error message.
  1243. A coroutine yields by calling `coroutine.yield` (see
  1244. |coroutine.yield()|). When a coroutine yields, the corresponding
  1245. `coroutine.resume` returns immediately, even if the yield happens inside
  1246. nested function calls (that is, not in the main function, but in a function
  1247. directly or indirectly called by the main function). In the case of a yield,
  1248. `coroutine.resume` also returns `true`, plus any values passed to
  1249. `coroutine.yield`. The next time you resume the same coroutine, it continues
  1250. its execution from the point where it yielded, with the call to
  1251. `coroutine.yield` returning any extra arguments passed to `coroutine.resume`.
  1252. Like `coroutine.create`, the `coroutine.wrap` function (see
  1253. |coroutine.wrap()|) also creates a coroutine, but instead of returning
  1254. the coroutine itself, it returns a function that, when called, resumes the
  1255. coroutine. Any arguments passed to this function go as extra arguments to
  1256. `coroutine.resume`. `coroutine.wrap` returns all the values returned by
  1257. `coroutine.resume`, except the first one (the boolean error code). Unlike
  1258. `coroutine.resume`, `coroutine.wrap` does not catch errors; any error is
  1259. propagated to the caller.
  1260. As an example, consider the next code:
  1261. >lua
  1262. function foo1 (a)
  1263. print("foo", a)
  1264. return coroutine.yield(2*a)
  1265. end
  1266. co = coroutine.create(function (a,b)
  1267. print("co-body", a, b)
  1268. local r = foo1(a+1)
  1269. print("co-body", r)
  1270. local r, s = coroutine.yield(a+b, a-b)
  1271. print("co-body", r, s)
  1272. return b, "end"
  1273. end)
  1274. print("main", coroutine.resume(co, 1, 10))
  1275. print("main", coroutine.resume(co, "r"))
  1276. print("main", coroutine.resume(co, "x", "y"))
  1277. print("main", coroutine.resume(co, "x", "y"))
  1278. <
  1279. When you run it, it produces the following output:
  1280. >
  1281. co-body 1 10
  1282. foo 2
  1283. main true 4
  1284. co-body r
  1285. main true 11 -9
  1286. co-body x y
  1287. main true 10 end
  1288. main false cannot resume dead coroutine
  1289. <
  1290. ==============================================================================
  1291. 3 THE APPLICATION PROGRAM INTERFACE *lua-API*
  1292. This section describes the C API for Lua, that is, the set of C functions
  1293. available to the host program to communicate with Lua. All API functions and
  1294. related types and constants are declared in the header file `lua.h`.
  1295. Even when we use the term "function", any facility in the API may be provided
  1296. as a `macro` instead. All such macros use each of its arguments exactly once
  1297. (except for the first argument, which is always a Lua state), and so do not
  1298. generate hidden side-effects.
  1299. As in most C libraries, the Lua API functions do not check their arguments for
  1300. validity or consistency. However, you can change this behavior by compiling
  1301. Lua with a proper definition for the macro `luai_apicheck`,in file
  1302. `luaconf.h`.
  1303. ==============================================================================
  1304. 3.1 The Stack *lua-stack* *lua-apiStack*
  1305. Lua uses a virtual stack to pass values to and from C. Each element in this
  1306. stack represents a Lua value (`nil`, number, string, etc.).
  1307. Whenever Lua calls C, the called function gets a new stack, which is
  1308. independent of previous stacks and of stacks of C functions that are still
  1309. active. This stack initially contains any arguments to the C function and it
  1310. is where the C function pushes its results to be returned to the caller (see
  1311. |lua_CFunction|).
  1312. *lua-stackindex*
  1313. For convenience, most query operations in the API do not follow a strict stack
  1314. discipline. Instead, they can refer to any element in the stack by using an
  1315. index: a positive index represents an absolute stack position (starting at 1);
  1316. a negative index represents an offset from the top of the stack. More
  1317. specifically, if the stack has `n` elements, then index 1 represents the first
  1318. element (that is, the element that was pushed onto the stack first) and index
  1319. `n` represents the last element; index `-1` also represents the last element
  1320. (that is, the element at the top) and index `-n` represents the first element.
  1321. We say that an index is valid if it lies between 1 and the stack top (that is,
  1322. if `1 <= abs(index) <= top`).
  1323. ==============================================================================
  1324. 3.2 Stack Size *lua-apiStackSize*
  1325. When you interact with Lua API, you are responsible for ensuring consistency.
  1326. In particular, you are responsible for controlling stack overflow. You can
  1327. use the function `lua_checkstack` to grow the stack size (see
  1328. |lua_checkstack()|).
  1329. Whenever Lua calls C, it ensures that at least `LUA_MINSTACK` stack positions
  1330. are available. `LUA_MINSTACK` is defined as 20, so that usually you do not
  1331. have to worry about stack space unless your code has loops pushing elements
  1332. onto the stack.
  1333. Most query functions accept as indices any value inside the available stack
  1334. space, that is, indices up to the maximum stack size you have set through
  1335. `lua_checkstack`. Such indices are called acceptable indices. More formally,
  1336. we define an acceptable index as follows:
  1337. >lua
  1338. (index < 0 && abs(index) <= top) || (index > 0 && index <= stackspace)
  1339. <
  1340. Note that 0 is never an acceptable index.
  1341. ==============================================================================
  1342. 3.3 Pseudo-Indices *lua-pseudoindex*
  1343. Unless otherwise noted, any function that accepts valid indices can also be
  1344. called with pseudo-indices, which represent some Lua values that are
  1345. accessible to the C code but which are not in the stack. Pseudo-indices are
  1346. used to access the thread environment, the function environment, the registry,
  1347. and the upvalues of a C function (see |lua-cclosure|).
  1348. The thread environment (where global variables live) is always at pseudo-index
  1349. `LUA_GLOBALSINDEX`. The environment of the running C function is always at
  1350. pseudo-index `LUA_ENVIRONINDEX`.
  1351. To access and change the value of global variables, you can use regular table
  1352. operations over an environment table. For instance, to access the value of a
  1353. global variable, do
  1354. >c
  1355. lua_getfield(L, LUA_GLOBALSINDEX, varname);
  1356. <
  1357. ==============================================================================
  1358. 3.4 C Closures *lua-cclosure*
  1359. When a C function is created, it is possible to associate some values with it,
  1360. thus creating a C closure; these values are called upvalues and are accessible
  1361. to the function whenever it is called (see |lua_pushcclosure()|).
  1362. Whenever a C function is called, its upvalues are located at specific
  1363. pseudo-indices. These pseudo-indices are produced by the macro
  1364. `lua_upvalueindex`. The first value associated with a function is at position
  1365. `lua_upvalueindex(1)`, and so on. Any access to `lua_upvalueindex(` `n` `)`,
  1366. where `n` is greater than the number of upvalues of the current function,
  1367. produces an acceptable (but invalid) index.
  1368. ==============================================================================
  1369. 3.5 Registry *lua-registry*
  1370. Lua provides a registry, a pre-defined table that can be used by any C code to
  1371. store whatever Lua value it needs to store. This table is always located at
  1372. pseudo-index `LUA_REGISTRYINDEX`. Any C library can store data into this
  1373. table, but it should take care to choose keys different from those used by
  1374. other libraries, to avoid collisions. Typically, you should use as key a
  1375. string containing your library name or a light userdata with the address of a
  1376. C object in your code.
  1377. The integer keys in the registry are used by the reference mechanism,
  1378. implemented by the auxiliary library, and therefore should not be used for
  1379. other purposes.
  1380. ==============================================================================
  1381. 3.6 Error Handling in C *lua-apiError*
  1382. Internally, Lua uses the C `longjmp` facility to handle errors. (You can also
  1383. choose to use exceptions if you use C++; see file `luaconf.h`.) When Lua faces
  1384. any error (such as memory allocation errors, type errors, syntax errors, and
  1385. runtime errors) it raises an error; that is, it does a long jump. A protected
  1386. environment uses `setjmp` to set a recover point; any error jumps to the most
  1387. recent active recover point.
  1388. Almost any function in the API may raise an error, for instance due to a
  1389. memory allocation error. The following functions run in protected mode (that
  1390. is, they create a protected environment to run), so they never raise an error:
  1391. `lua_newstate`, `lua_close`, `lua_load`, `lua_pcall`, and `lua_cpcall` (see
  1392. |lua_newstate()|, |lua_close()|, |lua_load()|,
  1393. |lua_pcall()|, and |lua_cpcall()|).
  1394. Inside a C function you can raise an error by calling `lua_error` (see
  1395. |lua_error()|).
  1396. ==============================================================================
  1397. 3.7 Functions and Types *lua-apiFunctions*
  1398. Here we list all functions and types from the C API in alphabetical order.
  1399. lua_Alloc *lua_Alloc*
  1400. >c
  1401. typedef void * (*lua_Alloc) (void *ud,
  1402. void *ptr,
  1403. size_t osize,
  1404. size_t nsize);
  1405. <
  1406. The type of the memory-allocation function used by Lua states. The
  1407. allocator function must provide a functionality similar to `realloc`,
  1408. but not exactly the same. Its arguments are `ud`, an opaque pointer
  1409. passed to `lua_newstate` (see |lua_newstate()|); `ptr`, a pointer
  1410. to the block being allocated/reallocated/freed; `osize`, the original
  1411. size of the block; `nsize`, the new size of the block. `ptr` is `NULL`
  1412. if and only if `osize` is zero. When `nsize` is zero, the allocator
  1413. must return `NULL`; if `osize` is not zero, it should free the block
  1414. pointed to by `ptr`. When `nsize` is not zero, the allocator returns
  1415. `NULL` if and only if it cannot fill the request. When `nsize` is not
  1416. zero and `osize` is zero, the allocator should behave like `malloc`.
  1417. When `nsize` and `osize` are not zero, the allocator behaves like
  1418. `realloc`. Lua assumes that the allocator never fails when `osize >=
  1419. nsize`.
  1420. Here is a simple implementation for the allocator function. It is used
  1421. in the auxiliary library by `luaL_newstate` (see
  1422. |luaL_newstate()|).
  1423. >c
  1424. static void *l_alloc (void *ud, void *ptr, size_t osize,
  1425. size_t nsize) {
  1426. (void)ud; (void)osize; /* not used */
  1427. if (nsize == 0) {
  1428. free(ptr);
  1429. return NULL;
  1430. }
  1431. else
  1432. return realloc(ptr, nsize);
  1433. }
  1434. <
  1435. This code assumes that `free(NULL)` has no effect and that
  1436. `realloc(NULL, size)` is equivalent to `malloc(size)`. ANSI C ensures both
  1437. behaviors.
  1438. lua_atpanic *lua_atpanic()*
  1439. >c
  1440. lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);
  1441. <
  1442. Sets a new panic function and returns the old one.
  1443. If an error happens outside any protected environment, Lua calls a
  1444. `panic` `function` and then calls `exit(EXIT_FAILURE)`, thus exiting
  1445. the host application. Your panic function may avoid this exit by never
  1446. returning (e.g., doing a long jump).
  1447. The panic function can access the error message at the top of the
  1448. stack.
  1449. lua_call *lua_call()*
  1450. >c
  1451. void lua_call (lua_State *L, int nargs, int nresults);
  1452. <
  1453. Calls a function.
  1454. To call a function you must use the following protocol: first, the
  1455. function to be called is pushed onto the stack; then, the arguments to
  1456. the function are pushed in direct order; that is, the first argument
  1457. is pushed first. Finally you call `lua_call`; `nargs` is the number of
  1458. arguments that you pushed onto the stack. All arguments and the
  1459. function value are popped from the stack when the function is called.
  1460. The function results are pushed onto the stack when the function
  1461. returns. The number of results is adjusted to `nresults`, unless
  1462. `nresults` is `LUA_MULTRET`. In this case, `all` results from the
  1463. function are pushed. Lua takes care that the returned values fit into
  1464. the stack space. The function results are pushed onto the stack in
  1465. direct order (the first result is pushed first), so that after the
  1466. call the last result is on the top of the stack.
  1467. Any error inside the called function is propagated upwards (with a
  1468. `longjmp`).
  1469. The following example shows how the host program may do the equivalent
  1470. to this Lua code:
  1471. >lua
  1472. a = f("how", t.x, 14)
  1473. <
  1474. Here it is in C:
  1475. >c
  1476. lua_getfield(L, LUA_GLOBALSINDEX, "f"); // function to be called
  1477. lua_pushstring(L, "how"); // 1st argument
  1478. lua_getfield(L, LUA_GLOBALSINDEX, "t"); // table to be indexed
  1479. lua_getfield(L, -1, "x"); // push result of t.x (2nd arg)
  1480. lua_remove(L, -2); // remove 't' from the stack
  1481. lua_pushinteger(L, 14); // 3rd argument
  1482. lua_call(L, 3, 1); // call 'f' with 3 arguments and 1 result
  1483. lua_setfield(L, LUA_GLOBALSINDEX, "a"); // set global 'a'
  1484. <
  1485. Note that the code above is "balanced": at its end, the stack is back
  1486. to its original configuration. This is considered good programming
  1487. practice.
  1488. lua_CFunction *lua-cfunction* *lua_CFunction*
  1489. >c
  1490. typedef int (*lua_CFunction) (lua_State *L);
  1491. <
  1492. Type for C functions.
  1493. In order to communicate properly with Lua, a C function must use the
  1494. following protocol, which defines the way parameters and results are
  1495. passed: a C function receives its arguments from Lua in its stack in
  1496. direct order (the first argument is pushed first). So, when the
  1497. function starts, `lua_gettop(L)` (see |lua_gettop()|) returns the
  1498. number of arguments received by the function. The first argument (if
  1499. any) is at index 1 and its last argument is at index `lua_gettop(L)`.
  1500. To return values to Lua, a C function just pushes them onto the stack,
  1501. in direct order (the first result is pushed first), and returns the
  1502. number of results. Any other value in the stack below the results will
  1503. be properly discarded by Lua. Like a Lua function, a C function called
  1504. by Lua can also return many results.
  1505. *lua-cfunctionexample*
  1506. As an example, the following function receives a variable number of
  1507. numerical arguments and returns their average and sum:
  1508. >c
  1509. static int foo (lua_State *L) {
  1510. int n = lua_gettop(L); /* number of arguments */
  1511. lua_Number sum = 0;
  1512. int i;
  1513. for (i = 1; i &lt;= n; i++) {
  1514. if (!lua_isnumber(L, i)) {
  1515. lua_pushstring(L, "incorrect argument");
  1516. lua_error(L);
  1517. }
  1518. sum += lua_tonumber(L, i);
  1519. }
  1520. lua_pushnumber(L, sum/n); /* first result */
  1521. lua_pushnumber(L, sum); /* second result */
  1522. return 2; /* number of results */
  1523. }
  1524. <
  1525. lua_checkstack *lua_checkstack()*
  1526. >c
  1527. int lua_checkstack (lua_State *L, int extra);
  1528. <
  1529. Ensures that there are at least `extra` free stack slots in the stack.
  1530. It returns false if it cannot grow the stack to that size. This
  1531. function never shrinks the stack; if the stack is already larger than
  1532. the new size, it is left unchanged.
  1533. lua_close *lua_close()*
  1534. >c
  1535. void lua_close (lua_State *L);
  1536. <
  1537. Destroys all objects in the given Lua state (calling the corresponding
  1538. garbage-collection metamethods, if any) and frees all dynamic memory
  1539. used by this state. On several platforms, you may not need to call
  1540. this function, because all resources are naturally released when the
  1541. host program ends. On the other hand, long-running programs, such as a
  1542. daemon or a web server, might need to release states as soon as they
  1543. are not needed, to avoid growing too large.
  1544. lua_concat *lua_concat()*
  1545. >c
  1546. void lua_concat (lua_State *L, int n);
  1547. <
  1548. Concatenates the `n` values at the top of the stack, pops them, and
  1549. leaves the result at the top. If `n` is 1, the result is the single
  1550. string on the stack (that is, the function does nothing); if `n` is 0,
  1551. the result is the empty string. Concatenation is done following the
  1552. usual semantics of Lua (see |lua-concat|).
  1553. lua_cpcall *lua_cpcall()*
  1554. >c
  1555. int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);
  1556. <
  1557. Calls the C function `func` in protected mode. `func` starts with only
  1558. one element in its stack, a light userdata containing `ud`. In case of
  1559. errors, `lua_cpcall` returns the same error codes as `lua_pcall` (see
  1560. |lua_pcall()|), plus the error object on the top of the stack;
  1561. otherwise, it returns zero, and does not change the stack. All values
  1562. returned by `func` are discarded.
  1563. lua_createtable *lua_createtable()*
  1564. >c
  1565. void lua_createtable (lua_State *L, int narr, int nrec);
  1566. <
  1567. Creates a new empty table and pushes it onto the stack. The new table
  1568. has space pre-allocated for `narr` array elements and `nrec` non-array
  1569. elements. This pre-allocation is useful when you know exactly how many
  1570. elements the table will have. Otherwise you can use the function
  1571. `lua_newtable` (see |lua_newtable()|).
  1572. lua_dump *lua_dump()*
  1573. >c
  1574. int lua_dump (lua_State *L, lua_Writer writer, void *data);
  1575. <
  1576. Dumps a function as a binary chunk. Receives a Lua function on the top
  1577. of the stack and produces a binary chunk that, if loaded again,
  1578. results in a function equivalent to the one dumped. As it produces
  1579. parts of the chunk, `lua_dump` calls function `writer` (see
  1580. |lua_Writer|) with the given `data` to write them.
  1581. The value returned is the error code returned by the last call to the
  1582. writer; 0 means no errors.
  1583. This function does not pop the Lua function from the stack.
  1584. lua_equal *lua_equal()*
  1585. >c
  1586. int lua_equal (lua_State *L, int index1, int index2);
  1587. <
  1588. Returns 1 if the two values in acceptable indices `index1` and
  1589. `index2` are equal, following the semantics of the Lua `==` operator
  1590. (that is, may call metamethods). Otherwise returns 0. Also returns 0
  1591. if any of the indices is non valid.
  1592. lua_error *lua_error()*
  1593. >c
  1594. int lua_error (lua_State *L);
  1595. <
  1596. Generates a Lua error. The error message (which can actually be a Lua
  1597. value of any type) must be on the stack top. This function does a long
  1598. jump, and therefore never returns (see |luaL_error()|).
  1599. lua_gc *lua_gc()*
  1600. >c
  1601. int lua_gc (lua_State *L, int what, int data);
  1602. <
  1603. Controls the garbage collector.
  1604. This function performs several tasks, according to the value of the
  1605. parameter `what`:
  1606. - `LUA_GCSTOP` stops the garbage collector.
  1607. - `LUA_GCRESTART` restarts the garbage collector.
  1608. - `LUA_GCCOLLECT` performs a full garbage-collection cycle.
  1609. - `LUA_GCCOUNT` returns the current amount of memory (in Kbytes) in
  1610. use by Lua.
  1611. - `LUA_GCCOUNTB` returns the remainder of dividing the current
  1612. amount of bytes of memory in use by Lua by 1024.
  1613. - `LUA_GCSTEP` performs an incremental step of garbage collection.
  1614. The step "size" is controlled by `data` (larger
  1615. values mean more steps) in a non-specified way. If
  1616. you want to control the step size you must
  1617. experimentally tune the value of `data`. The
  1618. function returns 1 if the step finished a
  1619. garbage-collection cycle.
  1620. - `LUA_GCSETPAUSE` sets `data` /100 as the new value for the
  1621. `pause` of the collector (see |lua-gc|).
  1622. The function returns the previous value of the
  1623. pause.
  1624. - `LUA_GCSETSTEPMUL`sets `data` /100 as the new value for the
  1625. `step` `multiplier` of the collector (see
  1626. |lua-gc|). The function returns the
  1627. previous value of the step multiplier.
  1628. lua_getallocf *lua_getallocf()*
  1629. >c
  1630. lua_Alloc lua_getallocf (lua_State *L, void **ud);
  1631. <
  1632. Returns the memory-allocation function of a given state. If `ud` is
  1633. not `NULL`, Lua stores in `*ud` the opaque pointer passed to
  1634. `lua_newstate` (see |lua_newstate()|).
  1635. lua_getfenv *lua_getfenv()*
  1636. >c
  1637. void lua_getfenv (lua_State *L, int index);
  1638. <
  1639. Pushes onto the stack the environment table of the value at the given
  1640. index.
  1641. lua_getfield *lua_getfield()*
  1642. >c
  1643. void lua_getfield (lua_State *L, int index, const char *k);
  1644. <
  1645. Pushes onto the stack the value `t[k]`, where `t` is the value at the
  1646. given valid index `index`. As in Lua, this function may trigger a
  1647. metamethod for the "index" event (see |lua-metatable|).
  1648. lua_getglobal *lua_getglobal()*
  1649. >c
  1650. void lua_getglobal (lua_State *L, const char *name);
  1651. <
  1652. Pushes onto the stack the value of the global `name`. It is defined as
  1653. a macro:
  1654. >c
  1655. #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s)
  1656. <
  1657. lua_getmetatable *lua_getmetatable()*
  1658. >c
  1659. int lua_getmetatable (lua_State *L, int index);
  1660. <
  1661. Pushes onto the stack the metatable of the value at the given
  1662. acceptable index. If the index is not valid, or if the value does not
  1663. have a metatable, the function returns 0 and pushes nothing on the
  1664. stack.
  1665. lua_gettable *lua_gettable()*
  1666. >c
  1667. void lua_gettable (lua_State *L, int index);
  1668. <
  1669. Pushes onto the stack the value `t[k]`, where `t` is the value at the
  1670. given valid index `index` and `k` is the value at the top of the
  1671. stack.
  1672. This function pops the key from the stack (putting the resulting value
  1673. in its place). As in Lua, this function may trigger a metamethod for
  1674. the "index" event (see |lua-metatable|).
  1675. lua_gettop *lua_gettop()*
  1676. >c
  1677. int lua_gettop (lua_State *L);
  1678. <
  1679. Returns the index of the top element in the stack. Because indices
  1680. start at 1, this result is equal to the number of elements in the
  1681. stack (and so
  1682. 0 means an empty stack).
  1683. lua_insert *lua_insert()*
  1684. >c
  1685. void lua_insert (lua_State *L, int index);
  1686. <
  1687. Moves the top element into the given valid index, shifting up the
  1688. elements above this index to open space. Cannot be called with a
  1689. pseudo-index, because a pseudo-index is not an actual stack position.
  1690. lua_Integer *lua_Integer*
  1691. >c
  1692. typedef ptrdiff_t lua_Integer;
  1693. <
  1694. The type used by the Lua API to represent integral values.
  1695. By default it is a `ptrdiff_t`, which is usually the largest integral
  1696. type the machine handles "comfortably".
  1697. lua_isboolean *lua_isboolean()*
  1698. >c
  1699. int lua_isboolean (lua_State *L, int index);
  1700. <
  1701. Returns 1 if the value at the given acceptable index has type boolean,
  1702. and 0 otherwise.
  1703. lua_iscfunction *lua_iscfunction()*
  1704. >c
  1705. int lua_iscfunction (lua_State *L, int index);
  1706. <
  1707. Returns 1 if the value at the given acceptable index is a C function,
  1708. and 0 otherwise.
  1709. lua_isfunction *lua_isfunction()*
  1710. >c
  1711. int lua_isfunction (lua_State *L, int index);
  1712. <
  1713. Returns 1 if the value at the given acceptable index is a function
  1714. (either C or Lua), and 0 otherwise.
  1715. lua_islightuserdata *lua_islightuserdata()*
  1716. >c
  1717. int lua_islightuserdata (lua_State *L, int index);
  1718. <
  1719. Returns 1 if the value at the given acceptable index is a light
  1720. userdata, and 0 otherwise.
  1721. lua_isnil *lua_isnil()*
  1722. >c
  1723. int lua_isnil (lua_State *L, int index);
  1724. <
  1725. Returns 1 if the value at the given acceptable index is `nil`, and 0
  1726. otherwise.
  1727. lua_isnumber *lua_isnumber()*
  1728. >c
  1729. int lua_isnumber (lua_State *L, int index);
  1730. <
  1731. Returns 1 if the value at the given acceptable index is a number or a
  1732. string convertible to a number, and 0 otherwise.
  1733. lua_isstring *lua_isstring()*
  1734. >c
  1735. int lua_isstring (lua_State *L, int index);
  1736. <
  1737. Returns 1 if the value at the given acceptable index is a string or a
  1738. number (which is always convertible to a string), and 0 otherwise.
  1739. lua_istable *lua_istable()*
  1740. >c
  1741. int lua_istable (lua_State *L, int index);
  1742. <
  1743. Returns 1 if the value at the given acceptable index is a table, and
  1744. 0 otherwise.
  1745. lua_isthread *lua_isthread()*
  1746. >c
  1747. int lua_isthread (lua_State *L, int index);
  1748. <
  1749. Returns 1 if the value at the given acceptable index is a thread, and
  1750. 0 otherwise.
  1751. lua_isuserdata *lua_isuserdata()*
  1752. >c
  1753. int lua_isuserdata (lua_State *L, int index);
  1754. <
  1755. Returns 1 if the value at the given acceptable index is a userdata
  1756. (either full or light), and 0 otherwise.
  1757. lua_lessthan *lua_lessthan()*
  1758. >c
  1759. int lua_lessthan (lua_State *L, int index1, int index2);
  1760. <
  1761. Returns 1 if the value at acceptable index `index1` is smaller than
  1762. the value at acceptable index `index2`, following the semantics of the
  1763. Lua `<` operator (that is, may call metamethods). Otherwise returns 0.
  1764. Also returns 0 if any of the indices is non valid.
  1765. lua_load *lua_load()*
  1766. >c
  1767. int lua_load (lua_State *L,
  1768. lua_Reader reader,
  1769. void *data,
  1770. const char *chunkname);
  1771. <
  1772. Loads a Lua chunk. If there are no errors, `lua_load` pushes the
  1773. compiled chunk as a Lua function on top of the stack. Otherwise, it
  1774. pushes an error message. The return values of `lua_load` are:
  1775. - `0`: no errors;
  1776. - `LUA_ERRSYNTAX` : syntax error during pre-compilation;
  1777. - `LUA_ERRMEM` : memory allocation error.
  1778. This function only loads a chunk; it does not run it.
  1779. `lua_load` automatically detects whether the chunk is text or binary,
  1780. and loads it accordingly (see program `luac`).
  1781. The `lua_load` function uses a user-supplied `reader` function to read
  1782. the chunk (see |lua_Reader|). The `data` argument is an opaque
  1783. value passed to the reader function.
  1784. The `chunkname` argument gives a name to the chunk, which is used for
  1785. error messages and in debug information (see |lua-apiDebug|).
  1786. lua_newstate *lua_newstate()*
  1787. >c
  1788. lua_State *lua_newstate (lua_Alloc f, void *ud);
  1789. <
  1790. Creates a new, independent state. Returns `NULL` if cannot create the
  1791. state (due to lack of memory). The argument `f` is the allocator
  1792. function; Lua does all memory allocation for this state through this
  1793. function. The second argument, `ud`, is an opaque pointer that Lua
  1794. simply passes to the allocator in every call.
  1795. lua_newtable *lua_newtable()*
  1796. >c
  1797. void lua_newtable (lua_State *L);
  1798. <
  1799. Creates a new empty table and pushes it onto the stack. It is
  1800. equivalent to `lua_createtable(L, 0, 0)` (see
  1801. |lua_createtable()|).
  1802. lua_newthread *lua_newthread()*
  1803. >c
  1804. lua_State *lua_newthread (lua_State *L);
  1805. <
  1806. Creates a new thread, pushes it on the stack, and returns a pointer to
  1807. a `lua_State` (see |lua_State|) that represents this new
  1808. thread. The new state returned by this function shares with the
  1809. original state all global objects (such as tables), but has an
  1810. independent execution stack.
  1811. There is no explicit function to close or to destroy a thread. Threads
  1812. are subject to garbage collection, like any Lua object.
  1813. lua_newuserdata *lua_newuserdata()*
  1814. >c
  1815. void *lua_newuserdata (lua_State *L, size_t size);
  1816. <
  1817. This function allocates a new block of memory with the given size,
  1818. pushes onto the stack a new full userdata with the block address, and
  1819. returns this address.
  1820. *userdata*
  1821. Userdata represents C values in Lua. A full userdata represents a
  1822. block of memory. It is an object (like a table): you must create it,
  1823. it can have its own metatable, and you can detect when it is being
  1824. collected. A full userdata is only equal to itself (under raw
  1825. equality).
  1826. When Lua collects a full userdata with a `gc` metamethod, Lua calls
  1827. the metamethod and marks the userdata as finalized. When this userdata
  1828. is collected again then Lua frees its corresponding memory.
  1829. lua_next *lua_next()*
  1830. >c
  1831. int lua_next (lua_State *L, int index);
  1832. <
  1833. Pops a key from the stack, and pushes a key-value pair from the table
  1834. at the given index (the "next" pair after the given key). If there are
  1835. no more elements in the table, then `lua_next` returns 0 (and pushes
  1836. nothing).
  1837. *lua-tabletraversal*
  1838. A typical traversal looks like this:
  1839. >c
  1840. /* table is in the stack at index 't' */
  1841. lua_pushnil(L); /* first key */
  1842. while (lua_next(L, t) != 0) {
  1843. /* uses 'key' (at index -2) and 'value' (at index -1) */
  1844. printf("%s - %s\n",
  1845. lua_typename(L, lua_type(L, -2)),
  1846. lua_typename(L, lua_type(L, -1)));
  1847. /* removes 'value'; keeps 'key' for next iteration */
  1848. lua_pop(L, 1);
  1849. }
  1850. <
  1851. While traversing a table, do not call `lua_tolstring` (see
  1852. |lua_tolstring()|) directly on a key, unless you know that the
  1853. key is actually a string. Recall that `lua_tolstring` `changes` the
  1854. value at the given index; this confuses the next call to `lua_next`.
  1855. lua_Number *lua_Number*
  1856. >c
  1857. typedef double lua_Number;
  1858. <
  1859. The type of numbers in Lua. By default, it is double, but that can be
  1860. changed in `luaconf.h`.
  1861. Through the configuration file you can change Lua to operate with
  1862. another type for numbers (e.g., float or long).
  1863. lua_objlen *lua_objlen()*
  1864. >c
  1865. size_t lua_objlen (lua_State *L, int index);
  1866. <
  1867. Returns the "length" of the value at the given acceptable index: for
  1868. strings, this is the string length; for tables, this is the result of
  1869. the length operator (`#`); for userdata, this is the size of the
  1870. block of memory allocated for the userdata; for other values, it is 0.
  1871. lua_pcall *lua_pcall()*
  1872. >c
  1873. lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);
  1874. <
  1875. Calls a function in protected mode.
  1876. Both `nargs` and `nresults` have the same meaning as in `lua_call`
  1877. (see |lua_call()|). If there are no errors during the call,
  1878. `lua_pcall` behaves exactly like `lua_call`. However, if there is any
  1879. error, `lua_pcall` catches it, pushes a single value on the stack (the
  1880. error message), and returns an error code. Like `lua_call`,
  1881. `lua_pcall` always removes the function and its arguments from the
  1882. stack.
  1883. If `errfunc` is 0, then the error message returned on the stack is
  1884. exactly the original error message. Otherwise, `errfunc` is the stack
  1885. index of an `error` `handler function`. (In the current
  1886. implementation, this index cannot be a pseudo-index.) In case of
  1887. runtime errors, this function will be called with the error message
  1888. and its return value will be the message returned on the stack by
  1889. `lua_pcall`.
  1890. Typically, the error handler function is used to add more debug
  1891. information to the error message, such as a stack traceback. Such
  1892. information cannot be gathered after the return of `lua_pcall`, since
  1893. by then the stack has unwound.
  1894. The `lua_pcall` function returns 0 in case of success or one of the
  1895. following error codes (defined in `lua.h`):
  1896. - `LUA_ERRRUN` a runtime error.
  1897. - `LUA_ERRMEM` memory allocation error. For such errors, Lua does
  1898. not call the error handler function.
  1899. - `LUA_ERRERR` error while running the error handler function.
  1900. lua_pop *lua_pop()*
  1901. >c
  1902. void lua_pop (lua_State *L, int n);
  1903. <
  1904. Pops `n` elements from the stack.
  1905. lua_pushboolean *lua_pushboolean()*
  1906. >c
  1907. void lua_pushboolean (lua_State *L, int b);
  1908. <
  1909. Pushes a boolean value with value `b` onto the stack.
  1910. lua_pushcclosure *lua_pushcclosure()*
  1911. >c
  1912. void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
  1913. <
  1914. Pushes a new C closure onto the stack.
  1915. When a C function is created, it is possible to associate some values
  1916. with it, thus creating a C closure (see |lua-cclosure|); these
  1917. values are then accessible to the function whenever it is called. To
  1918. associate values with a C function, first these values should be
  1919. pushed onto the stack (when there are multiple values, the first value
  1920. is pushed first). Then `lua_pushcclosure` is called to create and push
  1921. the C function onto the stack, with the argument `n` telling how many
  1922. values should be associated with the function. `lua_pushcclosure` also
  1923. pops these values from the stack.
  1924. lua_pushcfunction *lua_pushcfunction()*
  1925. >c
  1926. void lua_pushcfunction (lua_State *L, lua_CFunction f);
  1927. <
  1928. Pushes a C function onto the stack. This function receives a pointer
  1929. to a C function and pushes onto the stack a Lua value of type
  1930. `function` that, when called, invokes the corresponding C function.
  1931. Any function to be registered in Lua must follow the correct protocol
  1932. to receive its parameters and return its results (see
  1933. |lua_CFunction|).
  1934. `lua_pushcfunction` is defined as a macro:
  1935. >c
  1936. #define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0)
  1937. <
  1938. lua_pushfstring *lua_pushfstring()*
  1939. >c
  1940. const char *lua_pushfstring (lua_State *L, const char *fmt, ...);
  1941. <
  1942. Pushes onto the stack a formatted string and returns a pointer to this
  1943. string. It is similar to the C function `sprintf`, but has some
  1944. important differences:
  1945. - You do not have to allocate space for the result: the result is a
  1946. Lua string and Lua takes care of memory allocation (and
  1947. deallocation, through garbage collection).
  1948. - The conversion specifiers are quite restricted. There are no flags,
  1949. widths, or precisions. The conversion specifiers can only be `%%`
  1950. (inserts a `%` in the string), `%s` (inserts a zero-terminated
  1951. string, with no size restrictions), `%f` (inserts a
  1952. `lua_Number`), `%p` (inserts a pointer as a hexadecimal numeral),
  1953. `%d` (inserts an `int`), and `%c` (inserts an `int` as a
  1954. character).
  1955. lua_pushinteger *lua_pushinteger()*
  1956. >c
  1957. void lua_pushinteger (lua_State *L, lua_Integer n);
  1958. <
  1959. Pushes a number with value `n` onto the stack.
  1960. lua_pushlightuserdata *lua_pushlightuserdata()*
  1961. >c
  1962. void lua_pushlightuserdata (lua_State *L, void *p);
  1963. <
  1964. Pushes a light userdata onto the stack.
  1965. *lua-lightuserdata*
  1966. Userdata represents C values in Lua. A light userdata represents a
  1967. pointer. It is a value (like a number): you do not create it, it has
  1968. no individual metatable, and it is not collected (as it was never
  1969. created). A light userdata is equal to "any" light userdata with the
  1970. same C address.
  1971. lua_pushlstring *lua_pushlstring()*
  1972. >c
  1973. void lua_pushlstring (lua_State *L, const char *s, size_t len);
  1974. <
  1975. Pushes the string pointed to by `s` with size `len` onto the stack.
  1976. Lua makes (or reuses) an internal copy of the given string, so the
  1977. memory at `s` can be freed or reused immediately after the function
  1978. returns. The string can contain embedded zeros.
  1979. lua_pushnil *lua_pushnil()*
  1980. >c
  1981. void lua_pushnil (lua_State *L);
  1982. <
  1983. Pushes a nil value onto the stack.
  1984. lua_pushnumber *lua_pushnumber()*
  1985. >c
  1986. void lua_pushnumber (lua_State *L, lua_Number n);
  1987. <
  1988. Pushes a number with value `n` onto the stack.
  1989. lua_pushstring *lua_pushstring()*
  1990. >c
  1991. void lua_pushstring (lua_State *L, const char *s);
  1992. <
  1993. Pushes the zero-terminated string pointed to by `s` onto the stack.
  1994. Lua makes (or reuses) an internal copy of the given string, so the
  1995. memory at `s` can be freed or reused immediately after the function
  1996. returns. The string cannot contain embedded zeros; it is assumed to
  1997. end at the first zero.
  1998. lua_pushthread *lua_pushthread()*
  1999. >c
  2000. int lua_pushthread (lua_State *L);
  2001. <
  2002. Pushes the thread represented by `L` onto the stack. Returns 1 if this
  2003. thread is the main thread of its state.
  2004. lua_pushvalue *lua_pushvalue()*
  2005. >c
  2006. void lua_pushvalue (lua_State *L, int index);
  2007. <
  2008. Pushes a copy of the element at the given valid index onto the stack.
  2009. lua_pushvfstring *lua_pushvfstring()*
  2010. >c
  2011. const char *lua_pushvfstring (lua_State *L,
  2012. const char *fmt,
  2013. va_list argp);
  2014. <
  2015. Equivalent to `lua_pushfstring` (see |lua_pushfstring()|), except
  2016. that it receives a `va_list` instead of a variable number of
  2017. arguments.
  2018. lua_rawequal *lua_rawequal()*
  2019. >c
  2020. int lua_rawequal (lua_State *L, int index1, int index2);
  2021. <
  2022. Returns 1 if the two values in acceptable indices `index1` and
  2023. `index2` are primitively equal (that is, without calling metamethods).
  2024. Otherwise returns 0. Also returns 0 if any of the indices are non
  2025. valid.
  2026. lua_rawget *lua_rawget()*
  2027. >c
  2028. void lua_rawget (lua_State *L, int index);
  2029. <
  2030. Similar to `lua_gettable` (see |lua_gettable()|), but does a raw
  2031. access (i.e., without metamethods).
  2032. lua_rawgeti *lua_rawgeti()*
  2033. >c
  2034. void lua_rawgeti (lua_State *L, int index, int n);
  2035. <
  2036. Pushes onto the stack the value `t[n]`, where `t` is the value at the
  2037. given valid index `index`. The access is raw; that is, it does not
  2038. invoke metamethods.
  2039. lua_rawset *lua_rawset()*
  2040. >c
  2041. void lua_rawset (lua_State *L, int index);
  2042. <
  2043. Similar to `lua_settable` (see |lua_settable()|), but does a raw
  2044. assignment (i.e., without metamethods).
  2045. lua_rawseti *lua_rawseti()*
  2046. >c
  2047. void lua_rawseti (lua_State *L, int index, int n);
  2048. <
  2049. Does the equivalent of `t[n] = v`, where `t` is the value at the given
  2050. valid index `index` and `v` is the value at the top of the stack.
  2051. This function pops the value from the stack. The assignment is raw;
  2052. that is, it does not invoke metamethods.
  2053. lua_Reader *lua_Reader*
  2054. >c
  2055. typedef const char * (*lua_Reader) (lua_State *L,
  2056. void *data,
  2057. size_t *size);
  2058. <
  2059. The reader function used by `lua_load` (see |lua_load()|). Every
  2060. time it needs another piece of the chunk, `lua_load` calls the reader,
  2061. passing along its `data` parameter. The reader must return a pointer
  2062. to a block of memory with a new piece of the chunk and set `size` to
  2063. the block size. The block must exist until the reader function is
  2064. called again. To signal the end of the chunk, the reader must return
  2065. `NULL`. The reader function may return pieces of any size greater than
  2066. zero.
  2067. lua_register *lua_register()*
  2068. >c
  2069. void lua_register (lua_State *L,
  2070. const char *name,
  2071. lua_CFunction f);
  2072. <
  2073. Sets the C function `f` as the new value of global `name`. It is
  2074. defined as a macro:
  2075. >c
  2076. #define lua_register(L,n,f) \
  2077. (lua_pushcfunction(L, f), lua_setglobal(L, n))
  2078. <
  2079. lua_remove *lua_remove()*
  2080. >c
  2081. void lua_remove (lua_State *L, int index);
  2082. <
  2083. Removes the element at the given valid index, shifting down the
  2084. elements above this index to fill the gap. Cannot be called with a
  2085. pseudo-index, because a pseudo-index is not an actual stack position.
  2086. lua_replace *lua_replace()*
  2087. >c
  2088. void lua_replace (lua_State *L, int index);
  2089. <
  2090. Moves the top element into the given position (and pops it), without
  2091. shifting any element (therefore replacing the value at the given
  2092. position).
  2093. lua_resume *lua_resume()*
  2094. >c
  2095. int lua_resume (lua_State *L, int narg);
  2096. <
  2097. Starts and resumes a coroutine in a given thread.
  2098. To start a coroutine, you first create a new thread (see
  2099. |lua_newthread()|); then you push onto its stack the main
  2100. function plus any arguments; then you call `lua_resume` (see
  2101. |lua_resume()|) with `narg` being the number of arguments. This
  2102. call returns when the coroutine suspends or finishes its execution.
  2103. When it returns, the stack contains all values passed to `lua_yield`
  2104. (see |lua_yield()|), or all values returned by the body function.
  2105. `lua_resume` returns `LUA_YIELD` if the coroutine yields, 0 if the
  2106. coroutine finishes its execution without errors, or an error code in
  2107. case of errors (see |lua_pcall()|). In case of errors, the stack
  2108. is not unwound, so you can use the debug API over it. The error
  2109. message is on the top of the stack. To restart a coroutine, you put on
  2110. its stack only the values to be passed as results from `lua_yield`,
  2111. and then call `lua_resume`.
  2112. lua_setallocf *lua_setallocf()*
  2113. >c
  2114. void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);
  2115. <
  2116. Changes the allocator function of a given state to `f` with user data
  2117. `ud`.
  2118. lua_setfenv *lua_setfenv()*
  2119. >c
  2120. int lua_setfenv (lua_State *L, int index);
  2121. <
  2122. Pops a table from the stack and sets it as the new environment for the
  2123. value at the given index. If the value at the given index is neither a
  2124. function nor a thread nor a userdata, `lua_setfenv` returns 0.
  2125. Otherwise it returns 1.
  2126. lua_setfield *lua_setfield()*
  2127. >c
  2128. void lua_setfield (lua_State *L, int index, const char *k);
  2129. <
  2130. Does the equivalent to `t[k] = v`, where `t` is the value at the given
  2131. valid index `index` and `v` is the value at the top of the stack.
  2132. This function pops the value from the stack. As in Lua, this function
  2133. may trigger a metamethod for the "newindex" event (see
  2134. |lua-metatable|).
  2135. lua_setglobal *lua_setglobal()*
  2136. >c
  2137. void lua_setglobal (lua_State *L, const char *name);
  2138. <
  2139. Pops a value from the stack and sets it as the new value of global
  2140. `name`. It is defined as a macro:
  2141. >c
  2142. #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s)
  2143. <
  2144. lua_setmetatable *lua_setmetatable()*
  2145. >c
  2146. int lua_setmetatable (lua_State *L, int index);
  2147. <
  2148. Pops a table from the stack and sets it as the new metatable for the
  2149. value at the given acceptable index.
  2150. lua_settable *lua_settable()*
  2151. >c
  2152. void lua_settable (lua_State *L, int index);
  2153. <
  2154. Does the equivalent to `t[k] = v`, where `t` is the value at the given
  2155. valid index `index`, `v` is the value at the top of the stack, and `k`
  2156. is the value just below the top.
  2157. This function pops both the key and the value from the stack. As in
  2158. Lua, this function may trigger a metamethod for the "newindex" event
  2159. (see |lua-metatable|).
  2160. lua_settop *lua_settop()*
  2161. >c
  2162. void lua_settop (lua_State *L, int index);
  2163. <
  2164. Accepts any acceptable index, or 0, and sets the stack top to this
  2165. index. If the new top is larger than the old one, then the new
  2166. elements are filled with `nil`. If `index` is 0, then all stack
  2167. elements are removed.
  2168. lua_State *lua_State*
  2169. >c
  2170. typedef struct lua_State lua_State;
  2171. <
  2172. Opaque structure that keeps the whole state of a Lua interpreter. The
  2173. Lua library is fully reentrant: it has no global variables. All
  2174. information about a state is kept in this structure.
  2175. A pointer to this state must be passed as the first argument to every
  2176. function in the library, except to `lua_newstate` (see
  2177. |lua_newstate()|), which creates a Lua state from scratch.
  2178. lua_status *lua_status()*
  2179. >c
  2180. int lua_status (lua_State *L);
  2181. <
  2182. Returns the status of the thread `L`.
  2183. The status can be 0 for a normal thread, an error code if the thread
  2184. finished its execution with an error, or `LUA_YIELD` if the thread is
  2185. suspended.
  2186. lua_toboolean *lua_toboolean()*
  2187. >c
  2188. int lua_toboolean (lua_State *L, int index);
  2189. <
  2190. Converts the Lua value at the given acceptable index to a C boolean
  2191. value (0 or 1). Like all tests in Lua, `lua_toboolean` returns 1 for
  2192. any Lua value different from `false` and `nil`; otherwise it returns
  2193. 0. It also returns 0 when called with a non-valid index. (If you want
  2194. to accept only actual boolean values, use `lua_isboolean`
  2195. |lua_isboolean()| to test the value's type.)
  2196. lua_tocfunction *lua_tocfunction()*
  2197. >c
  2198. lua_CFunction lua_tocfunction (lua_State *L, int index);
  2199. <
  2200. Converts a value at the given acceptable index to a C function. That
  2201. value must be a C function; otherwise it returns `NULL`.
  2202. lua_tointeger *lua_tointeger()*
  2203. >c
  2204. lua_Integer lua_tointeger (lua_State *L, int idx);
  2205. <
  2206. Converts the Lua value at the given acceptable index to the signed
  2207. integral type `lua_Integer` (see |lua_Integer|). The Lua value
  2208. must be a number or a string convertible to a number (see
  2209. |lua-coercion|); otherwise, `lua_tointeger` returns 0.
  2210. If the number is not an integer, it is truncated in some non-specified
  2211. way.
  2212. lua_tolstring *lua_tolstring()*
  2213. >c
  2214. const char *lua_tolstring (lua_State *L, int index, size_t *len);
  2215. <
  2216. Converts the Lua value at the given acceptable index to a C string. If
  2217. `len` is not `NULL`, it also sets `*len` with the string length. The
  2218. Lua value must be a string or a number; otherwise, the function
  2219. returns `NULL`. If the value is a number, then `lua_tolstring` also
  2220. `changes the actual value in the stack to a` `string`. (This change
  2221. confuses `lua_next` |lua_next()| when `lua_tolstring` is applied
  2222. to keys during a table traversal.)
  2223. `lua_tolstring` returns a fully aligned pointer to a string inside the
  2224. Lua state. This string always has a zero (`\0`) after its last
  2225. character (as in C), but may contain other zeros in its body. Because
  2226. Lua has garbage collection, there is no guarantee that the pointer
  2227. returned by `lua_tolstring` will be valid after the corresponding
  2228. value is removed from the stack.
  2229. lua_tonumber *lua_tonumber()*
  2230. >c
  2231. lua_Number lua_tonumber (lua_State *L, int index);
  2232. <
  2233. Converts the Lua value at the given acceptable index to the C type
  2234. `lua_Number` (see |lua_Number|). The Lua value must be a number
  2235. or a string convertible to a number (see |lua-coercion|);
  2236. otherwise, `lua_tonumber` returns 0.
  2237. lua_topointer *lua_topointer()*
  2238. >c
  2239. const void *lua_topointer (lua_State *L, int index);
  2240. <
  2241. Converts the value at the given acceptable index to a generic C
  2242. pointer (`void*`). The value may be a userdata, a table, a thread, or
  2243. a function; otherwise, `lua_topointer` returns `NULL`. Different
  2244. objects will give different pointers. There is no way to convert the
  2245. pointer back to its original value.
  2246. Typically this function is used only for debug information.
  2247. lua_tostring *lua_tostring()*
  2248. >c
  2249. const char *lua_tostring (lua_State *L, int index);
  2250. <
  2251. Equivalent to `lua_tolstring` (see |lua_tolstring()|) with `len`
  2252. equal to `NULL`.
  2253. lua_tothread *lua_tothread()*
  2254. >c
  2255. lua_State *lua_tothread (lua_State *L, int index);
  2256. <
  2257. Converts the value at the given acceptable index to a Lua thread
  2258. (represented as `lua_State*` |lua_State|). This value must be a
  2259. thread; otherwise, the function returns `NULL`.
  2260. lua_touserdata *lua_touserdata()*
  2261. >c
  2262. void *lua_touserdata (lua_State *L, int index);
  2263. <
  2264. If the value at the given acceptable index is a full userdata, returns
  2265. its block address. If the value is a light userdata, returns its
  2266. pointer. Otherwise, it returns `NULL`.
  2267. lua_type *lua_type()*
  2268. >c
  2269. int lua_type (lua_State *L, int index);
  2270. <
  2271. Returns the type of the value in the given acceptable index, or
  2272. `LUA_TNONE` for a non-valid index (that is, an index to an "empty"
  2273. stack position). The types returned by `lua_type` are coded by the
  2274. following constants defined in `lua.h` : `LUA_TNIL`, `LUA_TNUMBER`,
  2275. `LUA_TBOOLEAN`, `LUA_TSTRING`, `LUA_TTABLE`, `LUA_TFUNCTION`,
  2276. `LUA_TUSERDATA`, `LUA_TTHREAD`, and `LUA_TLIGHTUSERDATA`.
  2277. lua_typename *lua_typename()*
  2278. >c
  2279. const char *lua_typename (lua_State *L, int tp);
  2280. <
  2281. Returns the name of the type encoded by the value `tp`, which must be
  2282. one the values returned by `lua_type`.
  2283. lua_Writer *lua_Writer*
  2284. >c
  2285. typedef int (*lua_Writer) (lua_State *L,
  2286. const void* p,
  2287. size_t sz,
  2288. void* ud);
  2289. <
  2290. The writer function used by `lua_dump` (see |lua_dump()|). Every
  2291. time it produces another piece of chunk, `lua_dump` calls the writer,
  2292. passing along the buffer to be written (`p`), its size (`sz`), and the
  2293. `data` parameter supplied to `lua_dump`.
  2294. The writer returns an error code: 0 means no errors; any other value
  2295. means an error and stops `lua_dump` from calling the writer again.
  2296. lua_xmove *lua_xmove()*
  2297. >c
  2298. void lua_xmove (lua_State *from, lua_State *to, int n);
  2299. <
  2300. Exchange values between different threads of the `same` global state.
  2301. This function pops `n` values from the stack `from`, and pushes them
  2302. onto the stack `to`.
  2303. lua_yield *lua_yield()*
  2304. >c
  2305. int lua_yield (lua_State *L, int nresults);
  2306. <
  2307. Yields a coroutine.
  2308. This function should only be called as the return expression of a C
  2309. function, as follows:
  2310. >c
  2311. return lua_yield (L, nresults);
  2312. <
  2313. When a C function calls `lua_yield` in that way, the running coroutine
  2314. suspends its execution, and the call to `lua_resume` (see
  2315. |lua_resume()|) that started this coroutine returns. The
  2316. parameter `nresults` is the number of values from the stack that are
  2317. passed as results to `lua_resume`.
  2318. *lua-stackexample*
  2319. As an example of stack manipulation, if the stack starts as
  2320. `10 20 30 40 50*` (from bottom to top; the `*` marks the top), then
  2321. >
  2322. lua_pushvalue(L, 3) --> 10 20 30 40 50 30*
  2323. lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30*
  2324. lua_remove(L, -3) --> 10 20 30 40 30 30*
  2325. lua_remove(L, 6) --> 10 20 30 40 30*
  2326. lua_insert(L, 1) --> 30 10 20 30 40*
  2327. lua_insert(L, -1) --> 30 10 20 30 40* (no effect)
  2328. lua_replace(L, 2) --> 30 40 20 30*
  2329. lua_settop(L, -3) --> 30 40*
  2330. lua_settop(L, 6) --> 30 40 nil nil nil nil*
  2331. <
  2332. ==============================================================================
  2333. 3.8 The Debug Interface *lua-apiDebug*
  2334. Lua has no built-in debugging facilities. Instead, it offers a special
  2335. interface by means of functions and hooks. This interface allows the
  2336. construction of different kinds of debuggers, profilers, and other tools that
  2337. need "inside information" from the interpreter.
  2338. lua_Debug *lua_Debug*
  2339. >c
  2340. typedef struct lua_Debug {
  2341. int event;
  2342. const char *name; /* (n) */
  2343. const char *namewhat; /* (n) */
  2344. const char *what; /* (S) */
  2345. const char *source; /* (S) */
  2346. int currentline; /* (l) */
  2347. int nups; /* (u) number of upvalues */
  2348. int linedefined; /* (S) */
  2349. int lastlinedefined; /* (S) */
  2350. char short_src[LUA_IDSIZE]; /* (S) */
  2351. /* private part */
  2352. other fields
  2353. } lua_Debug;
  2354. <
  2355. A structure used to carry different pieces of information about an active
  2356. function. `lua_getstack` (see |lua_getstack()|) fills only the private part
  2357. of this structure, for later use. To fill the other fields of `lua_Debug` with
  2358. useful information, call `lua_getinfo` (see |lua_getinfo()|).
  2359. The fields of `lua_Debug` have the following meaning:
  2360. - `source` If the function was defined in a string, then `source` is
  2361. that string. If the function was defined in a file, then
  2362. `source` starts with a `@` followed by the file name.
  2363. - `short_src` a "printable" version of `source`, to be used in error messages.
  2364. - `linedefined` the line number where the definition of the function starts.
  2365. - `lastlinedefined` the line number where the definition of the function ends.
  2366. - `what` the string `"Lua"` if the function is a Lua function,
  2367. `"C"` if it is a C function, `"main"` if it is the main
  2368. part of a chunk, and `"tail"` if it was a function that
  2369. did a tail call. In the latter case, Lua has no other
  2370. information about the function.
  2371. - `currentline` the current line where the given function is executing.
  2372. When no line information is available, `currentline` is
  2373. set to -1.
  2374. - `name` a reasonable name for the given function. Because
  2375. functions in Lua are first-class values, they do not have
  2376. a fixed name: some functions may be the value of multiple
  2377. global variables, while others may be stored only in a
  2378. table field. The `lua_getinfo` function checks how the
  2379. function was called to find a suitable name. If it cannot
  2380. find a name, then `name` is set to `NULL`.
  2381. - `namewhat` explains the `name` field. The value of `namewhat` can be
  2382. `"global"`, `"local"`, `"method"`, `"field"`,
  2383. `"upvalue"`, or `""` (the empty string), according to how
  2384. the function was called. (Lua uses the empty string when
  2385. no other option seems to apply.) `nups` the number of
  2386. upvalues of the function.
  2387. lua_gethook *lua_gethook()*
  2388. >c
  2389. lua_Hook lua_gethook (lua_State *L);
  2390. <
  2391. Returns the current hook function.
  2392. lua_gethookcount *lua_gethookcount()*
  2393. >c
  2394. int lua_gethookcount (lua_State *L);
  2395. <
  2396. Returns the current hook count.
  2397. lua_gethookmask *lua_gethookmask()*
  2398. >c
  2399. int lua_gethookmask (lua_State *L);
  2400. <
  2401. Returns the current hook mask.
  2402. lua_getinfo *lua_getinfo()*
  2403. >c
  2404. int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
  2405. <
  2406. Returns information about a specific function or function invocation.
  2407. To get information about a function invocation, the parameter `ar`
  2408. must be a valid activation record that was filled by a previous call
  2409. to `lua_getstack` (see |lua_getstack()|) or given as argument to
  2410. a hook (see |lua_Hook|).
  2411. To get information about a function you push it onto the stack and
  2412. start the `what` string with the character `>`. (In that case,
  2413. `lua_getinfo` pops the function in the top of the stack.) For
  2414. instance, to know in which line a function `f` was defined, you can
  2415. write the following code:
  2416. >c
  2417. lua_Debug ar;
  2418. lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global 'f' */
  2419. lua_getinfo(L, ">S", &ar);
  2420. printf("%d\n", ar.linedefined);
  2421. <
  2422. Each character in the string `what` selects some fields of the
  2423. structure `ar` to be filled or a value to be pushed on the stack:
  2424. `'n'` fills in the field `name` and `namewhat`
  2425. `'S'` fills in the fields `source`, `short_src`, `linedefined`,
  2426. `lastlinedefined`, and `what`
  2427. `'l'` fills in the field `currentline`
  2428. `'u'` fills in the field `nups`
  2429. `'f'` pushes onto the stack the function that is running at the
  2430. given level
  2431. `'L'` pushes onto the stack a table whose indices are the numbers
  2432. of the lines that are valid on the function. (A `valid line` is a
  2433. line with some associated code, that is, a line where you can put
  2434. a break point. Non-valid lines include empty lines and comments.)
  2435. This function returns 0 on error (for instance, an invalid option in
  2436. `what`).
  2437. lua_getlocal *lua_getlocal()*
  2438. >c
  2439. const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);
  2440. <
  2441. Gets information about a local variable of a given activation record.
  2442. The parameter `ar` must be a valid activation record that was filled
  2443. by a previous call to `lua_getstack` (see |lua_getstack()|) or
  2444. given as argument to a hook (see |lua_Hook|). The index `n`
  2445. selects which local variable to inspect (1 is the first parameter or
  2446. active local variable, and so on, until the last active local
  2447. variable). `lua_getlocal` pushes the variable's value onto the stack
  2448. and returns its name.
  2449. Variable names starting with `(` (open parentheses) represent
  2450. internal variables (loop control variables, temporaries, and C
  2451. function locals).
  2452. Returns `NULL` (and pushes nothing) when the index is greater than the
  2453. number of active local variables.
  2454. lua_getstack *lua_getstack()*
  2455. >c
  2456. int lua_getstack (lua_State *L, int level, lua_Debug *ar);
  2457. <
  2458. Gets information about the interpreter runtime stack.
  2459. This function fills parts of a `lua_Debug` (see |lua_Debug|)
  2460. structure with an identification of the `activation record` of the
  2461. function executing at a given level. Level 0 is the current running
  2462. function, whereas level `n+1` is the function that has called level
  2463. `n`. When there are no errors, `lua_getstack` returns 1; when called
  2464. with a level greater than the stack depth, it returns 0.
  2465. lua_getupvalue *lua_getupvalue()*
  2466. >c
  2467. const char *lua_getupvalue (lua_State *L, int funcindex, int n);
  2468. <
  2469. Gets information about a closure's upvalue. (For Lua functions,
  2470. upvalues are the external local variables that the function uses, and
  2471. that are consequently included in its closure.) `lua_getupvalue` gets
  2472. the index `n` of an upvalue, pushes the upvalue's value onto the
  2473. stack, and returns its name. `funcindex` points to the closure in the
  2474. stack. (Upvalues have no particular order, as they are active through
  2475. the whole function. So, they are numbered in an arbitrary order.)
  2476. Returns `NULL` (and pushes nothing) when the index is greater than the
  2477. number of upvalues. For C functions, this function uses the empty
  2478. string `""` as a name for all upvalues.
  2479. lua_Hook *lua_Hook*
  2480. >c
  2481. typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
  2482. <
  2483. Type for debugging hook functions.
  2484. Whenever a hook is called, its `ar` argument has its field `event` set
  2485. to the specific event that triggered the hook. Lua identifies these
  2486. events with the following constants: `LUA_HOOKCALL`, `LUA_HOOKRET`,
  2487. `LUA_HOOKTAILRET`, `LUA_HOOKLINE`, and `LUA_HOOKCOUNT`. Moreover, for
  2488. line events, the field `currentline` is also set. To get the value of
  2489. any other field in `ar`, the hook must call `lua_getinfo` (see
  2490. |lua_getinfo()|). For return events, `event` may be
  2491. `LUA_HOOKRET`, the normal value, or `LUA_HOOKTAILRET`. In the latter
  2492. case, Lua is simulating a return from a function that did a tail call;
  2493. in this case, it is useless to call `lua_getinfo`.
  2494. While Lua is running a hook, it disables other calls to hooks.
  2495. Therefore, if a hook calls back Lua to execute a function or a chunk,
  2496. this execution occurs without any calls to hooks.
  2497. lua_sethook *lua_sethook()*
  2498. >c
  2499. int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);
  2500. <
  2501. Sets the debugging hook function.
  2502. Argument `f` is the hook function. `mask` specifies on which events
  2503. the hook will be called: it is formed by a bitwise `or` of the
  2504. constants `LUA_MASKCALL`, `LUA_MASKRET`, `LUA_MASKLINE`, and
  2505. `LUA_MASKCOUNT`. The `count` argument is only meaningful when the mask
  2506. includes `LUA_MASKCOUNT`. For each event, the hook is called as
  2507. explained below:
  2508. - `The call hook`: is called when the interpreter calls a function.
  2509. The hook is called just after Lua enters the new function, before
  2510. the function gets its arguments.
  2511. - `The return hook`: is called when the interpreter returns from a
  2512. function. The hook is called just before Lua leaves the function.
  2513. You have no access to the values to be returned by the function.
  2514. - `The line hook`: is called when the interpreter is about to start
  2515. the execution of a new line of code, or when it jumps back in the
  2516. code (even to the same line). (This event only happens while Lua is
  2517. executing a Lua function.)
  2518. - `The count hook`: is called after the interpreter executes every
  2519. `count` instructions. (This event only happens while Lua is
  2520. executing a Lua function.)
  2521. A hook is disabled by setting `mask` to zero.
  2522. lua_setlocal *lua_setlocal()*
  2523. >c
  2524. const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);
  2525. <
  2526. Sets the value of a local variable of a given activation record.
  2527. Parameters `ar` and `n` are as in `lua_getlocal` (see
  2528. |lua_getlocal()|). `lua_setlocal` assigns the value at the top of
  2529. the stack to the variable and returns its name. It also pops the value
  2530. from the stack.
  2531. Returns `NULL` (and pops nothing) when the index is greater than the
  2532. number of active local variables.
  2533. lua_setupvalue *lua_setupvalue()*
  2534. >c
  2535. const char *lua_setupvalue (lua_State *L, int funcindex, int n);
  2536. <
  2537. Sets the value of a closure's upvalue. It assigns the value at the top
  2538. of the stack to the upvalue and returns its name. It also pops the
  2539. value from the stack. Parameters `funcindex` and `n` are as in the
  2540. `lua_getupvalue` (see |lua_getupvalue()|).
  2541. Returns `NULL` (and pops nothing) when the index is greater than the
  2542. number of upvalues.
  2543. *lua-debugexample*
  2544. As an example, the following function lists the names of all local
  2545. variables and upvalues for a function at a given level of the stack:
  2546. >c
  2547. int listvars (lua_State *L, int level) {
  2548. lua_Debug ar;
  2549. int i;
  2550. const char *name;
  2551. if (lua_getstack(L, level, &ar) == 0)
  2552. return 0; /* failure: no such level in the stack */
  2553. i = 1;
  2554. while ((name = lua_getlocal(L, &ar, i++)) != NULL) {
  2555. printf("local %d %s\n", i-1, name);
  2556. lua_pop(L, 1); /* remove variable value */
  2557. }
  2558. lua_getinfo(L, "f", &ar); /* retrieves function */
  2559. i = 1;
  2560. while ((name = lua_getupvalue(L, -1, i++)) != NULL) {
  2561. printf("upvalue %d %s\n", i-1, name);
  2562. lua_pop(L, 1); /* remove upvalue value */
  2563. }
  2564. return 1;
  2565. }
  2566. <
  2567. ==============================================================================
  2568. 4 THE AUXILIARY LIBRARY *lua-aux*
  2569. The auxiliary library provides several convenient functions to interface C
  2570. with Lua. While the basic API provides the primitive functions for all
  2571. interactions between C and Lua, the auxiliary library provides higher-level
  2572. functions for some common tasks.
  2573. All functions from the auxiliary library are defined in header file `lauxlib.h`
  2574. and have a prefix `luaL_`.
  2575. All functions in the auxiliary library are built on top of the basic API, and
  2576. so they provide nothing that cannot be done with this API.
  2577. Several functions in the auxiliary library are used to check C function
  2578. arguments. Their names are always `luaL_check*` or `luaL_opt*`. All of these
  2579. functions raise an error if the check is not satisfied. Because the error
  2580. message is formatted for arguments (e.g., "bad argument #1"), you should not
  2581. use these functions for other stack values.
  2582. ==============================================================================
  2583. 4.1 Functions and Types *lua-auxFunctions*
  2584. Here we list all functions and types from the auxiliary library in
  2585. alphabetical order.
  2586. luaL_addchar *luaL_addchar()*
  2587. >c
  2588. void luaL_addchar (luaL_Buffer *B, char c);
  2589. <
  2590. Adds the character `c` to the buffer `B` (see |luaL_Buffer|).
  2591. luaL_addlstring *luaL_addlstring()*
  2592. >c
  2593. void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);
  2594. <
  2595. Adds the string pointed to by `s` with length `l` to the buffer `B`
  2596. (see |luaL_Buffer|). The string may contain embedded zeros.
  2597. luaL_addsize *luaL_addsize()*
  2598. >c
  2599. void luaL_addsize (luaL_Buffer *B, size_t n);
  2600. <
  2601. Adds to the buffer `B` (see |luaL_Buffer|) a string of length
  2602. `n` previously copied to the buffer area (see
  2603. |luaL_prepbuffer()|).
  2604. luaL_addstring *luaL_addstring()*
  2605. >c
  2606. void luaL_addstring (luaL_Buffer *B, const char *s);
  2607. <
  2608. Adds the zero-terminated string pointed to by `s` to the buffer `B`
  2609. (see |luaL_Buffer|). The string may not contain embedded zeros.
  2610. luaL_addvalue *luaL_addvalue()*
  2611. >c
  2612. void luaL_addvalue (luaL_Buffer *B);
  2613. <
  2614. Adds the value at the top of the stack to the buffer `B` (see
  2615. |luaL_Buffer|). Pops the value.
  2616. This is the only function on string buffers that can (and must) be
  2617. called with an extra element on the stack, which is the value to be
  2618. added to the buffer.
  2619. luaL_argcheck *luaL_argcheck()*
  2620. >c
  2621. void luaL_argcheck (lua_State *L,
  2622. int cond,
  2623. int narg,
  2624. const char *extramsg);
  2625. <
  2626. Checks whether `cond` is true. If not, raises an error with the
  2627. following message, where `func` is retrieved from the call stack:
  2628. >
  2629. bad argument #<narg> to <func> (<extramsg>)
  2630. <
  2631. luaL_argerror *luaL_argerror()*
  2632. >c
  2633. int luaL_argerror (lua_State *L, int narg, const char *extramsg);
  2634. <
  2635. Raises an error with the following message, where `func` is retrieved
  2636. from the call stack:
  2637. >
  2638. bad argument #<narg> to <func> (<extramsg>)
  2639. <
  2640. This function never returns, but it is an idiom to use it in C
  2641. functions as `return luaL_argerror(` `args` `)`.
  2642. luaL_Buffer *luaL_Buffer*
  2643. >c
  2644. typedef struct luaL_Buffer luaL_Buffer;
  2645. <
  2646. Type for a `string buffer`.
  2647. A string buffer allows C code to build Lua strings piecemeal. Its
  2648. pattern of use is as follows:
  2649. - First you declare a variable `b` of type `luaL_Buffer`.
  2650. - Then you initialize it with a call `luaL_buffinit(L, &b)` (see
  2651. |luaL_buffinit()|).
  2652. - Then you add string pieces to the buffer calling any of the
  2653. `luaL_add*` functions.
  2654. - You finish by calling `luaL_pushresult(&b)` (see
  2655. |luaL_pushresult()|). This call leaves the final string on the
  2656. top of the stack.
  2657. During its normal operation, a string buffer uses a variable number of
  2658. stack slots. So, while using a buffer, you cannot assume that you know
  2659. where the top of the stack is. You can use the stack between
  2660. successive calls to buffer operations as long as that use is balanced;
  2661. that is, when you call a buffer operation, the stack is at the same
  2662. level it was immediately after the previous buffer operation. (The
  2663. only exception to this rule is `luaL_addvalue`
  2664. |luaL_addvalue()|.) After calling `luaL_pushresult` the stack is
  2665. back to its level when the buffer was initialized, plus the final
  2666. string on its top.
  2667. luaL_buffinit *luaL_buffinit()*
  2668. >c
  2669. void luaL_buffinit (lua_State *L, luaL_Buffer *B);
  2670. <
  2671. Initializes a buffer `B`. This function does not allocate any space;
  2672. the buffer must be declared as a variable (see |luaL_Buffer|).
  2673. luaL_callmeta *luaL_callmeta()*
  2674. >c
  2675. int luaL_callmeta (lua_State *L, int obj, const char *e);
  2676. <
  2677. Calls a metamethod.
  2678. If the object at index `obj` has a metatable and this metatable has a
  2679. field `e`, this function calls this field and passes the object as its
  2680. only argument. In this case this function returns 1 and pushes onto
  2681. the stack the value returned by the call. If there is no metatable or
  2682. no metamethod, this function returns
  2683. 0 (without pushing any value on the stack).
  2684. luaL_checkany *luaL_checkany()*
  2685. >c
  2686. void luaL_checkany (lua_State *L, int narg);
  2687. <
  2688. Checks whether the function has an argument of any type (including
  2689. `nil`) at position `narg`.
  2690. luaL_checkint *luaL_checkint()*
  2691. >c
  2692. int luaL_checkint (lua_State *L, int narg);
  2693. <
  2694. Checks whether the function argument `narg` is a number and returns
  2695. this number cast to an `int`.
  2696. luaL_checkinteger *luaL_checkinteger()*
  2697. >c
  2698. lua_Integer luaL_checkinteger (lua_State *L, int narg);
  2699. <
  2700. Checks whether the function argument `narg` is a number and returns
  2701. this number cast to a `lua_Integer` (see |lua_Integer|).
  2702. luaL_checklong *luaL_checklong()*
  2703. >c
  2704. long luaL_checklong (lua_State *L, int narg);
  2705. <
  2706. Checks whether the function argument `narg` is a number and returns
  2707. this number cast to a `long`.
  2708. luaL_checklstring *luaL_checklstring()*
  2709. >c
  2710. const char *luaL_checklstring (lua_State *L, int narg, size_t *l);
  2711. <
  2712. Checks whether the function argument `narg` is a string and returns
  2713. this string; if `l` is not `NULL` fills `*l` with the string's length.
  2714. luaL_checknumber *luaL_checknumber()*
  2715. >c
  2716. lua_Number luaL_checknumber (lua_State *L, int narg);
  2717. <
  2718. Checks whether the function argument `narg` is a number and returns
  2719. this number (see |lua_Number|).
  2720. luaL_checkoption *luaL_checkoption()*
  2721. >c
  2722. int luaL_checkoption (lua_State *L,
  2723. int narg,
  2724. const char *def,
  2725. const char *const lst[]);
  2726. <
  2727. Checks whether the function argument `narg` is a string and searches
  2728. for this string in the array `lst` (which must be NULL-terminated).
  2729. Returns the index in the array where the string was found. Raises an
  2730. error if the argument is not a string or if the string cannot be
  2731. found.
  2732. If `def` is not `NULL`, the function uses `def` as a default value
  2733. when there is no argument `narg` or if this argument is `nil`.
  2734. This is a useful function for mapping strings to C enums. (The usual
  2735. convention in Lua libraries is to use strings instead of numbers to
  2736. select options.)
  2737. luaL_checkstack *luaL_checkstack()*
  2738. >c
  2739. void luaL_checkstack (lua_State *L, int sz, const char *msg);
  2740. <
  2741. Grows the stack size to `top + sz` elements, raising an error if the
  2742. stack cannot grow to that size. `msg` is an additional text to go into
  2743. the error message.
  2744. luaL_checkstring *luaL_checkstring()*
  2745. >c
  2746. const char *luaL_checkstring (lua_State *L, int narg);
  2747. <
  2748. Checks whether the function argument `narg` is a string and returns
  2749. this string.
  2750. luaL_checktype *luaL_checktype()*
  2751. >c
  2752. void luaL_checktype (lua_State *L, int narg, int t);
  2753. <
  2754. Checks whether the function argument `narg` has type `t` (see
  2755. |lua_type()|).
  2756. luaL_checkudata *luaL_checkudata()*
  2757. >c
  2758. void *luaL_checkudata (lua_State *L, int narg, const char *tname);
  2759. <
  2760. Checks whether the function argument `narg` is a userdata of the type
  2761. `tname` (see |luaL_newmetatable()|).
  2762. luaL_dofile *luaL_dofile()*
  2763. >c
  2764. int luaL_dofile (lua_State *L, const char *filename);
  2765. <
  2766. Loads and runs the given file. It is defined as the following macro:
  2767. >c
  2768. (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
  2769. <
  2770. It returns 0 if there are no errors or 1 in case of errors.
  2771. luaL_dostring *luaL_dostring()*
  2772. >c
  2773. int luaL_dostring (lua_State *L, const char *str);
  2774. <
  2775. Loads and runs the given string. It is defined as the following macro:
  2776. >c
  2777. (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
  2778. <
  2779. It returns 0 if there are no errors or 1 in case of errors.
  2780. luaL_error *luaL_error()*
  2781. >c
  2782. int luaL_error (lua_State *L, const char *fmt, ...);
  2783. <
  2784. Raises an error. The error message format is given by `fmt` plus any
  2785. extra arguments, following the same rules of `lua_pushfstring` (see
  2786. |lua_pushfstring()|). It also adds at the beginning of the
  2787. message the file name and the line number where the error occurred, if
  2788. this information is available.
  2789. This function never returns, but it is an idiom to use it in C
  2790. functions as `return luaL_error(` `args` `)`.
  2791. luaL_getmetafield *luaL_getmetafield()*
  2792. >c
  2793. int luaL_getmetafield (lua_State *L, int obj, const char *e);
  2794. <
  2795. Pushes onto the stack the field `e` from the metatable of the object
  2796. at index `obj`. If the object does not have a metatable, or if the
  2797. metatable does not have this field, returns 0 and pushes nothing.
  2798. luaL_getmetatable *luaL_getmetatable()*
  2799. >c
  2800. void luaL_getmetatable (lua_State *L, const char *tname);
  2801. <
  2802. Pushes onto the stack the metatable associated with name `tname` in
  2803. the registry (see |luaL_newmetatable()|).
  2804. luaL_gsub *luaL_gsub()*
  2805. >c
  2806. const char *luaL_gsub (lua_State *L,
  2807. const char *s,
  2808. const char *p,
  2809. const char *r);
  2810. <
  2811. Creates a copy of string `s` by replacing any occurrence of the string
  2812. `p` with the string `r`. Pushes the resulting string on the stack and
  2813. returns it.
  2814. luaL_loadbuffer *luaL_loadbuffer()*
  2815. >c
  2816. int luaL_loadbuffer (lua_State *L,
  2817. const char *buff,
  2818. size_t sz,
  2819. const char *name);
  2820. <
  2821. Loads a buffer as a Lua chunk. This function uses `lua_load` (see
  2822. |lua_load()|) to load the chunk in the buffer pointed to by
  2823. `buff` with size `sz`.
  2824. This function returns the same results as `lua_load`. `name` is the
  2825. chunk name, used for debug information and error messages.
  2826. luaL_loadfile *luaL_loadfile()*
  2827. >c
  2828. int luaL_loadfile (lua_State *L, const char *filename);
  2829. <
  2830. Loads a file as a Lua chunk. This function uses `lua_load` (see
  2831. |lua_load()|) to load the chunk in the file named `filename`. If
  2832. `filename` is `NULL`, then it loads from the standard input. The first
  2833. line in the file is ignored if it starts with a `#`.
  2834. This function returns the same results as `lua_load`, but it has an
  2835. extra error code `LUA_ERRFILE` if it cannot open/read the file.
  2836. As `lua_load`, this function only loads the chunk; it does not run it.
  2837. luaL_loadstring *luaL_loadstring()*
  2838. >c
  2839. int luaL_loadstring (lua_State *L, const char *s);
  2840. <
  2841. Loads a string as a Lua chunk. This function uses `lua_load` (see
  2842. |lua_load()|) to load the chunk in the zero-terminated string
  2843. `s`.
  2844. This function returns the same results as `lua_load`.
  2845. Also as `lua_load`, this function only loads the chunk; it does not
  2846. run it.
  2847. luaL_newmetatable *luaL_newmetatable()*
  2848. >c
  2849. int luaL_newmetatable (lua_State *L, const char *tname);
  2850. <
  2851. If the registry already has the key `tname`, returns 0. Otherwise,
  2852. creates a new table to be used as a metatable for userdata, adds it to
  2853. the registry with key `tname`, and returns 1.
  2854. In both cases pushes onto the stack the final value associated with
  2855. `tname` in the registry.
  2856. luaL_newstate *luaL_newstate()*
  2857. >c
  2858. lua_State *luaL_newstate (void);
  2859. <
  2860. Creates a new Lua state. It calls `lua_newstate` (see
  2861. |lua_newstate()|) with an allocator based on the standard C
  2862. `realloc` function and then sets a panic function (see
  2863. |lua_atpanic()|) that prints an error message to the standard
  2864. error output in case of fatal errors.
  2865. Returns the new state, or `NULL` if there is a memory allocation
  2866. error.
  2867. luaL_openlibs *luaL_openlibs()*
  2868. >c
  2869. void luaL_openlibs (lua_State *L);
  2870. <
  2871. Opens all standard Lua libraries into the given state. See also
  2872. |lua-openlibs| for details on how to open individual libraries.
  2873. luaL_optint *luaL_optint()*
  2874. >c
  2875. int luaL_optint (lua_State *L, int narg, int d);
  2876. <
  2877. If the function argument `narg` is a number, returns this number cast
  2878. to an `int`. If this argument is absent or is `nil`, returns `d`.
  2879. Otherwise, raises an error.
  2880. luaL_optinteger *luaL_optinteger()*
  2881. >c
  2882. lua_Integer luaL_optinteger (lua_State *L,
  2883. int narg,
  2884. lua_Integer d);
  2885. <
  2886. If the function argument `narg` is a number, returns this number cast
  2887. to a `lua_Integer` (see |lua_Integer|). If this argument is
  2888. absent or is `nil`, returns `d`. Otherwise, raises an error.
  2889. luaL_optlong *luaL_optlong()*
  2890. >c
  2891. long luaL_optlong (lua_State *L, int narg, long d);
  2892. <
  2893. If the function argument `narg` is a number, returns this number cast
  2894. to a `long`. If this argument is absent or is `nil`, returns `d`.
  2895. Otherwise, raises an error.
  2896. luaL_optlstring *luaL_optlstring()*
  2897. >c
  2898. const char *luaL_optlstring (lua_State *L,
  2899. int narg,
  2900. const char *d,
  2901. size_t *l);
  2902. <
  2903. If the function argument `narg` is a string, returns this string. If
  2904. this argument is absent or is `nil`, returns `d`. Otherwise, raises an
  2905. error.
  2906. If `l` is not `NULL`, fills the position `*l` with the results' length.
  2907. luaL_optnumber *luaL_optnumber()*
  2908. >c
  2909. lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);
  2910. <
  2911. If the function argument `narg` is a number, returns this number. If
  2912. this argument is absent or is `nil`, returns `d`. Otherwise, raises an
  2913. error.
  2914. luaL_optstring *luaL_optstring()*
  2915. >c
  2916. const char *luaL_optstring (lua_State *L,
  2917. int narg,
  2918. const char *d);
  2919. <
  2920. If the function argument `narg` is a string, returns this string. If
  2921. this argument is absent or is `nil`, returns `d`. Otherwise, raises an
  2922. error.
  2923. luaL_prepbuffer *luaL_prepbuffer()*
  2924. >c
  2925. char *luaL_prepbuffer (luaL_Buffer *B);
  2926. <
  2927. Returns an address to a space of size `LUAL_BUFFERSIZE` where you can
  2928. copy a string to be added to buffer `B` (see |luaL_Buffer|).
  2929. After copying the string into this space you must call `luaL_addsize`
  2930. (see |luaL_addsize()|) with the size of the string to actually
  2931. add it to the buffer.
  2932. luaL_pushresult *luaL_pushresult()*
  2933. >c
  2934. void luaL_pushresult (luaL_Buffer *B);
  2935. <
  2936. Finishes the use of buffer `B` leaving the final string on the top of
  2937. the stack.
  2938. luaL_ref *luaL_ref()*
  2939. >c
  2940. int luaL_ref (lua_State *L, int t);
  2941. <
  2942. Creates and returns a `reference`, in the table at index `t`, for the
  2943. object at the top of the stack (and pops the object).
  2944. A reference is a unique integer key. As long as you do not manually
  2945. add integer keys into table `t`, `luaL_ref` ensures the uniqueness of
  2946. the key it returns. You can retrieve an object referred by reference
  2947. `r` by calling `lua_rawgeti(L, t, r)` (see |lua_rawgeti()|).
  2948. Function `luaL_unref` (see |luaL_unref()|) frees a reference and
  2949. its associated object.
  2950. If the object at the top of the stack is `nil`, `luaL_ref` returns the
  2951. constant `LUA_REFNIL`. The constant `LUA_NOREF` is guaranteed to be
  2952. different from any reference returned by `luaL_ref`.
  2953. luaL_Reg *luaL_Reg*
  2954. >c
  2955. typedef struct luaL_Reg {
  2956. const char *name;
  2957. lua_CFunction func;
  2958. } luaL_Reg;
  2959. <
  2960. Type for arrays of functions to be registered by `luaL_register` (see
  2961. |luaL_register()|). `name` is the function name and `func` is a
  2962. pointer to the function. Any array of `luaL_Reg` must end with a
  2963. sentinel entry in which both `name` and `func` are `NULL`.
  2964. luaL_register *luaL_register()*
  2965. >c
  2966. void luaL_register (lua_State *L,
  2967. const char *libname,
  2968. const luaL_Reg *l);
  2969. <
  2970. Opens a library.
  2971. When called with `libname` equal to `NULL`, it simply registers all
  2972. functions in the list `l` (see |luaL_Reg|) into the table on
  2973. the top of the stack.
  2974. When called with a non-null `libname`, `luaL_register` creates a new
  2975. table `t`, sets it as the value of the global variable `libname`, sets
  2976. it as the value of `package.loaded[libname]`, and registers on it all
  2977. functions in the list `l`. If there is a table in
  2978. `package.loaded[libname]` or in variable `libname`, reuses this table
  2979. instead of creating a new one.
  2980. In any case the function leaves the table on the top of the stack.
  2981. luaL_typename *luaL_typename()*
  2982. >c
  2983. const char *luaL_typename (lua_State *L, int idx);
  2984. <
  2985. Returns the name of the type of the value at index `idx`.
  2986. luaL_typerror *luaL_typerror()*
  2987. >c
  2988. int luaL_typerror (lua_State *L, int narg, const char *tname);
  2989. <
  2990. Generates an error with a message like the following:
  2991. `location` `: bad argument` `narg` `to` `'func'` `(` `tname`
  2992. `expected, got` `rt` `)`
  2993. where `location` is produced by `luaL_where` (see
  2994. |luaL_where()|), `func` is the name of the current function, and
  2995. `rt` is the type name of the actual argument.
  2996. luaL_unref *luaL_unref()*
  2997. >c
  2998. void luaL_unref (lua_State *L, int t, int ref);
  2999. <
  3000. Releases reference `ref` from the table at index `t` (see
  3001. |luaL_ref()|). The entry is removed from the table, so that the
  3002. referred object can be collected. The reference `ref` is also freed to
  3003. be used again.
  3004. If `ref` is `LUA_NOREF` or `LUA_REFNIL`, `luaL_unref` does nothing.
  3005. luaL_where *luaL_where()*
  3006. >c
  3007. void luaL_where (lua_State *L, int lvl);
  3008. <
  3009. Pushes onto the stack a string identifying the current position of the
  3010. control at level `lvl` in the call stack. Typically this string has
  3011. the following format:
  3012. `chunkname:currentline:`
  3013. Level 0 is the running function, level 1 is the function that called
  3014. the running function, etc.
  3015. This function is used to build a prefix for error messages.
  3016. ==============================================================================
  3017. 5 STANDARD LIBRARIES *lua-lib*
  3018. The standard libraries provide useful functions that are implemented directly
  3019. through the C API. Some of these functions provide essential services to the
  3020. language (e.g., `type` and `getmetatable`); others provide access to "outside"
  3021. services (e.g., I/O); and others could be implemented in Lua itself, but are
  3022. quite useful or have critical performance requirements that deserve an
  3023. implementation in C (e.g., `sort`).
  3024. All libraries are implemented through the official C API and are provided as
  3025. separate C modules. Currently, Lua has the following standard libraries:
  3026. - basic library;
  3027. - package library;
  3028. - string manipulation;
  3029. - table manipulation;
  3030. - mathematical functions (sin, log, etc.);
  3031. - input and output;
  3032. - operating system facilities;
  3033. - debug facilities.
  3034. Except for the basic and package libraries, each library provides all its
  3035. functions as fields of a global table or as methods of its objects.
  3036. *lua-openlibs*
  3037. To have access to these libraries, the C host program should call the
  3038. `luaL_openlibs` function, which opens all standard libraries (see
  3039. |luaL_openlibs()|). Alternatively, the host program can open the libraries
  3040. individually by calling `luaopen_base` (for the basic library),
  3041. `luaopen_package` (for the package library), `luaopen_string` (for the string
  3042. library), `luaopen_table` (for the table library), `luaopen_math` (for the
  3043. mathematical library), `luaopen_io` (for the I/O and the Operating System
  3044. libraries), and `luaopen_debug` (for the debug library). These functions are
  3045. declared in `lualib.h` and should not be called directly: you must call them
  3046. like any other Lua C function, e.g., by using `lua_call` (see |lua_call()|).
  3047. ==============================================================================
  3048. 5.1 Basic Functions *lua-lib-core*
  3049. The basic library provides some core functions to Lua. If you do not include
  3050. this library in your application, you should check carefully whether you need
  3051. to provide implementations for some of its facilities.
  3052. assert({v} [, {message}]) *assert()*
  3053. Issues an error when the value of its argument `v` is false (i.e., `nil` or
  3054. `false`); otherwise, returns all its arguments. `message` is an error message;
  3055. when absent, it defaults to "assertion failed!"
  3056. collectgarbage({opt} [, {arg}]) *collectgarbage()*
  3057. This function is a generic interface to the garbage collector. It
  3058. performs different functions according to its first argument, {opt}:
  3059. `"stop"` stops the garbage collector.
  3060. `"restart"` restarts the garbage collector.
  3061. `"collect"` performs a full garbage-collection cycle.
  3062. `"count"` returns the total memory in use by Lua (in Kbytes).
  3063. `"step"` performs a garbage-collection step. The step "size" is
  3064. controlled by {arg} (larger values mean more steps) in a
  3065. non-specified way. If you want to control the step size
  3066. you must experimentally tune the value of {arg}. Returns
  3067. `true` if the step finished a collection cycle.
  3068. `"setpause"` sets {arg} /100 as the new value for the `pause` of
  3069. the collector (see |lua-gc|).
  3070. `"setstepmul"` sets {arg} /100 as the new value for the `step
  3071. multiplier` of the collector (see |lua-gc|).
  3072. dofile({filename}) *dofile()*
  3073. Opens the named file and executes its contents as a Lua chunk. When
  3074. called without arguments, `dofile` executes the contents of the
  3075. standard input (`stdin`). Returns all values returned by the chunk. In
  3076. case of errors, `dofile` propagates the error to its caller (that is,
  3077. `dofile` does not run in protected mode).
  3078. error({message} [, {level}]) *error()*
  3079. Terminates the last protected function called and returns `message` as
  3080. the error message. Function {error} never returns.
  3081. Usually, {error} adds some information about the error position at the
  3082. beginning of the message. The {level} argument specifies how to get
  3083. the error position. With level 1 (the default), the error position is
  3084. where the {error} function was called. Level 2 points the error to
  3085. where the function that called {error} was called; and so on. Passing
  3086. a level 0 avoids the addition of error position information to the
  3087. message.
  3088. _G *_G*
  3089. A global variable (not a function) that holds the global environment
  3090. (that is, `_G._G = _G`). Lua itself does not use this variable;
  3091. changing its value does not affect any environment, nor vice-versa.
  3092. (Use `setfenv` to change environments.)
  3093. getfenv({f}) *getfenv()*
  3094. Returns the current environment in use by the function. {f} can be a
  3095. Lua function or a number that specifies the function at that stack
  3096. level: Level 1 is the function calling `getfenv`. If the given
  3097. function is not a Lua function, or if {f} is 0, `getfenv` returns the
  3098. global environment. The default for {f} is 1.
  3099. getmetatable({object}) *getmetatable()*
  3100. If {object} does not have a metatable, returns `nil`. Otherwise, if
  3101. the object's metatable has a `"__metatable"` field, returns the
  3102. associated value. Otherwise, returns the metatable of the given
  3103. object.
  3104. ipairs({t}) *ipairs()*
  3105. Returns three values: an |iterator| function, the table {t}, and 0, so
  3106. that the construction
  3107. `for i,v in ipairs(t) do` `body` `end`
  3108. will iterate over the pairs (`1,t[1]`), (`2,t[2]`), ..., up to the
  3109. first integer key absent from the table.
  3110. load({func} [, {chunkname}]) *load()*
  3111. Loads a chunk using function {func} to get its pieces. Each call to
  3112. {func} must return a string that concatenates with previous results. A
  3113. return of `nil` (or no value) signals the end of the chunk.
  3114. If there are no errors, returns the compiled chunk as a function;
  3115. otherwise, returns `nil` plus the error message. The environment of
  3116. the returned function is the global environment.
  3117. {chunkname} is used as the chunk name for error messages and debug
  3118. information.
  3119. loadfile([{filename}]) *loadfile()*
  3120. Similar to `load` (see |load()|), but gets the chunk from file
  3121. {filename} or from the standard input, if no file name is given.
  3122. loadstring({string} [, {chunkname}]) *loadstring()*
  3123. Similar to `load` (see |load()|), but gets the chunk from the
  3124. given {string}.
  3125. To load and run a given string, use the idiom
  3126. >lua
  3127. assert(loadstring(s))()
  3128. <
  3129. next({table} [, {index}]) *next()*
  3130. Allows a program to traverse all fields of a table. Its first argument
  3131. is a table and its second argument is an index in this table. `next`
  3132. returns the next index of the table and its associated value. When
  3133. called with `nil` as its second argument, `next` returns an initial
  3134. index and its associated value. When called with the last index, or
  3135. with `nil` in an empty table, `next` returns `nil`. If the second
  3136. argument is absent, then it is interpreted as `nil`. In particular,
  3137. you can use `next(t)` to check whether a table is empty.
  3138. The order in which the indices are enumerated is not specified, even
  3139. for numeric indices. (To traverse a table in numeric order, use a
  3140. numerical `for` or the |ipairs()| function.)
  3141. The behavior of `next` is `undefined` if, during the traversal, you
  3142. assign any value to a non-existent field in the table. You may however
  3143. modify existing fields. In particular, you may clear existing fields.
  3144. pairs({t}) *pairs()*
  3145. Returns three values: the |next()| function, the table {t}, and `nil`,
  3146. so that the construction
  3147. `for k,v in pairs(t) do` `body` `end`
  3148. will iterate over all key-value pairs of table {t}.
  3149. pcall({f}, {arg1}, {...}) *pcall()*
  3150. Calls function {f} with the given arguments in `protected mode`. This
  3151. means that any error inside {f} is not propagated; instead, `pcall`
  3152. catches the error and returns a status code. Its first result is the
  3153. status code (a boolean), which is `true` if the call succeeds without
  3154. errors. In such case, `pcall` also returns all results from the call,
  3155. after this first result. In case of any error, `pcall` returns `false`
  3156. plus the error message.
  3157. print({...}) *print()*
  3158. Receives any number of arguments, and prints their values to `stdout`,
  3159. using the `tostring` |tostring()| function to convert them to
  3160. strings. `print` is not intended for formatted output, but only as a
  3161. quick way to show a value, typically for debugging. For formatted
  3162. output, use `string.format` (see |string.format()|).
  3163. rawequal({v1}, {v2}) *rawequal()*
  3164. Checks whether {v1} is equal to {v2}, without invoking any metamethod.
  3165. Returns a boolean.
  3166. rawget({table}, {index}) *rawget()*
  3167. Gets the real value of `table[index]`, without invoking any
  3168. metamethod. {table} must be a table; {index} may be any value.
  3169. rawset({table}, {index}, {value}) *rawset()*
  3170. Sets the real value of `table[index]` to {value}, without invoking any
  3171. metamethod. {table} must be a table, {index} any value different from
  3172. `nil`, and {value} any Lua value.
  3173. This function returns {table}.
  3174. select({index}, {...}) *select()*
  3175. If {index} is a number, returns all arguments after argument number
  3176. {index}. Otherwise, {index} must be the string `"#"`, and `select`
  3177. returns the total number of extra arguments it received.
  3178. setfenv({f}, {table}) *setfenv()*
  3179. Sets the environment to be used by the given function. {f} can be a
  3180. Lua function or a number that specifies the function at that stack
  3181. level: Level 1 is the function calling `setfenv`. `setfenv` returns
  3182. the given function.
  3183. As a special case, when {f} is 0 `setfenv` changes the environment of
  3184. the running thread. In this case, `setfenv` returns no values.
  3185. setmetatable({table}, {metatable}) *setmetatable()*
  3186. Sets the metatable for the given table. (You cannot change the
  3187. metatable of other types from Lua, only from C.) If {metatable} is
  3188. `nil`, removes the metatable of the given table. If the original
  3189. metatable has a `"__metatable"` field, raises an error.
  3190. This function returns {table}.
  3191. tonumber({e} [, {base}]) *tonumber()*
  3192. Tries to convert its argument to a number. If the argument is already
  3193. a number or a string convertible to a number, then `tonumber` returns
  3194. this number; otherwise, it returns `nil`.
  3195. An optional argument specifies the base to interpret the numeral. The
  3196. base may be any integer between 2 and 36, inclusive. In bases above
  3197. 10, the letter `A` (in either upper or lower case) represents 10, `B`
  3198. represents 11, and so forth, with `Z'` representing 35. In base 10
  3199. (the default), the number may have a decimal part, as well as an
  3200. optional exponent part (see |lua-lexical|). In other bases,
  3201. only unsigned integers are accepted.
  3202. tostring({e}) *tostring()*
  3203. Receives an argument of any type and converts it to a string in a
  3204. reasonable format. For complete control of how numbers are converted,
  3205. use `string.format` (see |string.format()|).
  3206. *__tostring*
  3207. If the metatable of {e} has a `"__tostring"` field, `tostring` calls
  3208. the corresponding value with {e} as argument, and uses the result of
  3209. the call as its result.
  3210. type({v}) *lua-type()*
  3211. Returns the type of its only argument, coded as a string. The possible
  3212. results of this function are `"nil"` (a string, not the value `nil`),
  3213. `"number"`, `"string"`, `"boolean`, `"table"`, `"function"`,
  3214. `"thread"`, and `"userdata"`.
  3215. unpack({list} [, {i} [, {j}]]) *unpack()*
  3216. Returns the elements from the given table. This function is equivalent
  3217. to
  3218. >lua
  3219. return list[i], list[i+1], ..., list[j]
  3220. <
  3221. except that the above code can be written only for a fixed number of
  3222. elements. By default, {i} is 1 and {j} is the length of the list, as
  3223. defined by the length operator (see |lua-length|).
  3224. _VERSION *_VERSION*
  3225. A global variable (not a function) that holds a string containing the
  3226. current interpreter version. The current contents of this string is
  3227. `"Lua 5.1"` .
  3228. xpcall({f}, {err}) *xpcall()*
  3229. This function is similar to `pcall` (see |pcall()|), except that you
  3230. can set a new error handler.
  3231. `xpcall` calls function {f} in protected mode, using {err} as the
  3232. error handler. Any error inside {f} is not propagated; instead,
  3233. `xpcall` catches the error, calls the {err} function with the original
  3234. error object, and returns a status code. Its first result is the
  3235. status code (a boolean), which is true if the call succeeds without
  3236. errors. In this case, `xpcall` also returns all results from the call,
  3237. after this first result. In case of any error, `xpcall` returns
  3238. `false` plus the result from {err}.
  3239. ==============================================================================
  3240. 5.2 Coroutine Manipulation *lua-lib-coroutine*
  3241. The operations related to coroutines comprise a sub-library of the basic
  3242. library and come inside the table `coroutine`. See |lua-coroutine| for a
  3243. general description of coroutines.
  3244. coroutine.create({f}) *coroutine.create()*
  3245. Creates a new coroutine, with body {f}. {f} must be a Lua function.
  3246. Returns this new coroutine, an object with type `"thread"`.
  3247. coroutine.resume({co} [, {val1}, {...}]) *coroutine.resume()*
  3248. Starts or continues the execution of coroutine {co}. The first time
  3249. you resume a coroutine, it starts running its body. The values {val1},
  3250. {...} are passed as arguments to the body function. If the coroutine has
  3251. yielded, `resume` restarts it; the values {val1}, {...} are passed as
  3252. the results from the yield.
  3253. If the coroutine runs without any errors, `resume` returns `true` plus
  3254. any values passed to `yield` (if the coroutine yields) or any values
  3255. returned by the body function(if the coroutine terminates). If there
  3256. is any error, `resume` returns `false` plus the error message.
  3257. coroutine.running() *coroutine.running()*
  3258. Returns the running coroutine, or `nil` when called by the main
  3259. thread.
  3260. coroutine.status({co}) *coroutine.status()*
  3261. Returns the status of coroutine {co}, as a string: `"running"`, if the
  3262. coroutine is running (that is, it called `status`); `"suspended"`, if
  3263. the coroutine is suspended in a call to `yield`, or if it has not
  3264. started running yet; `"normal"` if the coroutine is active but not
  3265. running (that is, it has resumed another coroutine); and `"dead"` if
  3266. the coroutine has finished its body function, or if it has stopped
  3267. with an error.
  3268. coroutine.wrap({f}) *coroutine.wrap()*
  3269. Creates a new coroutine, with body {f}. {f} must be a Lua function.
  3270. Returns a function that resumes the coroutine each time it is called.
  3271. Any arguments passed to the function behave as the extra arguments to
  3272. `resume`. Returns the same values returned by `resume`, except the
  3273. first boolean. In case of error, propagates the error.
  3274. coroutine.yield({...}) *coroutine.yield()*
  3275. Suspends the execution of the calling coroutine. The coroutine cannot
  3276. be running a C function, a metamethod, or an |iterator|. Any arguments
  3277. to `yield` are passed as extra results to `resume`.
  3278. ==============================================================================
  3279. 5.3 Modules *lua-modules*
  3280. The package library provides basic facilities for loading and building modules
  3281. in Lua. It exports two of its functions directly in the global environment:
  3282. `require` and `module` (see |require()| and |module()|). Everything else is
  3283. exported in a table `package`.
  3284. module({name} [, {...}]) *module()*
  3285. Creates a module. If there is a table in `package.loaded[name]`, this
  3286. table is the module. Otherwise, if there is a global table `t` with
  3287. the given name, this table is the module. Otherwise creates a new
  3288. table `t` and sets it as the value of the global {name} and the value
  3289. of `package.loaded[name]`. This function also initializes `t._NAME`
  3290. with the given name, `t._M` with the module (`t` itself), and
  3291. `t._PACKAGE` with the package name (the full module name minus last
  3292. component; see below). Finally, `module` sets `t` as the new
  3293. environment of the current function and the new value of
  3294. `package.loaded[name]`, so that |require()| returns `t`.
  3295. If {name} is a compound name (that is, one with components separated
  3296. by dots), `module` creates (or reuses, if they already exist) tables
  3297. for each component. For instance, if {name} is `a.b.c`, then `module`
  3298. stores the module table in field `c` of field `b` of global `a`.
  3299. This function may receive optional `options` after the module name,
  3300. where each option is a function to be applied over the module.
  3301. require({modname}) *require()*
  3302. Loads the given module. The function starts by looking into the
  3303. `package.loaded` table to determine whether {modname} is already
  3304. loaded. If it is, then `require` returns the value stored at
  3305. `package.loaded[modname]`. Otherwise, it tries to find a `loader` for
  3306. the module.
  3307. To find a loader, first `require` queries `package.preload[modname]`.
  3308. If it has a value, this value (which should be a function) is the
  3309. loader. Otherwise `require` searches for a Lua loader using the path
  3310. stored in `package.path`. If that also fails, it searches for a C
  3311. loader using the path stored in `package.cpath`. If that also fails,
  3312. it tries an `all-in-one` loader (see below).
  3313. When loading a C library, `require` first uses a dynamic link facility
  3314. to link the application with the library. Then it tries to find a C
  3315. function inside this library to be used as the loader. The name of
  3316. this C function is the string `"luaopen_"` concatenated with a copy of
  3317. the module name where each dot is replaced by an underscore. Moreover,
  3318. if the module name has a hyphen, its prefix up to (and including) the
  3319. first hyphen is removed. For instance, if the module name is
  3320. `a.v1-b.c`, the function name will be `luaopen_b_c`.
  3321. If `require` finds neither a Lua library nor a C library for a module,
  3322. it calls the `all-in-one loader`. This loader searches the C path for
  3323. a library for the root name of the given module. For instance, when
  3324. requiring `a.b.c`, it will search for a C library for `a`. If found,
  3325. it looks into it for an open function for the submodule; in our
  3326. example, that would be `luaopen_a_b_c`. With this facility, a package
  3327. can pack several C submodules into one single library, with each
  3328. submodule keeping its original open function.
  3329. Once a loader is found, `require` calls the loader with a single
  3330. argument, {modname}. If the loader returns any value, `require`
  3331. assigns the returned value to `package.loaded[modname]`. If the loader
  3332. returns no value and has not assigned any value to
  3333. `package.loaded[modname]`, then `require` assigns `true` to this
  3334. entry. In any case, `require` returns the final value of
  3335. `package.loaded[modname]`.
  3336. If there is any error loading or running the module, or if it cannot
  3337. find any loader for the module, then `require` signals an error.
  3338. package.cpath *package.cpath*
  3339. The path used by `require` to search for a C loader.
  3340. Lua initializes the C path `package.cpath` in the same way it
  3341. initializes the Lua path `package.path`, using the environment
  3342. variable `LUA_CPATH` (plus another default path defined in
  3343. `luaconf.h`).
  3344. package.loaded *package.loaded()*
  3345. A table used by `require` to control which modules are already loaded.
  3346. When you require a module `modname` and `package.loaded[modname]` is
  3347. not false, `require` simply returns the value stored there.
  3348. package.loadlib({libname}, {funcname}) *package.loadlib()*
  3349. Dynamically links the host program with the C library {libname}.
  3350. Inside this library, looks for a function {funcname} and returns this
  3351. function as a C function. (So, {funcname} must follow the protocol
  3352. (see |lua_CFunction|)).
  3353. This is a low-level function. It completely bypasses the package and
  3354. module system. Unlike `require`, it does not perform any path
  3355. searching and does not automatically adds extensions. {libname} must
  3356. be the complete file name of the C library, including if necessary a
  3357. path and extension. {funcname} must be the exact name exported by the
  3358. C library (which may depend on the C compiler and linker used).
  3359. This function is not supported by ANSI C. As such, it is only
  3360. available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD,
  3361. plus other Unix systems that support the `dlfcn` standard).
  3362. package.path *package.path*
  3363. The path used by `require` to search for a Lua loader.
  3364. At start-up, Lua initializes this variable with the value of the
  3365. environment variable `LUA_PATH` or with a default path defined in
  3366. `luaconf.h`, if the environment variable is not defined. Any `";;"` in
  3367. the value of the environment variable is replaced by the default path.
  3368. A path is a sequence of `templates` separated by semicolons. For each
  3369. template, `require` will change each interrogation mark in the
  3370. template by `filename`, which is `modname` with each dot replaced by a
  3371. "directory separator" (such as `"/"` in Unix); then it will try to
  3372. load the resulting file name. So, for instance, if the Lua path is
  3373. >
  3374. "./?.lua;./?.lc;/usr/local/?/init.lua"
  3375. <
  3376. the search for a Lua loader for module `foo` will try to load the
  3377. files `./foo.lua`, `./foo.lc`, and `/usr/local/foo/init.lua`, in that
  3378. order.
  3379. package.preload *package.preload()*
  3380. A table to store loaders for specific modules (see |require()|).
  3381. package.seeall({module}) *package.seeall()*
  3382. Sets a metatable for {module} with its `__index` field referring to
  3383. the global environment, so that this module inherits values from the
  3384. global environment. To be used as an option to function {module}.
  3385. ==============================================================================
  3386. 5.4 String Manipulation *lua-lib-string*
  3387. This library provides generic functions for string manipulation, such as
  3388. finding and extracting substrings, and pattern matching. When indexing a
  3389. string in Lua, the first character is at position 1 (not at 0, as in C).
  3390. Indices are allowed to be negative and are interpreted as indexing backwards,
  3391. from the end of the string. Thus, the last character is at position -1, and
  3392. so on.
  3393. The string library provides all its functions inside the table `string`.
  3394. It also sets a metatable for strings where the `__index` field points to the
  3395. `string` table. Therefore, you can use the string functions in object-oriented
  3396. style. For instance, `string.byte(s, i)` can be written as `s:byte(i)`.
  3397. string.byte({s} [, {i} [, {j}]]) *string.byte()*
  3398. Returns the internal numerical codes of the characters `s[i]`,
  3399. `s[i+1]`,..., `s[j]`. The default value for {i} is 1; the default
  3400. value for {j} is {i}.
  3401. Note that numerical codes are not necessarily portable across
  3402. platforms.
  3403. string.char({...}) *string.char()*
  3404. Receives zero or more integers. Returns a string with length equal to
  3405. the number of arguments, in which each character has the internal
  3406. numerical code equal to its correspondent argument.
  3407. Note that numerical codes are not necessarily portable across
  3408. platforms.
  3409. string.dump({function}) *string.dump()*
  3410. Returns a string containing a binary representation of the given
  3411. function, so that a later |loadstring()| on this string returns a
  3412. copy of the function. {function} must be a Lua function without
  3413. upvalues.
  3414. string.find({s}, {pattern} [, {init} [, {plain}]]) *string.find()*
  3415. Looks for the first match of {pattern} in the string {s}. If it finds
  3416. a match, then {find} returns the indices of {s} where this occurrence
  3417. starts and ends; otherwise, it returns `nil`. A third, optional
  3418. numerical argument {init} specifies where to start the search; its
  3419. default value is 1 and may be negative. A value of {true} as a fourth,
  3420. optional argument {plain} turns off the pattern matching facilities,
  3421. so the function does a plain "find substring" operation, with no
  3422. characters in {pattern} being considered "magic". Note that if {plain}
  3423. is given, then {init} must be given as well.
  3424. If the pattern has captures, then in a successful match the captured
  3425. values are also returned, after the two indices.
  3426. string.format({formatstring}, {...}) *string.format()*
  3427. Returns a formatted version of its variable number of arguments
  3428. following the description given in its first argument (which must be a
  3429. string). The format string follows the same rules as the `printf`
  3430. family of standard C functions. The only differences are that the
  3431. options/modifiers `*`, `l`, `L`, `n`, `p`, and `h` are not supported
  3432. and that there is an extra option, `q`. The `q` option formats a
  3433. string in a form suitable to be safely read back by the Lua
  3434. interpreter: the string is written between double quotes, and all
  3435. double quotes, newlines, embedded zeros, and backslashes in the string
  3436. are correctly escaped when written. For instance, the call
  3437. >lua
  3438. string.format('%q', 'a string with "quotes" and \n new line')
  3439. <
  3440. will produce the string:
  3441. >lua
  3442. "a string with \"quotes\" and \
  3443. new line"
  3444. <
  3445. The options `c`, `d`, `E`, `e`, `f`, `g`, `G`, `i`, `o`, `u`, `X`, and
  3446. `x` all expect a number as argument, whereas `q` and `s` expect a
  3447. string.
  3448. This function does not accept string values containing embedded zeros.
  3449. string.gmatch({s}, {pattern}) *string.gmatch()*
  3450. Returns an |iterator| function that, each time it is called, returns the
  3451. next captures from {pattern} over string {s}.
  3452. If {pattern} specifies no captures, then the whole match is produced
  3453. in each call.
  3454. As an example, the following loop
  3455. >lua
  3456. s = "hello world from Lua"
  3457. for w in string.gmatch(s, "%a+") do
  3458. print(w)
  3459. end
  3460. <
  3461. will iterate over all the words from string {s}, printing one per
  3462. line. The next example collects all pairs `key=value` from the given
  3463. string into a table:
  3464. >lua
  3465. t = {}
  3466. s = "from=world, to=Lua"
  3467. for k, v in string.gmatch(s, "(%w+)=(%w+)") do
  3468. t[k] = v
  3469. end
  3470. <
  3471. string.gsub({s}, {pattern}, {repl} [, {n}]) *string.gsub()*
  3472. Returns a copy of {s} in which all occurrences of the {pattern} have
  3473. been replaced by a replacement string specified by {repl}, which may
  3474. be a string, a table, or a function. `gsub` also returns, as its
  3475. second value, the total number of substitutions made.
  3476. If {repl} is a string, then its value is used for replacement. The
  3477. character `%` works as an escape character: any sequence in {repl} of
  3478. the form `%n`, with {n} between 1 and 9, stands for the value of the
  3479. {n} -th captured substring (see below). The sequence `%0` stands for
  3480. the whole match. The sequence `%%` stands for a single `%`.
  3481. If {repl} is a table, then the table is queried for every match, using
  3482. the first capture as the key; if the pattern specifies no captures,
  3483. then the whole match is used as the key.
  3484. If {repl} is a function, then this function is called every time a
  3485. match occurs, with all captured substrings passed as arguments, in
  3486. order; if the pattern specifies no captures, then the whole match is
  3487. passed as a sole argument.
  3488. If the value returned by the table query or by the function call is a
  3489. string or a number, then it is used as the replacement string;
  3490. otherwise, if it is `false` or `nil`, then there is no replacement
  3491. (that is, the original match is kept in the string).
  3492. The optional last parameter {n} limits the maximum number of
  3493. substitutions to occur. For instance, when {n} is 1 only the first
  3494. occurrence of `pattern` is replaced.
  3495. Here are some examples:
  3496. >lua
  3497. x = string.gsub("hello world", "(%w+)", "%1 %1")
  3498. --> x="hello hello world world"
  3499. x = string.gsub("hello world", "%w+", "%0 %0", 1)
  3500. --> x="hello hello world"
  3501. x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
  3502. --> x="world hello Lua from"
  3503. x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
  3504. --> x="home = /home/roberto, user = roberto"
  3505. x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
  3506. return loadstring(s)()
  3507. end)
  3508. --> x="4+5 = 9"
  3509. local t = {name="lua", version="5.1"}
  3510. x = string.gsub("$name%-$version.tar.gz", "%$(%w+)", t)
  3511. --> x="lua-5.1.tar.gz"
  3512. <
  3513. string.len({s}) *string.len()*
  3514. Receives a string and returns its length. The empty string `""` has
  3515. length 0. Embedded zeros are counted, so `"a\000b\000c"` has length 5.
  3516. string.lower({s}) *string.lower()*
  3517. Receives a string and returns a copy of this string with all uppercase
  3518. letters changed to lowercase. All other characters are left unchanged.
  3519. The definition of what an uppercase letter is depends on the current
  3520. locale.
  3521. string.match({s}, {pattern} [, {init}]) *string.match()*
  3522. Looks for the first `match` of {pattern} in the string {s}. If it
  3523. finds one, then `match` returns the captures from the pattern;
  3524. otherwise it returns `nil`. If {pattern} specifies no captures, then
  3525. the whole match is returned. A third, optional numerical argument
  3526. {init} specifies where to start the search; its default value is 1 and
  3527. may be negative.
  3528. string.rep({s}, {n}) *string.rep()*
  3529. Returns a string that is the concatenation of {n} copies of the string
  3530. {s}.
  3531. string.reverse({s}) *string.reverse()*
  3532. Returns a string that is the string {s} reversed.
  3533. string.sub({s}, {i} [, {j}]) *string.sub()*
  3534. Returns the substring of {s} that starts at {i} and continues until
  3535. {j}; {i} and {j} may be negative. If {j} is absent, then it is assumed
  3536. to be equal to `-1` (which is the same as the string length). In
  3537. particular, the call `string.sub(s,1,j)` returns a prefix of {s} with
  3538. length {j}, and `string.sub(s,-i)` returns a suffix of {s} with length
  3539. {i}.
  3540. string.upper({s}) *string.upper()*
  3541. Receives a string and returns a copy of that string with all lowercase
  3542. letters changed to uppercase. All other characters are left unchanged.
  3543. The definition of what a lowercase letter is depends on the current
  3544. locale.
  3545. ------------------------------------------------------------------------------
  3546. 5.4.1 Patterns *lua-patterns*
  3547. A character class is used to represent a set of characters. The following
  3548. combinations are allowed in describing a character class:
  3549. - `x` (where `x` is not one of the magic characters `^$()%.[]*+-?`)
  3550. represents the character `x` itself.
  3551. - `.` (a dot) represents all characters.
  3552. - `%a` represents all letters.
  3553. - `%c` represents all control characters.
  3554. - `%d` represents all digits.
  3555. - `%l` represents all lowercase letters.
  3556. - `%p` represents all punctuation characters.
  3557. - `%s` represents all space characters.
  3558. - `%u` represents all uppercase letters.
  3559. - `%w` represents all alphanumeric characters.
  3560. - `%x` represents all hexadecimal digits.
  3561. - `%z` represents the character with representation `0`.
  3562. - `%x` (where `x` is any non-alphanumeric character) represents the
  3563. character `x`. This is the standard way to escape the magic
  3564. characters. Any punctuation character (even the non-magic) can be
  3565. preceded by a `%` when used to represent itself in a pattern.
  3566. - `[set]` represents the class which is the union of all characters in
  3567. `set`. A range of characters may be specified by separating the end
  3568. characters of the range with a `-`. All classes `%x` described
  3569. above may also be used as components in `set`. All other characters
  3570. in `set` represent themselves. For example, `[%w_]` (or `[_%w]`)
  3571. represents all alphanumeric characters plus the underscore, `[0-7]`
  3572. represents the octal digits, and `[0-7%l%-]` represents the octal
  3573. digits plus the lowercase letters plus the `-` character.
  3574. The interaction between ranges and classes is not defined. Therefore,
  3575. patterns like `[%a-z]` or `[a-%%]` have no meaning.
  3576. - `[^set]` represents the complement of `set`, where `set` is interpreted
  3577. as above.
  3578. For all classes represented by single letters (`%a`, `%c`, etc.), the
  3579. corresponding uppercase letter represents the complement of the class. For
  3580. instance, `%S` represents all non-space characters.
  3581. The definitions of letter, space, and other character groups depend on the
  3582. current locale. In particular, the class `[a-z]` may not be equivalent to `%l`.
  3583. PATTERN ITEM *lua-patternitem*
  3584. A pattern item may be
  3585. - a single character class, which matches any single character in the
  3586. class;
  3587. - a single character class followed by `*`, which matches 0 or more
  3588. repetitions of characters in the class. These repetition items will
  3589. always match the longest possible sequence;
  3590. - a single character class followed by `+`, which matches 1 or more
  3591. repetitions of characters in the class. These repetition items will
  3592. always match the longest possible sequence;
  3593. - a single character class followed by `-`, which also matches 0 or
  3594. more repetitions of characters in the class. Unlike `*`, these
  3595. repetition items will always match the shortest possible sequence;
  3596. - a single character class followed by `?`, which matches 0 or 1
  3597. occurrences of a character in the class;
  3598. - `%n`, for `n` between 1 and 9; such item matches a substring equal to the
  3599. `n` -th captured string (see below);
  3600. - `%bxy`, where `x` and `y` are two distinct characters; such item matches
  3601. strings that start with `x`, end with `y`, and where the `x` and `y`
  3602. are balanced. This means that, if one reads the string from left to
  3603. right, counting `+1` for an `x` and `-1` for a `y`, the ending `y` is the first
  3604. `y` where the count reaches 0. For instance, the item `%b()` matches
  3605. expressions with balanced parentheses.
  3606. PATTERN *lua-pattern*
  3607. A pattern is a sequence of pattern items. A `^` at the beginning of a pattern
  3608. anchors the match at the beginning of the subject string. A `$` at the end of
  3609. a pattern anchors the match at the end of the subject string. At other
  3610. positions, `^` and `$` have no special meaning and represent themselves.
  3611. CAPTURES *lua-capture*
  3612. A pattern may contain sub-patterns enclosed in parentheses; they describe
  3613. captures. When a match succeeds, the substrings of the subject string that
  3614. match captures are stored (captured) for future use. Captures are numbered
  3615. according to their left parentheses. For instance, in the pattern
  3616. `"(a*(.)%w(%s*))"`, the part of the string matching `"a*(.)%w(%s*)"` is stored
  3617. as the first capture (and therefore has number 1); the character matching `.`
  3618. is captured with number 2, and the part matching `%s*` has number 3.
  3619. As a special case, the empty capture `()` captures the current string position
  3620. (a number). For instance, if we apply the pattern `"()aa()"` on the
  3621. string `"flaaap"`, there will be two captures: 3 and 5.
  3622. A pattern cannot contain embedded zeros. Use `%z` instead.
  3623. ==============================================================================
  3624. 5.5 Table Manipulation *lua-lib-table*
  3625. This library provides generic functions for table manipulation. It provides
  3626. all its functions inside the table `table`.
  3627. Most functions in the table library assume that the table represents an array
  3628. or a list. For those functions, when we talk about the "length" of a table we
  3629. mean the result of the length operator.
  3630. table.concat({table} [, {sep} [, {i} [, {j}]]]) *table.concat()*
  3631. Given an array where all elements are strings or numbers, returns
  3632. `table[i]..sep..table[i+1] ... sep..table[j]`. The default value for
  3633. {sep} is the empty string, the default for {i} is 1, and the default
  3634. for {j} is the length of the table. If {i} is greater than {j},
  3635. returns the empty string.
  3636. table.foreach({table}, {f}) *table.foreach()*
  3637. Executes the given {f} over all elements of {table}. For each element,
  3638. {f} is called with the index and respective value as arguments. If {f}
  3639. returns a non-`nil` value, then the loop is broken, and this value is
  3640. returned as the final value of `table.foreach`.
  3641. See |next()| for extra information about table traversals.
  3642. table.foreachi({table}, {f}) *table.foreachi()*
  3643. Executes the given {f} over the numerical indices of {table}. For each
  3644. index, {f} is called with the index and respective value as arguments.
  3645. Indices are visited in sequential order, from 1 to `n`, where `n` is
  3646. the length of the table. If {f} returns a non-`nil` value, then the
  3647. loop is broken and this value is returned as the result of
  3648. `table.foreachi`.
  3649. table.insert({table}, [{pos},] {value}) *table.insert()*
  3650. Inserts element {value} at position {pos} in {table}, shifting up
  3651. other elements to open space, if necessary. The default value for
  3652. {pos} is `n+1`, where `n` is the length of the table (see
  3653. |lua-length|), so that a call `table.insert(t,x)` inserts `x`
  3654. at the end of table `t`.
  3655. table.maxn({table}) *table.maxn()*
  3656. Returns the largest positive numerical index of the given table, or
  3657. zero if the table has no positive numerical indices. (To do its job
  3658. this function does a linear traversal of the whole table.)
  3659. table.remove({table} [, {pos}]) *table.remove()*
  3660. Removes from {table} the element at position {pos}, shifting down
  3661. other elements to close the space, if necessary. Returns the value of
  3662. the removed element. The default value for {pos} is `n`, where `n` is
  3663. the length of the table (see |lua-length|), so that a call
  3664. `table.remove(t)` removes the last element of table `t`.
  3665. table.sort({table} [, {comp}]) *table.sort()*
  3666. Sorts table elements in a given order, `in-place`, from `table[1]` to
  3667. `table[n]`, where `n` is the length of the table (see |lua-length|).
  3668. If {comp} is given, then it must be a function that receives two table
  3669. elements, and returns true when the first is less than the second (so
  3670. that `not comp(a[i+1],a[i])` will be true after the sort). If {comp}
  3671. is not given, then the standard Lua operator `<` is used instead.
  3672. The sort algorithm is `not` stable, that is, elements considered equal by the
  3673. given order may have their relative positions changed by the sort.
  3674. ==============================================================================
  3675. 5.6 Mathematical Functions *lua-lib-math*
  3676. This library is an interface to most of the functions of the standard C math
  3677. library. It provides all its functions inside the table `math`.
  3678. math.abs({x}) *math.abs()*
  3679. Returns the absolute value of {x}.
  3680. math.acos({x}) *math.acos()*
  3681. Returns the arc cosine of {x} (in radians).
  3682. math.asin({x}) *math.asin()*
  3683. Returns the arc sine of {x} (in radians).
  3684. math.atan({x}) *math.atan()*
  3685. Returns the arc tangent of {x} (in radians).
  3686. math.atan2({x}, {y}) *math.atan2()*
  3687. Returns the arc tangent of `x/y` (in radians), but uses the signs of
  3688. both parameters to find the quadrant of the result. (It also handles
  3689. correctly the case of {y} being zero.)
  3690. math.ceil({x}) *math.ceil()*
  3691. Returns the smallest integer larger than or equal to {x}.
  3692. math.cos({x}) *math.cos()*
  3693. Returns the cosine of {x} (assumed to be in radians).
  3694. math.cosh({x}) *math.cosh()*
  3695. Returns the hyperbolic cosine of {x}.
  3696. math.deg({x}) *math.deg()*
  3697. Returns the angle {x} (given in radians) in degrees.
  3698. math.exp({x}) *math.exp()*
  3699. Returns the value `e^x`.
  3700. math.floor({x}) *math.floor()*
  3701. Returns the largest integer smaller than or equal to {x}.
  3702. math.fmod({x}, {y}) *math.fmod()*
  3703. Returns the remainder of the division of {x} by {y}.
  3704. math.frexp({x}) *math.frexp()*
  3705. Returns `m` and `e` such that `x = m * 2^e`, `e` is an integer and the
  3706. absolute value of `m` is in the range `[0.5, 1)` (or zero when {x} is
  3707. zero).
  3708. math.huge *math.huge*
  3709. The value `HUGE_VAL`, a value larger than or equal to any other
  3710. numerical value.
  3711. math.ldexp({m}, {e}) *math.ldexp()*
  3712. Returns `m * 2^e` (`e` should be an integer).
  3713. math.log({x}) *math.log()*
  3714. Returns the natural logarithm of {x}.
  3715. math.log10({x}) *math.log10()*
  3716. Returns the base-10 logarithm of {x}.
  3717. math.max({x}, {...}) *math.max()*
  3718. Returns the maximum value among its arguments.
  3719. math.min({x}, {...}) *math.min()*
  3720. Returns the minimum value among its arguments.
  3721. math.modf({x}) *math.modf()*
  3722. Returns two numbers, the integral part of {x} and the fractional part
  3723. of {x}.
  3724. math.pi *math.pi*
  3725. The value of `pi`.
  3726. math.pow({x}, {y}) *math.pow()*
  3727. Returns `x^y`. (You can also use the expression `x^y` to compute this
  3728. value.)
  3729. math.rad({x}) *math.rad()*
  3730. Returns the angle {x} (given in degrees) in radians.
  3731. math.random([{m} [, {n}]]) *math.random()*
  3732. This function is an interface to the simple pseudo-random generator
  3733. function `rand` provided by ANSI C. (No guarantees can be given for
  3734. its statistical properties.)
  3735. When called without arguments, returns a pseudo-random real number in
  3736. the range `[0,1)`. When called with a number {m}, `math.random`
  3737. returns a pseudo-random integer in the range `[1, m]`. When called
  3738. with two numbers {m} and {n}, `math.random` returns a pseudo-random
  3739. integer in the range `[m, n]`.
  3740. math.randomseed({x}) *math.randomseed()*
  3741. Sets {x} as the "seed" for the pseudo-random generator: equal seeds
  3742. produce equal sequences of numbers.
  3743. math.sin({x}) *math.sin()*
  3744. Returns the sine of {x} (assumed to be in radians).
  3745. math.sinh({x}) *math.sinh()*
  3746. Returns the hyperbolic sine of {x}.
  3747. math.sqrt({x}) *math.sqrt()*
  3748. Returns the square root of {x}. (You can also use the expression
  3749. `x^0.5` to compute this value.)
  3750. math.tan({x}) *math.tan()*
  3751. Returns the tangent of {x} (assumed to be in radians).
  3752. math.tanh({x}) *math.tanh()*
  3753. Returns the hyperbolic tangent of {x}.
  3754. ==============================================================================
  3755. 5.6 Input and Output Facilities *lua-lib-io*
  3756. The I/O library provides two different styles for file manipulation. The first
  3757. one uses implicit file descriptors; that is, there are operations to set a
  3758. default input file and a default output file, and all input/output operations
  3759. are over these default files. The second style uses explicit file
  3760. descriptors.
  3761. When using implicit file descriptors, all operations are supplied by
  3762. table `io`. When using explicit file descriptors, the operation `io.open` returns
  3763. a file descriptor and then all operations are supplied as methods of the file
  3764. descriptor.
  3765. The table `io` also provides three predefined file descriptors with their usual
  3766. meanings from C: `io.stdin`, `io.stdout`, and `io.stderr`.
  3767. Unless otherwise stated, all I/O functions return `nil` on failure (plus an
  3768. error message as a second result) and some value different from `nil` on
  3769. success.
  3770. io.close([{file}]) *io.close()*
  3771. Equivalent to `file:close`. Without a {file}, closes the default
  3772. output file.
  3773. io.flush() *io.flush()*
  3774. Equivalent to `file:flush` over the default output file.
  3775. io.input([{file}]) *io.input()*
  3776. When called with a file name, it opens the named file (in text mode),
  3777. and sets its handle as the default input file. When called with a file
  3778. handle, it simply sets this file handle as the default input file.
  3779. When called without parameters, it returns the current default input
  3780. file.
  3781. In case of errors this function raises the error, instead of returning
  3782. an error code.
  3783. io.lines([{filename}]) *io.lines()*
  3784. Opens the given file name in read mode and returns an |iterator|
  3785. function that, each time it is called, returns a new line from the
  3786. file. Therefore, the construction
  3787. `for line in io.lines(filename) do` `body` `end`
  3788. will iterate over all lines of the file. When the iterator function
  3789. detects the end of file, it returns `nil` (to finish the loop) and
  3790. automatically closes the file.
  3791. The call `io.lines()` (without a file name) is equivalent to
  3792. `io.input():lines()`; that is, it iterates over the lines of the
  3793. default input file. In this case it does not close the file when the
  3794. loop ends.
  3795. io.open({filename} [, {mode}]) *io.open()*
  3796. This function opens a file, in the mode specified in the string
  3797. {mode}. It returns a new file handle, or, in case of errors, `nil`
  3798. plus an error message.
  3799. The {mode} string can be any of the following:
  3800. - `"r"` read mode (the default);
  3801. - `"w"` write mode;
  3802. - `"a"` append mode;
  3803. - `"r+"` update mode, all previous data is preserved;
  3804. - `"w+"` update mode, all previous data is erased;
  3805. - `"a+"` append update mode, previous data is preserved, writing is
  3806. only allowed at the end of file.
  3807. The {mode} string may also have a `b` at the end, which is needed in
  3808. some systems to open the file in binary mode. This string is exactly
  3809. what is used in the standard C function `fopen`.
  3810. io.output([{file}]) *io.output()*
  3811. Similar to `io.input`, but operates over the default output file.
  3812. io.popen({prog} [, {mode}]) *io.popen()*
  3813. Starts program {prog} in a separated process and returns a file handle
  3814. that you can use to read data from this program (if {mode} is `"r"`,
  3815. the default) or to write data to this program (if {mode} is `"w"`).
  3816. This function is system dependent and is not available on all
  3817. platforms.
  3818. io.read({...}) *io.read()*
  3819. Equivalent to `io.input():read`.
  3820. io.tmpfile() *io.tmpfile()*
  3821. Returns a handle for a temporary file. This file is opened in update
  3822. mode and it is automatically removed when the program ends.
  3823. io.type({obj}) *io.type()*
  3824. Checks whether {obj} is a valid file handle. Returns the string
  3825. `"file"` if {obj} is an open file handle, `"closed file"` if {obj} is
  3826. a closed file handle, or `nil` if {obj} is not a file handle.
  3827. io.write({...}) *io.write()*
  3828. Equivalent to `io.output():write`.
  3829. file:close() *file:close()*
  3830. Closes `file`. Note that files are automatically closed when their
  3831. handles are garbage collected, but that takes an unpredictable amount
  3832. of time to happen.
  3833. file:flush() *file:flush()*
  3834. Saves any written data to `file`.
  3835. file:lines() *file:lines()*
  3836. Returns an |iterator| function that, each time it is called, returns a
  3837. new line from the file. Therefore, the construction
  3838. `for line in file:lines() do` `body` `end`
  3839. will iterate over all lines of the file. (Unlike `io.lines`, this
  3840. function does not close the file when the loop ends.)
  3841. file:read({...}) *file:read()*
  3842. Reads the file `file`, according to the given formats, which specify
  3843. what to read. For each format, the function returns a string (or a
  3844. number) with the characters read, or `nil` if it cannot read data with
  3845. the specified format. When called without formats, it uses a default
  3846. format that reads the entire next line (see below).
  3847. The available formats are
  3848. `"*n"` reads a number; this is the only format that returns a
  3849. number instead of a string.
  3850. `"*a"` reads the whole file, starting at the current position. On
  3851. end of file, it returns the empty string.
  3852. `"*l"` reads the next line (skipping the end of line), returning
  3853. `nil` on end of file. This is the default format.
  3854. `number` reads a string with up to that number of characters,
  3855. returning `nil` on end of file. If number is zero, it reads
  3856. nothing and returns an empty string, or `nil` on end of file.
  3857. file:seek([{whence}] [, {offset}]) *file:seek()*
  3858. Sets and gets the file position, measured from the beginning of the
  3859. file, to the position given by {offset} plus a base specified by the
  3860. string {whence}, as follows:
  3861. - `"set"`: base is position 0 (beginning of the file);
  3862. - `"cur"`: base is current position;
  3863. - `"end"`: base is end of file;
  3864. In case of success, function `seek` returns the final file position,
  3865. measured in bytes from the beginning of the file. If this function
  3866. fails, it returns `nil`, plus a string describing the error.
  3867. The default value for {whence} is `"cur"`, and for {offset} is 0.
  3868. Therefore, the call `file:seek()` returns the current file position,
  3869. without changing it; the call `file:seek("set")` sets the position to
  3870. the beginning of the file (and returns 0); and the call
  3871. `file:seek("end")` sets the position to the end of the file, and
  3872. returns its size.
  3873. file:setvbuf({mode} [, {size}]) *file:setvbuf()*
  3874. Sets the buffering mode for an output file. There are three available
  3875. modes:
  3876. `"no"` no buffering; the result of any output operation appears
  3877. immediately.
  3878. `"full"` full buffering; output operation is performed only when
  3879. the buffer is full (or when you explicitly `flush` the file
  3880. (see |io.flush()|).
  3881. `"line"` line buffering; output is buffered until a newline is
  3882. output or there is any input from some special files (such as
  3883. a terminal device).
  3884. For the last two cases, {size} specifies the size of the buffer, in
  3885. bytes. The default is an appropriate size.
  3886. file:write({...}) *file:write()*
  3887. Writes the value of each of its arguments to `file`. The arguments
  3888. must be strings or numbers. To write other values, use `tostring`
  3889. |tostring()| or `string.format` |string.format()| before
  3890. `write`.
  3891. ==============================================================================
  3892. 5.8 Operating System Facilities *lua-lib-os*
  3893. This library is implemented through table `os`.
  3894. os.clock() *os.clock()*
  3895. Returns an approximation of the amount in seconds of CPU time used by
  3896. the program.
  3897. os.date([{format} [, {time}]]) *os.date()*
  3898. Returns a string or a table containing date and time, formatted
  3899. according to the given string {format}.
  3900. If the {time} argument is present, this is the time to be formatted
  3901. (see the `os.time` function |os.time()| for a description of this
  3902. value). Otherwise, `date` formats the current time.
  3903. If {format} starts with `!`, then the date is formatted in
  3904. Coordinated Universal Time. After this optional character, if {format}
  3905. is the string `"*t"`, then `date` returns a table with the following
  3906. fields: `year` (four digits), `month` (1-12), `day` (1-31), `hour`
  3907. (0-23), `min` (0-59), `sec` (0-61), `wday` (weekday, Sunday is 1),
  3908. `yday` (day of the year), and `isdst` (daylight saving flag, a
  3909. boolean).
  3910. If {format} is not `"*t"`, then `date` returns the date as a string,
  3911. formatted according to the same rules as the C function `strftime`.
  3912. When called without arguments, `date` returns a reasonable date and
  3913. time representation that depends on the host system and on the current
  3914. locale (that is, `os.date()` is equivalent to `os.date("%c")`).
  3915. os.difftime({t2}, {t1}) *os.difftime()*
  3916. Returns the number of seconds from time {t1} to time {t2}. In POSIX,
  3917. Windows, and some other systems, this value is exactly `t2 - t1` .
  3918. os.execute([{command}]) *os.execute()*
  3919. This function is equivalent to the C function `system`. It passes
  3920. {command} to be executed by an operating system shell. It returns a
  3921. status code, which is system-dependent. If {command} is absent, then
  3922. it returns nonzero if a shell is available and zero otherwise.
  3923. os.exit([{code}]) *os.exit()*
  3924. Calls the C function `exit`, with an optional {code}, to terminate the
  3925. host program. The default value for {code} is the success code.
  3926. os.getenv({varname}) *os.getenv()*
  3927. Returns the value of the process environment variable {varname}, or
  3928. `nil` if the variable is not defined.
  3929. os.remove({filename}) *os.remove()*
  3930. Deletes the file with the given name. Directories must be empty to be
  3931. removed. If this function fails, it returns `nil`, plus a string
  3932. describing the error.
  3933. os.rename({oldname}, {newname}) *os.rename()*
  3934. Renames file named {oldname} to {newname}. If this function fails, it
  3935. returns `nil`, plus a string describing the error.
  3936. os.setlocale({locale} [, {category}]) *os.setlocale()*
  3937. Sets the current locale of the program. {locale} is a string
  3938. specifying a locale; {category} is an optional string describing which
  3939. category to change: `"all"`, `"collate"`, `"ctype"`, `"monetary"`,
  3940. `"numeric"`, or `"time"`; the default category is `"all"`. The
  3941. function returns the name of the new locale, or `nil` if the request
  3942. cannot be honored.
  3943. os.time([{table}]) *os.time()*
  3944. Returns the current time when called without arguments, or a time
  3945. representing the date and time specified by the given table. This
  3946. table must have fields `year`, `month`, and `day`, and may have fields
  3947. `hour`, `min`, `sec`, and `isdst` (for a description of these fields,
  3948. see the `os.date` function |os.date()|).
  3949. The returned value is a number, whose meaning depends on your system.
  3950. In POSIX, Windows, and some other systems, this number counts the
  3951. number of seconds since some given start time (the "epoch"). In other
  3952. systems, the meaning is not specified, and the number returned by
  3953. `time` can be used only as an argument to `date` and `difftime`.
  3954. os.tmpname() *os.tmpname()*
  3955. Returns a string with a file name that can be used for a temporary
  3956. file. The file must be explicitly opened before its use and explicitly
  3957. removed when no longer needed.
  3958. ==============================================================================
  3959. 5.9 The Debug Library *lua-lib-debug*
  3960. This library provides the functionality of the debug interface to Lua
  3961. programs. You should exert care when using this library. The functions
  3962. provided here should be used exclusively for debugging and similar tasks, such
  3963. as profiling. Please resist the temptation to use them as a usual programming
  3964. tool: they can be very slow. Moreover, several of its functions violate some
  3965. assumptions about Lua code (e.g., that variables local to a function cannot be
  3966. accessed from outside or that userdata metatables cannot be changed by Lua
  3967. code) and therefore can compromise otherwise secure code.
  3968. All functions in this library are provided inside the `debug` table. All
  3969. functions that operate over a thread have an optional first argument which is
  3970. the thread to operate over. The default is always the current thread.
  3971. debug.debug() *debug.debug()*
  3972. Enters an interactive mode with the user, running each string that the
  3973. user enters. Using simple commands and other debug facilities, the
  3974. user can inspect global and local variables, change their values,
  3975. evaluate expressions, and so on. A line containing only the word
  3976. `cont` finishes this function, so that the caller continues its
  3977. execution.
  3978. Note that commands for `debug.debug` are not lexically nested within
  3979. any function, and so have no direct access to local variables.
  3980. debug.getfenv(o) *debug.getfenv()*
  3981. Returns the environment of object {o}.
  3982. debug.gethook([{thread}]) *debug.gethook()*
  3983. Returns the current hook settings of the thread, as three values: the
  3984. current hook function, the current hook mask, and the current hook
  3985. count (as set by the `debug.sethook` function).
  3986. debug.getinfo([{thread},] {function} [, {what}]) *debug.getinfo()*
  3987. Returns a table with information about a function. You can give the
  3988. function directly, or you can give a number as the value of
  3989. {function}, which means the function running at level {function} of
  3990. the call stack of the given thread: level 0 is the current function
  3991. (`getinfo` itself); level 1 is the function that called `getinfo`; and
  3992. so on. If {function} is a number larger than the number of active
  3993. functions, then `getinfo` returns `nil`.
  3994. The returned table may contain all the fields returned by
  3995. `lua_getinfo` (see |lua_getinfo()|), with the string {what}
  3996. describing which fields to fill in. The default for {what} is to get
  3997. all information available, except the table of valid lines. If
  3998. present, the option `f` adds a field named `func` with the function
  3999. itself. If present, the option `L` adds a field named `activelines`
  4000. with the table of valid lines.
  4001. For instance, the expression `debug.getinfo(1,"n").name` returns the
  4002. name of the current function, if a reasonable name can be found, and
  4003. `debug.getinfo(print)` returns a table with all available information
  4004. about the `print` function.
  4005. debug.getlocal([{thread},] {level}, {local}) *debug.getlocal()*
  4006. This function returns the name and the value of the local variable
  4007. with index {local} of the function at level {level} of the stack. (The
  4008. first parameter or local variable has index 1, and so on, until the
  4009. last active local variable.) The function returns `nil` if there is no
  4010. local variable with the given index, and raises an error when called
  4011. with a {level} out of range. (You can call `debug.getinfo`
  4012. |debug.getinfo()| to check whether the level is valid.)
  4013. Variable names starting with `(` (open parentheses) represent
  4014. internal variables (loop control variables, temporaries, and C
  4015. function locals).
  4016. debug.getmetatable({object}) *debug.getmetatable()*
  4017. Returns the metatable of the given {object} or `nil` if it does not
  4018. have a metatable.
  4019. debug.getregistry() *debug.getregistry()*
  4020. Returns the registry table (see |lua-registry|).
  4021. debug.getupvalue({func}, {up}) *debug.getupvalue()*
  4022. This function returns the name and the value of the upvalue with index
  4023. {up} of the function {func}. The function returns `nil` if there is no
  4024. upvalue with the given index.
  4025. debug.setfenv({object}, {table}) *debug.setfenv()*
  4026. Sets the environment of the given {object} to the given {table}.
  4027. Returns {object}.
  4028. debug.sethook([{thread},] {hook}, {mask} [, {count}]) *debug.sethook()*
  4029. Sets the given function as a hook. The string {mask} and the number
  4030. {count} describe when the hook will be called. The string mask may
  4031. have the following characters, with the given meaning:
  4032. - `"c"` : The hook is called every time Lua calls a function;
  4033. - `"r"` : The hook is called every time Lua returns from a function;
  4034. - `"l"` : The hook is called every time Lua enters a new line of
  4035. code.
  4036. With a {count} different from zero, the hook is called after every
  4037. {count} instructions.
  4038. When called without arguments, the `debug.sethook` turns off the hook.
  4039. When the hook is called, its first parameter is a string describing
  4040. the event that triggered its call: `"call"`, `"return"` (or `"tail
  4041. return"`), `"line"`, and `"count"`. For line events, the hook also
  4042. gets the new line number as its second parameter. Inside a hook, you
  4043. can call `getinfo` with level 2 to get more information about the
  4044. running function (level 0 is the `getinfo` function, and level 1 is
  4045. the hook function), unless the event is `"tail return"`. In this case,
  4046. Lua is only simulating the return, and a call to `getinfo` will return
  4047. invalid data.
  4048. debug.setlocal([{thread},] {level}, {local}, {value}) *debug.setlocal()*
  4049. This function assigns the value {value} to the local variable with
  4050. index {local} of the function at level {level} of the stack. The
  4051. function returns `nil` if there is no local variable with the given
  4052. index, and raises an error when called with a {level} out of range.
  4053. (You can call `getinfo` to check whether the level is valid.)
  4054. Otherwise, it returns the name of the local variable.
  4055. debug.setmetatable({object}, {table}) *debug.setmetatable()*
  4056. Sets the metatable for the given {object} to the given {table} (which
  4057. can be `nil`).
  4058. debug.setupvalue({func}, {up}, {value}) *debug.setupvalue()*
  4059. This function assigns the value {value} to the upvalue with index {up}
  4060. of the function {func}. The function returns `nil` if there is no
  4061. upvalue with the given index. Otherwise, it returns the name of the
  4062. upvalue.
  4063. debug.traceback([{thread},] [{message} [,{level}]]) *debug.traceback()*
  4064. Returns a string with a traceback of the call stack. An optional
  4065. {message} string is appended at the beginning of the traceback. An
  4066. optional {level} number tells at which level to start the traceback
  4067. (default is 1, the function calling `traceback`).
  4068. ==============================================================================
  4069. A BIBLIOGRAPHY *lua-ref-bibliography*
  4070. This help file is a minor adaptation from this main reference:
  4071. - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes.,
  4072. "Lua: 5.1 reference manual", https://www.lua.org/manual/5.1/manual.html
  4073. Lua is discussed in these references:
  4074. - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes.,
  4075. "Lua --- an extensible extension language".
  4076. "Software: Practice & Experience" 26, 6 (1996) 635-652.
  4077. - L. H. de Figueiredo, R. Ierusalimschy, and W. Celes.,
  4078. "The design and implementation of a language for extending applications".
  4079. "Proc. of XXI Brazilian Seminar on Software and Hardware" (1994) 273-283.
  4080. - L. H. de Figueiredo, R. Ierusalimschy, and W. Celes.,
  4081. "Lua: an extensible embedded language".
  4082. "Dr. Dobb's Journal" 21, 12 (Dec 1996) 26-33.
  4083. - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes.,
  4084. "The evolution of an extension language: a history of Lua".
  4085. "Proc. of V Brazilian Symposium on Programming Languages" (2001) B-14-B-28.
  4086. ==============================================================================
  4087. B COPYRIGHT AND LICENSES *lua-ref-copyright*
  4088. This help file has the same copyright and license as Lua 5.1 and the Lua 5.1
  4089. manual:
  4090. Copyright (c) 1994-2006 Lua.org, PUC-Rio.
  4091. Permission is hereby granted, free of charge, to any person obtaining a copy
  4092. of this software and associated documentation files (the "Software"), to deal
  4093. in the Software without restriction, including without limitation the rights
  4094. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  4095. copies of the Software, and to permit persons to whom the Software is
  4096. furnished to do so, subject to the following conditions:
  4097. The above copyright notice and this permission notice shall be included in all
  4098. copies or substantial portions of the Software.
  4099. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4100. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4101. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4102. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4103. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4104. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  4105. SOFTWARE.
  4106. ==============================================================================
  4107. C LUAREF DOC *lua-ref-doc*
  4108. This is a Vim help file containing a reference for Lua 5.1, and it is -- with
  4109. a few exceptions and adaptations -- a copy of the Lua 5.1 Reference Manual
  4110. (see |lua-ref-bibliography|). For usage information, refer to
  4111. |lua-ref-doc|. For copyright information, see |lua-ref-copyright|.
  4112. The main ideas and concepts on how to implement this reference were taken from
  4113. Christian Habermann's CRefVim project
  4114. (https://www.vim.org/scripts/script.php?script_id=614).
  4115. Adapted for bundled Nvim documentation; the original plugin can be found at
  4116. https://www.vim.org/scripts/script.php?script_id=1291
  4117. ------------------------------------------------------------------------------
  4118. vi:tw=78:ts=4:ft=help:norl:et