manual.tex 158 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487
  1. % $Id: manual.tex,v 1.63 2002/11/18 14:39:34 roberto Exp roberto $
  2. %{[(
  3. \documentclass[11pt,twoside]{article}
  4. \usepackage{fullpage}
  5. \usepackage{bnf}
  6. \usepackage{graphicx}
  7. % no need for subscripts...
  8. \catcode`\_=12
  9. %\newcommand{\See}[1]{Section~\ref{#1}}
  10. \newcommand{\See}[1]{\S\ref{#1}}
  11. %\newcommand{\see}[1]{(see~\See{#1} on page \pageref{#1})}
  12. \newcommand{\see}[1]{(see~\See{#1})}
  13. \newcommand{\seepage}[1]{(see page~\pageref{#1})}
  14. \newcommand{\M}[1]{{\rm\emph{#1}}}
  15. \newcommand{\T}[1]{{\tt #1}}
  16. \newcommand{\Math}[1]{$#1$}
  17. \newcommand{\nil}{{\bf nil}}
  18. \newcommand{\False}{{\bf false}}
  19. \newcommand{\True}{{\bf true}}
  20. %\def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}}
  21. \def\tecgraf{{\sf Tecgraf}}
  22. \newcommand{\Index}[1]{#1\index{#1@{\lowercase{#1}}}}
  23. \newcommand{\IndexVerb}[1]{\T{#1}\index{#1@{\tt #1}}}
  24. \newcommand{\IndexEmph}[1]{\emph{#1}\index{#1@{\lowercase{#1}}}}
  25. \newcommand{\IndexTM}[1]{\index{#1 event@{``#1'' event}}\index{metamethod!#1}}
  26. \newcommand{\Def}[1]{\emph{#1}\index{#1}}
  27. \newcommand{\IndexAPI}[1]{\T{#1}\DefAPI{#1}}
  28. \newcommand{\IndexLIB}[1]{\T{#1}\DefLIB{#1}}
  29. \newcommand{\DefLIB}[1]{\index{#1@{\tt #1}}}
  30. \newcommand{\DefAPI}[1]{\index{C API!#1@{\tt #1}}}
  31. \newcommand{\IndexKW}[1]{\index{keywords!#1@{\tt #1}}}
  32. \newcommand{\ff}{$\bullet$\ }
  33. \newcommand{\Version}{5.0 (beta)}
  34. % changes to bnf.sty by LHF
  35. \renewcommand{\Or}{$|$ }
  36. \renewcommand{\rep}[1]{{\rm\{}\,#1\,{\rm\}}}
  37. \renewcommand{\opt}[1]{{\rm [}\,#1\,{\,\rm]}}
  38. \renewcommand{\ter}[1]{{\rm`{\tt#1}'}}
  39. \newcommand{\Nter}[1]{{\tt#1}}
  40. \newcommand{\NOTE}{\par\medskip\noindent\emph{NOTE}: }
  41. \makeindex
  42. \begin{document}
  43. %{===============================================================
  44. \thispagestyle{empty}
  45. \pagestyle{empty}
  46. {
  47. \parindent=0pt
  48. \vglue1.5in
  49. {\LARGE\bf
  50. The Lua Programming Language}
  51. \hfill
  52. \vskip4pt \hrule height 4pt width \hsize \vskip4pt
  53. \hfill
  54. Reference Manual for Lua version \Version
  55. \\
  56. \null
  57. \hfill
  58. Last revised on \today
  59. \\
  60. \vfill
  61. \centering
  62. \includegraphics[width=0.7\textwidth]{nolabel.ps}
  63. \vfill
  64. \vskip4pt \hrule height 2pt width \hsize
  65. }
  66. \newpage
  67. \begin{quotation}
  68. \parskip=10pt
  69. \parindent=0pt
  70. \footnotesize
  71. \null\vfill
  72. \noindent
  73. Copyright \copyright\ 2002 Tecgraf, PUC-Rio. All rights reserved.
  74. Permission is hereby granted, free of charge,
  75. to any person obtaining a copy of this software
  76. and associated documentation files (the "Software"),
  77. to deal in the Software without restriction,
  78. including without limitation the rights to use, copy, modify,
  79. merge, publish, distribute, sublicense,
  80. and/or sell copies of the Software,
  81. and to permit persons to whom the Software is furnished to do so,
  82. subject to the following conditions:
  83. The above copyright notice and this permission notice shall be
  84. included in all copies or substantial portions of the Software.
  85. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  86. EXPRESS OR IMPLIED,
  87. INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  88. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  89. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  90. FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  91. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  92. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  93. OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  94. Copies of this manual can be obtained at
  95. Lua's official web site,
  96. \verb|www.lua.org|.
  97. \bigskip
  98. The Lua logo was designed by A. Nakonechny.
  99. Copyright \copyright\ 1998. All rights reserved.
  100. \end{quotation}
  101. %}===============================================================
  102. \newpage
  103. \title{\Large\bf Reference Manual of the Programming Language Lua \Version}
  104. \author{%
  105. Roberto Ierusalimschy\qquad
  106. Luiz Henrique de Figueiredo\qquad
  107. Waldemar Celes
  108. \vspace{1.0ex}\\
  109. \smallskip
  110. \small\tt [email protected]
  111. \vspace{2.0ex}\\
  112. %MCC 08/95 ---
  113. \tecgraf\ --- Computer Science Department --- PUC-Rio
  114. }
  115. %\date{{\small \tt\$Date: 2002/11/18 14:39:34 $ $}}
  116. \maketitle
  117. \pagestyle{plain}
  118. \pagenumbering{roman}
  119. \begin{abstract}
  120. \noindent
  121. Lua is a powerful, light-weight programming language
  122. designed for extending applications.
  123. Lua is also frequently used as a general-purpose, stand-alone language.
  124. Lua combines simple procedural syntax
  125. (similar to Pascal)
  126. with
  127. powerful data description constructs
  128. based on associative arrays and extensible semantics.
  129. Lua is
  130. dynamically typed,
  131. interpreted from opcodes,
  132. and has automatic memory management with garbage collection,
  133. making it ideal for
  134. configuration,
  135. scripting,
  136. and
  137. rapid prototyping.
  138. This document describes version \Version\ of the Lua programming language
  139. and the Application Program Interface (API)
  140. that allows interaction between Lua programs and their host C~programs.
  141. \end{abstract}
  142. \def\abstractname{Resumo}
  143. \begin{abstract}
  144. \noindent
  145. Lua \'e uma linguagem de programa\c{c}\~ao
  146. poderosa e leve,
  147. projetada para estender aplica\c{c}\~oes.
  148. Lua tamb\'em \'e frequentemente usada como uma linguagem de prop\'osito geral.
  149. Lua combina programa\c{c}\~ao procedural
  150. (com sintaxe semelhante \`a de Pascal)
  151. com
  152. poderosas constru\c{c}\~oes para descri\c{c}\~ao de dados,
  153. baseadas em tabelas associativas e sem\^antica extens\'\i vel.
  154. Lua \'e
  155. tipada dinamicamente,
  156. interpretada a partir de \emph{opcodes},
  157. e tem gerenciamento autom\'atico de mem\'oria com coleta de lixo.
  158. Essas caracter\'{\i}sticas fazem de Lua uma linguagem ideal para
  159. configura\c{c}\~ao,
  160. automa\c{c}\~ao (\emph{scripting})
  161. e prototipagem r\'apida.
  162. Este documento descreve a vers\~ao \Version\ da linguagem de
  163. programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite
  164. a intera\c{c}\~ao entre programas Lua e programas C~hospedeiros.
  165. \end{abstract}
  166. \newpage
  167. \null
  168. \newpage
  169. \tableofcontents
  170. \newpage
  171. \setcounter{page}{1}
  172. \pagestyle{plain}
  173. \pagenumbering{arabic}
  174. %------------------------------------------------------------------------------
  175. \section{Introduction}
  176. Lua is an extension programming language designed to support
  177. general procedural programming with data description
  178. facilities.
  179. Lua is intended to be used as a powerful, light-weight
  180. configuration language for any program that needs one.
  181. Lua is implemented as a library, written in C.
  182. Being an extension language, Lua has no notion of a ``main'' program:
  183. it only works \emph{embedded} in a host client,
  184. called the \emph{embedding program} or simply the \emph{host}.
  185. This host program can invoke functions to execute a piece of Lua code,
  186. can write and read Lua variables,
  187. and can register C~functions to be called by Lua code.
  188. Through the use of C~functions, Lua can be augmented to cope with
  189. a wide range of different domains,
  190. thus creating customized programming languages sharing a syntactical framework.
  191. Lua is free software,
  192. and is provided as usual with no guarantees,
  193. as stated in its copyright notice.
  194. The implementation described in this manual is available
  195. at Lua's official web site, \verb|www.lua.org|.
  196. Like any other reference manual,
  197. this document is dry in places.
  198. For a discussion of the decisions behind the design of Lua,
  199. see the papers below,
  200. which are available at Lua's web site.
  201. \begin{itemize}
  202. \item
  203. R.~Ierusalimschy, L.~H.~de Figueiredo, and W.~Celes.
  204. Lua---an extensible extension language.
  205. \emph{Software: Practice \& Experience} {\bf 26} \#6 (1996) 635--652.
  206. \item
  207. L.~H.~de Figueiredo, R.~Ierusalimschy, and W.~Celes.
  208. The design and implementation of a language for extending applications.
  209. \emph{Proceedings of XXI Brazilian Seminar on Software and Hardware} (1994) 273--283.
  210. \item
  211. L.~H.~de Figueiredo, R.~Ierusalimschy, and W.~Celes.
  212. Lua: an extensible embedded language.
  213. \emph{Dr. Dobb's Journal} {\bf 21} \#12 (Dec 1996) 26--33.
  214. \item
  215. R.~Ierusalimschy, L.~H.~de Figueiredo, and W.~Celes.
  216. The evolution of an extension language: a history of Lua,
  217. \emph{Proceedings of V Brazilian Symposium on Programming Languages} (2001) B-14--B-28.
  218. \end{itemize}
  219. Lua means ``moon'' in Portuguese.
  220. %------------------------------------------------------------------------------
  221. \section{Lua Concepts}\label{concepts}
  222. This section describes the main concepts of Lua as a language.
  223. The syntax and semantics of Lua are described in \See{language}.
  224. The discussion below is not purely conceptual;
  225. it includes references to the C~API \see{API},
  226. because Lua is designed to be embedded in host programs.
  227. It also includes references to the standard libraries \see{libraries}.
  228. \subsection{Environment and Chunks}
  229. All statements in Lua are executed in a \Def{global environment}.
  230. This environment is initialized with a call from the embedding program to
  231. \verb|lua_open| and
  232. persists until a call to \verb|lua_close|
  233. or the end of the embedding program.
  234. The host program can create multiple independent global
  235. environments, and freely switch between them \see{mangstate}.
  236. The unit of execution of Lua is called a \Def{chunk}.
  237. A chunk is simply a sequence of statements.
  238. Statements are described in \See{stats}.
  239. A chunk may be stored in a file or in a string inside the host program.
  240. When a chunk is executed, first it is pre-compiled into opcodes for
  241. a virtual machine,
  242. and then the compiled statements are executed
  243. by an interpreter for the virtual machine.
  244. All modifications a chunk makes to the global environment persist
  245. after the chunk ends.
  246. Chunks may also be pre-compiled into binary form and stored in files;
  247. see program \IndexVerb{luac} for details.
  248. Programs in source and compiled forms are interchangeable;
  249. Lua automatically detects the file type and acts accordingly.
  250. \index{pre-compilation}
  251. \subsection{Table of Globals} \label{global-table}
  252. ????
  253. \subsection{\Index{Values and Types}} \label{TypesSec}
  254. Lua is a \emph{dynamically typed language}.
  255. That means that
  256. variables do not have types; only values do.
  257. There are no type definitions in the language.
  258. All values carry their own type.
  259. There are eight \Index{basic types} in Lua:
  260. \Def{nil}, \Def{boolean}, \Def{number},
  261. \Def{string}, \Def{function}, \Def{userdata}, \Def{thread}, and \Def{table}.
  262. \emph{Nil} is the type of the value \nil,
  263. whose main property is to be different from any other value;
  264. usually it represents the absence of a useful value.
  265. \emph{Boolean} is the type of the values \False{} and \True.
  266. In Lua, both \nil{} and \False{} make a condition false,
  267. and any other value makes it true.
  268. \emph{Number} represents real (double-precision floating-point) numbers.
  269. \emph{String} represents arrays of characters.
  270. \index{eight-bit clean}
  271. Lua is 8-bit clean,
  272. and so strings may contain any 8-bit character,
  273. including embedded zeros (\verb|'\0'|) \see{lexical}.
  274. Functions are \emph{first-class values} in Lua.
  275. That means that functions can be stored in variables,
  276. passed as arguments to other functions, and returned as results.
  277. Lua can call (and manipulate) functions written in Lua and
  278. functions written in C
  279. \see{functioncall}.
  280. The type \emph{userdata} is provided to allow arbitrary C data to
  281. be stored in Lua variables.
  282. This type corresponds to a block of raw memory
  283. and has no pre-defined operations in Lua,
  284. except assignment and identity test.
  285. However, by using \emph{metatables},
  286. the programmer can define operations for userdata values
  287. \see{metatable}.
  288. Userdata values cannot be created or modified in Lua,
  289. only through the C~API.
  290. This guarantees the integrity of data owned by the host program.
  291. The type \Def{thread} represents independent threads of execution,
  292. and it is used to implement coroutines.
  293. (This is an experimental area; it needs more documentation,
  294. and is subject to changes in the future.)
  295. The type \emph{table} implements \Index{associative arrays},
  296. that is, \Index{arrays} that can be indexed not only with numbers,
  297. but with any value (except \nil).
  298. Moreover,
  299. tables can be \emph{heterogeneous},
  300. that is, they can contain values of all types.
  301. Tables are the sole data structuring mechanism in Lua;
  302. they may be used not only to represent ordinary arrays,
  303. but also symbol tables, sets, records, graphs, trees, etc.
  304. To represent \Index{records}, Lua uses the field name as an index.
  305. The language supports this representation by
  306. providing \verb|a.name| as syntactic sugar for \verb|a["name"]|.
  307. There are several convenient ways to create tables in Lua
  308. \see{tableconstructor}.
  309. Like indices, the value of a table field can be of any type.
  310. In particular,
  311. because functions are first class values,
  312. table fields may contain functions.
  313. So, tables may also carry \emph{methods} \see{func-def}.
  314. Tables, functions, and userdata values are \emph{objects}:
  315. variables do not actually \emph{contain} these values,
  316. only \emph{references} to them.
  317. Assignment, parameter passing, and function returns
  318. always manipulate references to these values,
  319. and do not imply any kind of copy.
  320. The library function \verb|type| returns a string describing the type
  321. of a given value \see{pdf-type}.
  322. \subsubsection{Metatables}
  323. Each table and userdata object in Lua may have a \Index{metatable}.
  324. You can change several aspects of the behavior
  325. of an object by setting specific fields in its metatable.
  326. For instance, when an object is the operand of an addition,
  327. Lua checks for a function in the field \verb|"__add"| in its metatable.
  328. If it finds one,
  329. Lua calls that function to perform the addition.
  330. We call the keys in a metatable \Index{events},
  331. and the values \Index{metamethods}.
  332. In the previous example, \verb|"add"| is the event,
  333. and the function is the metamethod that performs the addition.
  334. A metatable controls how an object behaves in arithmetic operations,
  335. order comparisons, concatenation, and indexing.
  336. A metatable can also define a function to be called when a userdata
  337. is garbage collected.
  338. \See{metatable} gives a detailed description of which events you
  339. can control with metatables.
  340. You can query and change the metatable of an object
  341. through the \verb|setmetatable| and \verb|getmetatable|
  342. functions \see{pdf-getmetatable}.
  343. \subsection{Coercion} \label{coercion}
  344. Lua provides automatic conversion between
  345. string and number values at run time.
  346. Any arithmetic operation applied to a string tries to convert
  347. that string to a number, following the usual rules.
  348. Conversely, whenever a number is used when a string is expected,
  349. the number is converted to a string, in a reasonable format.
  350. The format is chosen so that
  351. a conversion from number to string then back to number
  352. reproduces the original number \emph{exactly}.
  353. For complete control of how numbers are converted to strings,
  354. use the \verb|format| function \see{format}.
  355. \subsection{Variables}
  356. There are two kinds of variables in Lua:
  357. global variables
  358. and local variables.
  359. Variables are assumed to be global unless explicitly declared local
  360. \see{localvar}.
  361. Before the first assignment, the value of a variable is \nil.
  362. All global variables live as fields in ordinary Lua tables.
  363. Usually, globals live in a table called \Index{table of globals}.
  364. However, a function can individually change its global table,
  365. so that all global variables in that function will refer to that table.
  366. This mechanism allows the creation of \Index{namespaces} and other
  367. modularization facilities.
  368. \Index{Local variables} are lexically scoped.
  369. Therefore, local variables can be freely accessed by functions
  370. defined inside their scope \see{visibility}.
  371. \subsection{Garbage Collection}\label{GC}
  372. Lua does automatic memory management.
  373. That means that
  374. you do not have to worry about allocating memory for new objects
  375. and freeing it when the objects are no longer needed.
  376. Lua manages memory automatically by running
  377. a \Index{garbage collector} from time to time
  378. and
  379. collecting all dead objects
  380. (all objects that are no longer accessible from Lua).
  381. All objects in Lua are subject to automatic management:
  382. tables, userdata, functions, and strings.
  383. Using the C~API,
  384. you can set garbage-collector metamethods for userdata \see{metatable}.
  385. When it is about to free a userdata,
  386. Lua calls the metamethod associated with event \verb|gc| in the
  387. userdata's metatable.
  388. Using such facility, you can coordinate Lua's garbage collection
  389. with external resource management
  390. (such as closing files, network or database connections,
  391. or freeing your own memory).
  392. Lua uses two numbers to control its garbage-collection cycles.
  393. One number counts how many bytes of dynamic memory Lua is using,
  394. and the other is a threshold.
  395. When the number of bytes crosses the threshold,
  396. Lua runs the garbage collector,
  397. which reclaims the memory of all dead objects.
  398. The byte counter is corrected,
  399. and then the threshold is reset to twice the value of the byte counter.
  400. Through the C~API, you can query those numbers,
  401. and change the threshold \see{GC-API}.
  402. Setting the threshold to zero actually forces an immediate
  403. garbage-collection cycle,
  404. while setting it to a huge number effectively stops the garbage collector.
  405. Using Lua code you have a more limited control over garbage-collection cycles,
  406. through the functions \verb|gcinfo| and \verb|collectgarbage|
  407. \see{predefined}.
  408. \subsubsection{Weak Tables}\label{weak-table}
  409. A \IndexEmph{weak table} is a table whose elements are
  410. \IndexEmph{weak references}.
  411. A weak reference is ignored by the garbage collector.
  412. In other words,
  413. if the only references to an object are weak references,
  414. then the garbage collector will collect that object.
  415. A weak table can have weak keys, weak values, or both.
  416. A table with weak keys allows the collection of its keys,
  417. but prevents the collection of its values.
  418. A table with both weak keys and weak values allows the collection of
  419. both keys and values.
  420. In any case, if either the key or the value is collected,
  421. the whole pair is removed from the table.
  422. The weakness of a table is controled by the value of the
  423. \verb|__mode| field of its metatable.
  424. If the \verb|__mode| field is a string containing the \verb|k| character,
  425. the keys in the table are weak.
  426. If \verb|__mode| contains \verb|v|,
  427. the values in the table are weak.
  428. %------------------------------------------------------------------------------
  429. \section{The Language}\label{language}
  430. This section describes the lexis, the syntax, and the semantics of Lua.
  431. In other words,
  432. this section describes
  433. which tokens are valid,
  434. how they can be combined,
  435. and what their combinations mean.
  436. \subsection{Lexical Conventions} \label{lexical}
  437. \IndexEmph{Identifiers} in Lua can be any string of letters,
  438. digits, and underscores,
  439. not beginning with a digit.
  440. This coincides with the definition of identifiers in most languages.
  441. (The definition of letter depends on the current locale:
  442. any character considered alphabetic by the current locale
  443. can be used in an identifier.)
  444. The following \IndexEmph{keywords} are reserved,
  445. and cannot be used as identifiers:
  446. \index{reserved words}
  447. \begin{verbatim}
  448. and break do else elseif
  449. end false for function if
  450. in local nil not or
  451. repeat return then true until
  452. while
  453. \end{verbatim}
  454. Lua is a case-sensitive language:
  455. \T{and} is a reserved word, but \T{And} and \T{\'and}
  456. (if the locale permits) are two different, valid identifiers.
  457. As a convention, identifiers starting with an underscore followed by
  458. uppercase letters (such as \verb|_VERSION|)
  459. are reserved for internal variables.
  460. The following strings denote other \Index{tokens}:
  461. \begin{verbatim}
  462. + - * / ^ =
  463. ~= <= >= < > ==
  464. ( ) { } [ ]
  465. ; : , . .. ...
  466. \end{verbatim}
  467. \IndexEmph{Literal strings}
  468. can be delimited by matching single or double quotes,
  469. and can contain the C-like escape sequences
  470. `\verb|\a|' (bell),
  471. `\verb|\b|' (backspace),
  472. `\verb|\f|' (form feed),
  473. `\verb|\n|' (newline),
  474. `\verb|\r|' (carriage return),
  475. `\verb|\t|' (horizontal tab),
  476. `\verb|\v|' (vertical tab),
  477. `\verb|\\|' (backslash),
  478. `\verb|\"|' (double quote),
  479. `\verb|\'|' (single quote),
  480. and `\verb|\|\emph{newline}' (that is, a backslash followed by a real newline,
  481. which results in a newline in the string).
  482. A character in a string may also be specified by its numerical value,
  483. through the escape sequence `\verb|\|\emph{ddd}',
  484. where \emph{ddd} is a sequence of up to three \emph{decimal} digits.
  485. Strings in Lua may contain any 8-bit value, including embedded zeros,
  486. which can be specified as `\verb|\0|'.
  487. Literal strings can also be delimited by matching \verb|[[| $\ldots$ \verb|]]|.
  488. Literals in this bracketed form may run for several lines,
  489. may contain nested \verb|[[| $\ldots$ \verb|]]| pairs,
  490. and do not interpret escape sequences.
  491. For convenience,
  492. when the opening \verb|[[| is immediately followed by a newline,
  493. the newline is not included in the string. % ]]
  494. That form is specially convenient for
  495. writing strings that contain program pieces or
  496. other quoted strings.
  497. As an example, in a system using ASCII
  498. (in which `\verb|a|' is coded as~97,
  499. newline is coded as~10, and `\verb|1|' is coded as~49),
  500. the four literals below denote the same string:
  501. \begin{verbatim}
  502. (1) "alo\n123\""
  503. (2) '\97lo\10\04923"'
  504. (3) [[alo
  505. 123"]]
  506. (4) [[
  507. alo
  508. 123"]]
  509. \end{verbatim}
  510. \IndexEmph{Numerical constants} may be written with an optional decimal part
  511. and an optional decimal exponent.
  512. Examples of valid numerical constants are
  513. \begin{verbatim}
  514. 3 3.0 3.1416 314.16e-2 0.31416E1
  515. \end{verbatim}
  516. \IndexEmph{Comments} start anywhere outside a string with a
  517. double hyphen (\verb|--|);
  518. If the text after \verb|--| is different from \verb|[[|,
  519. the comment is a short comment,
  520. that runs until the end of the line.
  521. Otherwise, it is a long comment,
  522. that runs until the corresponding \verb|]]|.
  523. Long comments may run for several lines,
  524. and may contain nested \verb|[[| $\ldots$ \verb|]]| pairs.
  525. For convenience,
  526. the first line of a chunk is skipped if it starts with \verb|#|.
  527. This facility allows the use of Lua as a script interpreter
  528. in Unix systems \see{lua-sa}.
  529. \subsection{Variables}\label{variables}
  530. Variables are places that store values.
  531. %In Lua, variables are given by simple identifiers or by table fields.
  532. A single name can denote a global variable, a local variable,
  533. or a formal parameter in a function
  534. (formal parameters are just local variables):
  535. \begin{Produc}
  536. \produc{var}{\Nter{Name}}
  537. \end{Produc}%
  538. Square brackets are used to index a table:
  539. \begin{Produc}
  540. \produc{var}{prefixexp \ter{[} exp \ter{]}}
  541. \end{Produc}%
  542. The first expression should result in a table value,
  543. and the second expression identifies a specific entry inside that table.
  544. The syntax \verb|var.NAME| is just syntactic sugar for
  545. \verb|var["NAME"]|:
  546. \begin{Produc}
  547. \produc{var}{prefixexp \ter{.} \Nter{Name}}
  548. \end{Produc}%
  549. The expression denoting the table to be indexed has a restricted syntax;
  550. \See{expressions} for details.
  551. The meaning of assignments and evaluations of global and
  552. indexed variables can be changed via metatables.
  553. An assignment to a global variable \verb|x = val|
  554. is equivalent to the assignment
  555. \verb|_glob.x = val|,
  556. where \verb|_glob| is the table of globals of the running function
  557. (\see{global-table} for a discussion about the table of globals).
  558. An assignment to an indexed variable \verb|t[i] = val| is equivalent to
  559. \verb|settable_event(t,i,val)|.
  560. An access to a global variable \verb|x|
  561. is equivalent to \verb|_glob.x|
  562. (again, \see{global-table} for a discussion about \verb|_glob|).
  563. An access to an indexed variable \verb|t[i]| is equivalent to
  564. a call \verb|gettable_event(t,i)|.
  565. See \See{metatable} for a complete description of the
  566. \verb|settable_event| and \verb|gettable_event| functions.
  567. (These functions are not defined in Lua.
  568. We use them here only for explanatory purposes.)
  569. \subsection{Statements}\label{stats}
  570. Lua supports an almost conventional set of \Index{statements},
  571. similar to those in Pascal or C.
  572. The conventional commands include
  573. assignment, control structures, and procedure calls.
  574. Non-conventional commands include table constructors
  575. and variable declarations.
  576. \subsubsection{Chunks}\label{chunks}
  577. The unit of execution of Lua is called a \Def{chunk}.
  578. A chunk is simply a sequence of statements,
  579. which are executed sequentially.
  580. Each statement can be optionally followed by a semicolon:
  581. \begin{Produc}
  582. \produc{chunk}{\rep{stat \opt{\ter{;}}}}
  583. \end{Produc}%
  584. \subsubsection{Blocks}
  585. A \Index{block} is a list of statements;
  586. syntactically, a block is equal to a chunk:
  587. \begin{Produc}
  588. \produc{block}{chunk}
  589. \end{Produc}%
  590. A block may be explicitly delimited to produce a single statement:
  591. \begin{Produc}
  592. \produc{stat}{\rwd{do} block \rwd{end}}
  593. \end{Produc}%
  594. \IndexKW{do}
  595. Explicit blocks are useful
  596. to control the scope of variable declarations.
  597. Explicit blocks are also sometimes used to
  598. add a \rwd{return} or \rwd{break} statement in the middle
  599. of another block \see{control}.
  600. \subsubsection{\Index{Assignment}} \label{assignment}
  601. Lua allows \Index{multiple assignment}.
  602. Therefore, the syntax for assignment
  603. defines a list of variables on the left side
  604. and a list of expressions on the right side.
  605. The elements in both lists are separated by commas:
  606. \begin{Produc}
  607. \produc{stat}{varlist1 \ter{=} explist1}
  608. \produc{varlist1}{var \rep{\ter{,} var}}
  609. \produc{explist1}{exp \rep{\ter{,} exp}}
  610. \end{Produc}%
  611. Expressions are discussed in \See{expressions}.
  612. Before the assignment,
  613. the list of values is \emph{adjusted} to the length of
  614. the list of variables.\index{adjustment}
  615. If there are more values than needed,
  616. the excess values are thrown away.
  617. If there are less values than needed,
  618. the list is extended with as many \nil's as needed.
  619. If the list of expressions ends with a function call,
  620. then all values returned by that function call enter in the list of values,
  621. before the adjust
  622. (except when the call is enclosed in parentheses; see \See{expressions}).
  623. The assignment statement first evaluates all its expressions,
  624. and only then makes the assignments.
  625. So, the code
  626. \begin{verbatim}
  627. i = 3
  628. i, a[i] = i+1, 20
  629. \end{verbatim}
  630. sets \verb|a[3]| to 20, without affecting \verb|a[4]|
  631. because the \verb|i| in \verb|a[i]| is evaluated
  632. before it is assigned 4.
  633. Similarly, the line
  634. \begin{verbatim}
  635. x, y = y, x
  636. \end{verbatim}
  637. exchanges the values of \verb|x| and \verb|y|.
  638. \subsubsection{Control Structures}\label{control}
  639. The control structures
  640. \rwd{if}, \rwd{while}, and \rwd{repeat} have the usual meaning and
  641. familiar syntax:
  642. \index{while-do statement}\IndexKW{while}
  643. \index{repeat-until statement}\IndexKW{repeat}\IndexKW{until}
  644. \index{if-then-else statement}\IndexKW{if}\IndexKW{else}\IndexKW{elseif}
  645. \begin{Produc}
  646. \produc{stat}{\rwd{while} exp \rwd{do} block \rwd{end}}
  647. \produc{stat}{\rwd{repeat} block \rwd{until} exp}
  648. \produc{stat}{\rwd{if} exp \rwd{then} block
  649. \rep{\rwd{elseif} exp \rwd{then} block}
  650. \opt{\rwd{else} block} \rwd{end}}
  651. \end{Produc}%
  652. Lua also has a \rwd{for} statement, in two flavors \see{for}.
  653. The \Index{condition expression} \M{exp} of a
  654. control structure may return any value.
  655. All values different from \nil{} and \False{} are considered true
  656. (in particular, the number 0 and the empty string are also true);
  657. both \False{} and \nil{} are considered false.
  658. The \rwd{return} statement is used to return values
  659. from a function or from a chunk.\IndexKW{return}
  660. \label{return}%
  661. \index{return statement}%
  662. Functions and chunks may return more than one value,
  663. and so the syntax for the \rwd{return} statement is
  664. \begin{Produc}
  665. \produc{stat}{\rwd{return} \opt{explist1}}
  666. \end{Produc}%
  667. The \rwd{break} statement can be used to terminate the execution of a
  668. \rwd{while}, \rwd{repeat}, or \rwd{for} loop,
  669. skipping to the next statement after the loop:\IndexKW{break}
  670. \index{break statement}
  671. \begin{Produc}
  672. \produc{stat}{\rwd{break}}
  673. \end{Produc}%
  674. A \rwd{break} ends the innermost enclosing loop.
  675. \NOTE
  676. For syntactic reasons, \rwd{return} and \rwd{break}
  677. statements can only be written as the \emph{last} statement of a block.
  678. If it is really necessary to \rwd{return} or \rwd{break} in the
  679. middle of a block,
  680. then an explicit inner block can used,
  681. as in the idioms
  682. `\verb|do return end|' and
  683. `\verb|do break end|',
  684. because now \rwd{return} and \rwd{break} are the last statements in
  685. their (inner) blocks.
  686. In practice,
  687. those idioms are only used during debugging.
  688. (For instance, a line `\verb|do return end|' can be added at the
  689. beginning of a chunk for syntax checking only.)
  690. \subsubsection{For Statement} \label{for}\index{for statement}
  691. The \rwd{for} statement has two forms,
  692. one for numbers and one generic.
  693. \IndexKW{for}\IndexKW{in}
  694. The numerical \rwd{for} loop repeats a block of code while a
  695. control variable runs through an arithmetic progression.
  696. It has the following syntax:
  697. \begin{Produc}
  698. \produc{stat}{\rwd{for} \Nter{Name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp}
  699. \rwd{do} block \rwd{end}}
  700. \end{Produc}%
  701. The \emph{block} is repeated for \emph{name} starting at the value of
  702. the first \emph{exp}, until it reaches the second \emph{exp} by steps of the
  703. third \emph{exp}.
  704. More precisely, a \rwd{for} statement like
  705. \begin{verbatim}
  706. for var = e1, e2, e3 do block end
  707. \end{verbatim}
  708. is equivalent to the code:
  709. \begin{verbatim}
  710. do
  711. local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3)
  712. if not (var and _limit and _step) then error() end
  713. while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do
  714. block
  715. var = var+_step
  716. end
  717. end
  718. \end{verbatim}
  719. Note the following:
  720. \begin{itemize}\itemsep=0pt
  721. \item Both the limit and the step are evaluated only once,
  722. before the loop starts.
  723. \item \verb|_limit| and \verb|_step| are invisible variables.
  724. The names are here for explanatory purposes only.
  725. \item The behavior is \emph{undefined} if you assign to \verb|var| inside
  726. the block.
  727. \item If the third expression (the step) is absent, then a step of~1 is used.
  728. \item You can use \rwd{break} to exit a \rwd{for} loop.
  729. \item The loop variable \verb|var| is local to the statement;
  730. you cannot use its value after the \rwd{for} ends or is broken.
  731. If you need the value of the loop variable \verb|var|,
  732. then assign it to another variable before breaking or exiting the loop.
  733. \end{itemize}
  734. The generic \rwd{for} statement works over functions,
  735. called \Index{generators}.
  736. It calls its generator to produce a new value for each iteration,
  737. stopping when the new value is \nil.
  738. It has the following syntax:
  739. \begin{Produc}
  740. \produc{stat}{\rwd{for} \Nter{Name} \rep{\ter{,} \Nter{Name}} \rwd{in} explist1
  741. \rwd{do} block \rwd{end}}
  742. \end{Produc}%
  743. A \rwd{for} statement like
  744. \begin{verbatim}
  745. for var_1, ..., var_n in explist do block end
  746. \end{verbatim}
  747. is equivalent to the code:
  748. \begin{verbatim}
  749. do
  750. local _f, _s, var_1, ..., var_n = explist
  751. while 1 do
  752. var_1, ..., var_n = _f(_s, var_1)
  753. if var_1 == nil then break end
  754. block
  755. end
  756. end
  757. \end{verbatim}
  758. Note the following:
  759. \begin{itemize}\itemsep=0pt
  760. \item \verb|explist| is evaluated only once.
  761. Its results are a ``generator'' function,
  762. a ``state'', and an initial value for the ``iterator variable''.
  763. \item \verb|_f| and \verb|_s| are invisible variables.
  764. The names are here for explanatory purposes only.
  765. \item The behavior is \emph{undefined} if you assign to any
  766. \verb|var_i| inside the block.
  767. \item You can use \rwd{break} to exit a \rwd{for} loop.
  768. \item The loop variables \verb|var_i| are local to the statement;
  769. you cannot use their values after the \rwd{for} ends.
  770. If you need these values,
  771. then assign them to other variables before breaking or exiting the loop.
  772. \end{itemize}
  773. \subsubsection{Function Calls as Statements} \label{funcstat}
  774. Because of possible side-effects,
  775. function calls can be executed as statements:
  776. \begin{Produc}
  777. \produc{stat}{functioncall}
  778. \end{Produc}%
  779. In this case, all returned values are thrown away.
  780. Function calls are explained in \See{functioncall}.
  781. \subsubsection{Local Declarations} \label{localvar}
  782. \Index{Local variables} may be declared anywhere inside a block.
  783. The declaration may include an initial assignment:\IndexKW{local}
  784. \begin{Produc}
  785. \produc{stat}{\rwd{local} namelist \opt{\ter{=} explist1}}
  786. \produc{namelist}{\Nter{Name} \rep{\ter{,} \Nter{Name}}}
  787. \end{Produc}%
  788. If present, an initial assignment has the same semantics
  789. of a multiple assignment \see{assignment}.
  790. Otherwise, all variables are initialized with \nil.
  791. A chunk is also a block \see{chunks},
  792. and so local variables can be declared outside any explicit block.
  793. Such local variables die when the chunk ends.
  794. Visibility rules for local variables are explained in \See{visibility}.
  795. \subsection{\Index{Expressions}}\label{expressions}
  796. %\subsubsection{\Index{Basic Expressions}}
  797. The basic expressions in Lua are the following:
  798. \begin{Produc}
  799. \produc{exp}{prefixexp}
  800. \produc{exp}{\rwd{nil} \Or \rwd{false} \Or \rwd{true}}
  801. \produc{exp}{Number}
  802. \produc{exp}{Literal}
  803. \produc{exp}{function}
  804. \produc{exp}{tableconstructor}
  805. \produc{prefixexp}{var \Or functioncall \Or \ter{(} exp \ter{)}}
  806. \end{Produc}%
  807. \IndexKW{nil}\IndexKW{false}\IndexKW{true}
  808. An expression enclosed in parentheses always results in only one value.
  809. Thus,
  810. \verb|(f(x,y,z))| is always a single value,
  811. even if \verb|f| returns several values.
  812. (The value of \verb|(f(x,y,z))| is the first value returned by \verb|f|
  813. or \nil{} if \verb|f| does not return any values.)
  814. \emph{Numbers} and \emph{literal strings} are explained in \See{lexical};
  815. variables are explained in \See{variables};
  816. function definitions are explained in \See{func-def};
  817. function calls are explained in \See{functioncall};
  818. table constructors are explained in \See{tableconstructor}.
  819. Expressions can also be built with arithmetic operators, relational operators,
  820. and logical operadors, all of which are explained below.
  821. \subsubsection{Arithmetic Operators}
  822. Lua supports the usual \Index{arithmetic operators}:
  823. the binary \verb|+| (addition),
  824. \verb|-| (subtraction), \verb|*| (multiplication),
  825. \verb|/| (division), and \verb|^| (exponentiation);
  826. and unary \verb|-| (negation).
  827. If the operands are numbers, or strings that can be converted to
  828. numbers \see{coercion},
  829. then all operations except exponentiation have the usual meaning,
  830. while exponentiation calls a global function \verb|pow|; ??
  831. otherwise, an appropriate metamethod is called \see{metatable}.
  832. The standard mathematical library defines function \verb|pow|,
  833. giving the expected meaning to \Index{exponentiation}
  834. \see{mathlib}.
  835. \subsubsection{Relational Operators}\label{rel-ops}
  836. The \Index{relational operators} in Lua are
  837. \begin{verbatim}
  838. == ~= < > <= >=
  839. \end{verbatim}
  840. These operators always result in \False{} or \True.
  841. Equality (\verb|==|) first compares the type of its operands.
  842. If the types are different, then the result is \False.
  843. Otherwise, the values of the operands are compared.
  844. Numbers and strings are compared in the usual way.
  845. Tables, userdata, and functions are compared \emph{by reference},
  846. that is,
  847. two tables are considered equal only if they are the \emph{same} table.
  848. %% TODO eq metamethod
  849. Every time you create a new table (or userdata, or function),
  850. this new value is different from any previously existing value.
  851. \NOTE
  852. The conversion rules of \See{coercion}
  853. \emph{do not} apply to equality comparisons.
  854. Thus, \verb|"0"==0| evaluates to \emph{false},
  855. and \verb|t[0]| and \verb|t["0"]| denote different
  856. entries in a table.
  857. \medskip
  858. The operator \verb|~=| is exactly the negation of equality (\verb|==|).
  859. The order operators work as follows.
  860. If both arguments are numbers, then they are compared as such.
  861. Otherwise, if both arguments are strings,
  862. then their values are compared according to the current locale.
  863. Otherwise, the ``lt'' or the ``le'' metamethod is called \see{metatable}.
  864. \subsubsection{Logical Operators}
  865. The \Index{logical operators} in Lua are
  866. \index{and}\index{or}\index{not}
  867. \begin{verbatim}
  868. and or not
  869. \end{verbatim}
  870. Like the control structures \see{control},
  871. all logical operators consider both \False{} and \nil{} as false
  872. and anything else as true.
  873. \IndexKW{and}\IndexKW{or}\IndexKW{not}
  874. The operator \rwd{not} always return \False{} or \True.
  875. The conjunction operator \rwd{and} returns its first argument
  876. if its value is \False{} or \nil;
  877. otherwise, \rwd{and} returns its second argument.
  878. The disjunction operator \rwd{or} returns its first argument
  879. if it is different from \nil and \False;
  880. otherwise, \rwd{or} returns its second argument.
  881. Both \rwd{and} and \rwd{or} use \Index{short-cut evaluation},
  882. that is,
  883. the second operand is evaluated only if necessary.
  884. For example,
  885. \begin{verbatim}
  886. 10 or error() -> 10
  887. nil or "a" -> "a"
  888. nil and 10 -> nil
  889. false and error() -> false
  890. false and nil -> false
  891. false or nil -> nil
  892. 10 and 20 -> 20
  893. \end{verbatim}
  894. \subsubsection{Concatenation} \label{concat}
  895. The string \Index{concatenation} operator in Lua is
  896. denoted by two dots (`\verb|..|').
  897. If both operands are strings or numbers, then they are converted to
  898. strings according to the rules mentioned in \See{coercion}.
  899. Otherwise, the ``concat'' metamethod is called \see{metatable}.
  900. \subsubsection{Precedence}
  901. \Index{Operator precedence} in Lua follows the table below,
  902. from lower to higher priority:
  903. \begin{verbatim}
  904. or
  905. and
  906. < > <= >= ~= ==
  907. ..
  908. + -
  909. * /
  910. not - (unary)
  911. ^
  912. \end{verbatim}
  913. The \verb|..| (concatenation) and \verb|^| (exponentiation)
  914. operators are right associative.
  915. All other binary operators are left associative.
  916. \subsubsection{Table Constructors} \label{tableconstructor}
  917. Table \Index{constructors} are expressions that create tables;
  918. every time a constructor is evaluated, a new table is created.
  919. Constructors can be used to create empty tables,
  920. or to create a table and initialize some of its fields.
  921. The general syntax for constructors is
  922. \begin{Produc}
  923. \produc{tableconstructor}{\ter{\{} \opt{fieldlist} \ter{\}}}
  924. \produc{fieldlist}{field \rep{fieldsep field} \opt{fieldsep}}
  925. \produc{field}{\ter{[} exp \ter{]} \ter{=} exp \Or
  926. \Nter{Name} \ter{=} exp \Or exp}
  927. \produc{fieldsep}{\ter{,} \Or \ter{;}}
  928. \end{Produc}%
  929. Each field of the form \verb|[exp1] = exp2| adds to the new table an entry
  930. with key \verb|exp1| and value \verb|exp2|.
  931. A field of the form \verb|name = exp| is equivalent to
  932. \verb|["name"] = exp|.
  933. Finally, fields of the form \verb|exp| are equivalent to
  934. \verb|[i] = exp|, where \verb|i| are consecutive numerical integers,
  935. starting with 1.
  936. Fields in the other formats do not affect this counting.
  937. For example,
  938. \begin{verbatim}
  939. a = {[f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45}
  940. \end{verbatim}
  941. is equivalent to
  942. \begin{verbatim}
  943. do
  944. local temp = {}
  945. temp[f(1)] = g
  946. temp[1] = "x" -- 1st exp
  947. temp[2] = "y" -- 2nd exp
  948. temp.x = 1 -- temp["x"] = 1
  949. temp[3] = f(x) -- 3rd exp
  950. temp[30] = 23
  951. temp[4] = 45 -- 4th exp
  952. a = temp
  953. end
  954. \end{verbatim}
  955. If the last expression in the list is a function call,
  956. then all values returned by the call enter the list consecutively
  957. \see{functioncall}.
  958. If you want to avoid this,
  959. enclose the function call in parentheses.
  960. The field list may have an optional trailing separator,
  961. as a convenience for machine-generated code.
  962. \subsubsection{Function Calls} \label{functioncall}
  963. A \Index{function call} in Lua has the following syntax:
  964. \begin{Produc}
  965. \produc{functioncall}{prefixexp args}
  966. \end{Produc}%
  967. In a function call,
  968. first \M{prefixexp} and \M{args} are evaluated.
  969. If the value of \M{prefixexp} has type \emph{function},
  970. then that function is called,
  971. with the given arguments.
  972. Otherwise, its ``call'' metamethod is called,
  973. having as first parameter the value of \M{prefixexp},
  974. followed by the original call arguments
  975. \see{metatable}.
  976. The form
  977. \begin{Produc}
  978. \produc{functioncall}{prefixexp \ter{:} \Nter{name} args}
  979. \end{Produc}%
  980. can be used to call ``methods''.
  981. A call \verb|v:name(...)|
  982. is syntactic sugar for \verb|v.name(v, ...)|,
  983. except that \verb|v| is evaluated only once.
  984. Arguments have the following syntax:
  985. \begin{Produc}
  986. \produc{args}{\ter{(} \opt{explist1} \ter{)}}
  987. \produc{args}{tableconstructor}
  988. \produc{args}{Literal}
  989. \end{Produc}%
  990. All argument expressions are evaluated before the call.
  991. A call of the form \verb|f{...}| is syntactic sugar for
  992. \verb|f({...})|, that is,
  993. the argument list is a single new table.
  994. A call of the form \verb|f'...'|
  995. (or \verb|f"..."| or \verb|f[[...]]|) is syntactic sugar for
  996. \verb|f('...')|, that is,
  997. the argument list is a single literal string.
  998. Because a function can return any number of results
  999. \see{return},
  1000. the number of results must be adjusted before they are used.
  1001. If the function is called as a statement \see{funcstat},
  1002. then its return list is adjusted to~0 elements,
  1003. thus discarding all returned values.
  1004. If the function is called inside another expression,
  1005. or in the middle of a list of expressions,
  1006. then its return list is adjusted to~1 element,
  1007. thus discarding all returned values but the first one.
  1008. If the function is called as the last element of a list of expressions,
  1009. then no adjustment is made
  1010. (unless the call is enclosed in parentheses).
  1011. Here are some examples:
  1012. \begin{verbatim}
  1013. f() -- adjusted to 0 results
  1014. g(f(), x) -- f() is adjusted to 1 result
  1015. g(x, f()) -- g gets x plus all values returned by f()
  1016. a,b,c = f(), x -- f() is adjusted to 1 result (and c gets nil)
  1017. a,b,c = x, f() -- f() is adjusted to 2
  1018. a,b,c = f() -- f() is adjusted to 3
  1019. return f() -- returns all values returned by f()
  1020. return x,y,f() -- returns x, y, and all values returned by f()
  1021. {f()} -- creates a list with all values returned by f()
  1022. {f(), nil} -- f() is adjusted to 1 result
  1023. \end{verbatim}
  1024. If you enclose a function call in parentheses,
  1025. then it is adjusted to return exactly one value:
  1026. \begin{verbatim}
  1027. return x,y,(f()) -- returns x, y, and the first value from f()
  1028. {(f())} -- creates a table with exactly one element
  1029. \end{verbatim}
  1030. As an exception to the format-free syntax of Lua,
  1031. you cannot put a line break before the \verb|(| in a function call.
  1032. That restriction avoids some ambiguities in the language.
  1033. If you write
  1034. \begin{verbatim}
  1035. a = f
  1036. (g).x(a)
  1037. \end{verbatim}
  1038. Lua would read that as \verb|a = f(g).x(a)|.
  1039. So, if you want two statements, you must add a semi-colon between them.
  1040. If you actually want to call \verb|f|,
  1041. you must remove the line break before \verb|(g)|.
  1042. \subsubsection{\Index{Function Definitions}} \label{func-def}
  1043. The syntax for function definition is\IndexKW{function}
  1044. \begin{Produc}
  1045. \produc{function}{\rwd{function} funcbody}
  1046. \produc{funcbody}{\ter{(} \opt{parlist1} \ter{)} block \rwd{end}}
  1047. \end{Produc}%
  1048. The following syntactic sugar simplifies function definitions:
  1049. \begin{Produc}
  1050. \produc{stat}{\rwd{function} funcname funcbody}
  1051. \produc{stat}{\rwd{local} \rwd{function} \Nter{name} funcbody}
  1052. \produc{funcname}{\Nter{name} \rep{\ter{.} \Nter{name}} \opt{\ter{:} \Nter{name}}}
  1053. \end{Produc}%
  1054. The statement
  1055. \begin{verbatim}
  1056. function f () ... end
  1057. \end{verbatim}
  1058. translates to
  1059. \begin{verbatim}
  1060. f = function () ... end
  1061. \end{verbatim}
  1062. The statement
  1063. \begin{verbatim}
  1064. function t.a.b.c.f () ... end
  1065. \end{verbatim}
  1066. translates to
  1067. \begin{verbatim}
  1068. t.a.b.c.f = function () ... end
  1069. \end{verbatim}
  1070. The statement
  1071. \begin{verbatim}
  1072. local function f () ... end
  1073. \end{verbatim}
  1074. translates to
  1075. \begin{verbatim}
  1076. local f; f = function () ... end
  1077. \end{verbatim}
  1078. A function definition is an executable expression,
  1079. whose value has type \emph{function}.
  1080. When Lua pre-compiles a chunk,
  1081. all its function bodies are pre-compiled too.
  1082. Then, whenever Lua executes the function definition,
  1083. the function is \emph{instantiated} (or \emph{closed}).
  1084. This function instance (or \emph{closure})
  1085. is the final value of the expression.
  1086. Different instances of the same function
  1087. may refer to different non-local variables \see{visibility}
  1088. and may have different tables of globals \see{global-table}.
  1089. Parameters act as local variables,
  1090. initialized with the argument values:
  1091. \begin{Produc}
  1092. \produc{parlist1}{namelist \opt{\ter{,} \ter{\ldots}}}
  1093. \produc{parlist1}{\ter{\ldots}}
  1094. \end{Produc}%
  1095. \label{vararg}%
  1096. When a function is called,
  1097. the list of \Index{arguments} is adjusted to
  1098. the length of the list of parameters,
  1099. unless the function is a \Def{vararg function},
  1100. which is
  1101. indicated by three dots (`\verb|...|') at the end of its parameter list.
  1102. A vararg function does not adjust its argument list;
  1103. instead, it collects all extra arguments into an implicit parameter,
  1104. called \IndexLIB{arg}.
  1105. The value of \verb|arg| is a table,
  1106. with a field~\verb|n| whose value is the number of extra arguments,
  1107. and the extra arguments at positions 1,~2,~\ldots,~\verb|n|.
  1108. As an example, consider the following definitions:
  1109. \begin{verbatim}
  1110. function f(a, b) end
  1111. function g(a, b, ...) end
  1112. function r() return 1,2,3 end
  1113. \end{verbatim}
  1114. Then, we have the following mapping from arguments to parameters:
  1115. \begin{verbatim}
  1116. CALL PARAMETERS
  1117. f(3) a=3, b=nil
  1118. f(3, 4) a=3, b=4
  1119. f(3, 4, 5) a=3, b=4
  1120. f(r(), 10) a=1, b=10
  1121. f(r()) a=1, b=2
  1122. g(3) a=3, b=nil, arg={n=0}
  1123. g(3, 4) a=3, b=4, arg={n=0}
  1124. g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2}
  1125. g(5, r()) a=5, b=1, arg={2, 3; n=2}
  1126. \end{verbatim}
  1127. Results are returned using the \rwd{return} statement \see{return}.
  1128. If control reaches the end of a function
  1129. without encountering a \rwd{return} statement,
  1130. then the function returns with no results.
  1131. The \emph{colon} syntax
  1132. is used for defining \IndexEmph{methods},
  1133. that is, functions that have an implicit extra parameter \IndexVerb{self}.
  1134. Thus, the statement
  1135. \begin{verbatim}
  1136. function t.a.b.c:f (...) ... end
  1137. \end{verbatim}
  1138. is syntactic sugar for
  1139. \begin{verbatim}
  1140. t.a.b.c.f = function (self, ...) ... end
  1141. \end{verbatim}
  1142. \subsection{Visibility Rules} \label{visibility}
  1143. \index{visibility}
  1144. Lua is a lexically scoped language.
  1145. The scope of variables begins at the first statement \emph{after}
  1146. their declaration and lasts until the end of the innermost block that
  1147. includes the declaration.
  1148. For instance:
  1149. \begin{verbatim}
  1150. x = 10 -- global variable
  1151. do -- new block
  1152. local x = x -- new `x', with value 10
  1153. print(x) --> 10
  1154. x = x+1
  1155. do -- another block
  1156. local x = x+1 -- another `x'
  1157. print(x) --> 12
  1158. end
  1159. print(x) --> 11
  1160. end
  1161. print(x) --> 10 (the global one)
  1162. \end{verbatim}
  1163. Notice that, in a declaration like \verb|local x = x|,
  1164. the new \verb|x| being declared is not in scope yet,
  1165. so the second \verb|x| refers to the ``outside'' variable.
  1166. Because of those \Index{lexical scoping} rules,
  1167. local variables can be freely accessed by functions
  1168. defined inside their scope.
  1169. For instance:
  1170. \begin{verbatim}
  1171. local counter = 0
  1172. function inc (x)
  1173. counter = counter + x
  1174. return counter
  1175. end
  1176. \end{verbatim}
  1177. Notice that each execution of a \rwd{local} statement
  1178. ``creates'' new local variables.
  1179. Consider the following example:
  1180. \begin{verbatim}
  1181. a = {}
  1182. local x = 20
  1183. for i=1,10 do
  1184. local y = 0
  1185. a[i] = function () y=y+1; return x+y end
  1186. end
  1187. \end{verbatim}
  1188. In that code,
  1189. each function uses a different \verb|y| variable,
  1190. while all of them share the same \verb|x|.
  1191. \subsection{Error Handling} \label{error}
  1192. Because Lua is an extension language,
  1193. all Lua actions start from C~code in the host program
  1194. calling a function from the Lua library \see{pcall}.
  1195. Whenever an error occurs during Lua compilation or execution,
  1196. control returns to C,
  1197. which can take appropriate measures
  1198. (such as to print an error message).
  1199. Lua code can explicitly generate an error by calling the
  1200. function \verb|error| \see{pdf-error}.
  1201. If you need to catch errors in Lua,
  1202. you can use the \verb|pcall| function \see{pdf-pcall}.
  1203. \subsection{Metatables} \label{metatable}
  1204. Every table and userdata value in Lua may have a \emph{metatable}.
  1205. This \IndexEmph{metatable} is a table that defines the behavior of
  1206. the original table and userdata under some operations.
  1207. You can query and change the metatable of an object with
  1208. functions \verb|setmetatable| and \verb|getmetatable| \see{pdf-getmetatable}.
  1209. For each of those operations Lua associates a specific key,
  1210. called an \emph{event}.
  1211. When Lua performs one of those operations over a table or a userdata,
  1212. if checks whether that object has a metatable with the corresponding event.
  1213. If so, the value associated with that key (the \IndexEmph{metamethod})
  1214. controls how Lua will perform the operation.
  1215. Metatables control the operations listed next.
  1216. Each operation is identified by its corresponding name.
  1217. The key for each operation is a string with its name prefixed by
  1218. two underscores;
  1219. for instance, the key for operation ``add'' is the
  1220. string \verb|"__add"|.
  1221. The semantics of these operations is better explained by a Lua function
  1222. describing how the interpreter executes that operation.
  1223. %Each function shows how a handler is called,
  1224. %its arguments (that is, its signature),
  1225. %its results,
  1226. %and the default behavior in the absence of a handler.
  1227. The code shown here in Lua is only illustrative;
  1228. the real behavior is hard coded in the interpreter,
  1229. and it is much more efficient than this simulation.
  1230. All functions used in these descriptions
  1231. (\verb|rawget|, \verb|tonumber|, etc.)
  1232. are described in \See{predefined}.
  1233. \begin{description}
  1234. \item[``add'':]\IndexTM{add}
  1235. the \verb|+| operation.
  1236. The function \verb|getbinhandler| below defines how Lua chooses a handler
  1237. for a binary operation.
  1238. First, Lua tries the first operand.
  1239. If its type does not define a handler for the operation,
  1240. then Lua tries the second operand.
  1241. \begin{verbatim}
  1242. function getbinhandler (op1, op2, event)
  1243. return metatable(op1)[event] or metatable(op2)[event]
  1244. end
  1245. \end{verbatim}
  1246. Using that function,
  1247. the behavior of the ``add'' operation is
  1248. \begin{verbatim}
  1249. function add_event (op1, op2)
  1250. local o1, o2 = tonumber(op1), tonumber(op2)
  1251. if o1 and o2 then -- both operands are numeric
  1252. return o1+o2 -- '+' here is the primitive 'add'
  1253. else -- at least one of the operands is not numeric
  1254. local h = getbinhandler(op1, op2, "__add")
  1255. if h then
  1256. -- call the handler with both operands
  1257. return h(op1, op2)
  1258. else -- no handler available: default behavior
  1259. error("unexpected type at arithmetic operation")
  1260. end
  1261. end
  1262. end
  1263. \end{verbatim}
  1264. \item[``sub'':]\IndexTM{sub}
  1265. the \verb|-| operation.
  1266. Behavior similar to the ``add'' operation.
  1267. \item[``mul'':]\IndexTM{mul}
  1268. the \verb|*| operation.
  1269. Behavior similar to the ``add'' operation.
  1270. \item[``div'':]\IndexTM{div}
  1271. the \verb|/| operation.
  1272. Behavior similar to the ``add'' operation.
  1273. \item[``pow'':]\IndexTM{pow}
  1274. the \verb|^| operation (exponentiation) operation.
  1275. \begin{verbatim} ??
  1276. function pow_event (op1, op2)
  1277. local h = getbinhandler(op1, op2, "__pow") ???
  1278. if h then
  1279. -- call the handler with both operands
  1280. return h(op1, op2)
  1281. else -- no handler available: default behavior
  1282. error("unexpected type at arithmetic operation")
  1283. end
  1284. end
  1285. \end{verbatim}
  1286. \item[``unm'':]\IndexTM{unm}
  1287. the unary \verb|-| operation.
  1288. \begin{verbatim}
  1289. function unm_event (op)
  1290. local o = tonumber(op)
  1291. if o then -- operand is numeric
  1292. return -o -- '-' here is the primitive 'unm'
  1293. else -- the operand is not numeric.
  1294. -- Try to get a handler from the operand;
  1295. local h = metatable(op).__unm
  1296. if h then
  1297. -- call the handler with the operand and nil
  1298. return h(op, nil)
  1299. else -- no handler available: default behavior
  1300. error("unexpected type at arithmetic operation")
  1301. end
  1302. end
  1303. end
  1304. \end{verbatim}
  1305. \item[``lt'':]\IndexTM{lt}
  1306. the \verb|<| operation.
  1307. \begin{verbatim}
  1308. function lt_event (op1, op2)
  1309. if type(op1) == "number" and type(op2) == "number" then
  1310. return op1 < op2 -- numeric comparison
  1311. elseif type(op1) == "string" and type(op2) == "string" then
  1312. return op1 < op2 -- lexicographic comparison
  1313. else
  1314. local h = getbinhandler(op1, op2, "__lt")
  1315. if h then
  1316. return h(op1, op2)
  1317. else
  1318. error("unexpected type at comparison");
  1319. end
  1320. end
  1321. end
  1322. \end{verbatim}
  1323. \verb|a>b| is equivalent to \verb|b<a|.
  1324. \item[``le'':]\IndexTM{lt}
  1325. the \verb|<=| operation.
  1326. \begin{verbatim}
  1327. function lt_event (op1, op2)
  1328. if type(op1) == "number" and type(op2) == "number" then
  1329. return op1 < op2 -- numeric comparison
  1330. elseif type(op1) == "string" and type(op2) == "string" then
  1331. return op1 < op2 -- lexicographic comparison
  1332. else
  1333. local h = getbinhandler(op1, op2, "__le")
  1334. if h then
  1335. return h(op1, op2)
  1336. else
  1337. h = getbinhandler(op1, op2, "__lt")
  1338. if h then
  1339. return not h(op2, op1)
  1340. else
  1341. error("unexpected type at comparison");
  1342. end
  1343. end
  1344. end
  1345. end
  1346. \end{verbatim}
  1347. \verb|a>=b| is equivalent to \verb|b<=a|.
  1348. Notice that, in the absence of a ``le'' metamethod,
  1349. Lua tries the ``lt'', assuming that \verb|a<=b| is
  1350. equivalent to \verb|not (b<a)|.
  1351. \item[``concat'':]\IndexTM{concatenation}
  1352. the \verb|..| (concatenation) operation.
  1353. \begin{verbatim}
  1354. function concat_event (op1, op2)
  1355. if (type(op1) == "string" or type(op1) == "number") and
  1356. (type(op2) == "string" or type(op2) == "number") then
  1357. return op1..op2 -- primitive string concatenation
  1358. else
  1359. local h = getbinhandler(op1, op2, "__concat")
  1360. if h then
  1361. return h(op1, op2)
  1362. else
  1363. error("unexpected type for concatenation")
  1364. end
  1365. end
  1366. end
  1367. \end{verbatim}
  1368. \item[``index'':]\IndexTM{index}
  1369. The ``gettable'' operation \verb|table[key]|.
  1370. \begin{verbatim}
  1371. function gettable_event (table, key)
  1372. local h
  1373. if type(table) == "table" then
  1374. local v = rawget(table, key)
  1375. if v ~= nil then return v end
  1376. h = metatable(table).__index
  1377. if h == nil then return nil end
  1378. else
  1379. h = metatable(table).__index
  1380. if h == nil then
  1381. error("indexed expression not a table");
  1382. end
  1383. end
  1384. if type(h) == "function" then
  1385. return h(table, key) -- call the handler
  1386. else return h[key] -- or repeat operation with it
  1387. end
  1388. \end{verbatim}
  1389. \item[``newindex'':]\IndexTM{index}
  1390. The ``settable'' operation \verb|table[key] = value|.
  1391. \begin{verbatim}
  1392. function settable_event (table, key, value)
  1393. local h
  1394. if type(table) == "table" then
  1395. local v = rawget(table, key)
  1396. if v ~= nil then rawset(table, key, value); return end
  1397. h = metatable(table).__newindex
  1398. if h == nil then rawset(table, key, value); return end
  1399. else
  1400. h = metatable(table).__newindex
  1401. if h == nil then
  1402. error("indexed expression not a table");
  1403. end
  1404. end
  1405. if type(h) == "function" then
  1406. return h(table, key,value) -- call the handler
  1407. else h[key] = value -- or repeat operation with it
  1408. end
  1409. \end{verbatim}
  1410. \item[``call'':]\IndexTM{call}
  1411. called when Lua calls a value.
  1412. \begin{verbatim}
  1413. function function_event (func, ...)
  1414. if type(func) == "function" then
  1415. return func(unpack(arg)) -- regular call
  1416. else
  1417. local h = metatable(func).__call
  1418. if h then
  1419. tinsert(arg, 1, func)
  1420. return h(unpack(arg))
  1421. else
  1422. error("call expression not a function")
  1423. end
  1424. end
  1425. end
  1426. \end{verbatim}
  1427. \end{description}
  1428. \subsubsection{Metatables and Garbage collection}
  1429. Metatables may also define \IndexEmph{finalizer} methods
  1430. for userdata values.
  1431. For each userdata to be collected,
  1432. Lua does the equivalent of the following function:
  1433. \begin{verbatim}
  1434. function gc_event (obj)
  1435. local h = metatable(obj).__gc
  1436. if h then
  1437. h(obj)
  1438. end
  1439. end
  1440. \end{verbatim}
  1441. In a garbage-collection cycle,
  1442. the finalizers for userdata are called in \emph{reverse}
  1443. order of their creation,
  1444. that is, the first finalizer to be called is the one associated
  1445. with the last userdata created in the program
  1446. (among those to be collected in the same cycle).
  1447. \subsection{Coroutines}
  1448. Lua supports coroutines,
  1449. also called \emph{semi-coroutines}, \emph{generators},
  1450. or \emph{colaborative multithreading}.
  1451. A coroutine in Lua represents an independent thread of execution.
  1452. Unlike ``real'' threads, however,
  1453. a coroutine only suspends its execution by explicitly calling
  1454. an yield function.
  1455. You create a coroutine with a call to \IndexVerb{coroutine.create}.
  1456. Its sole argument is a function,
  1457. which is the main function of the coroutine.
  1458. The \verb|coroutine.create| only creates a new coroutine and
  1459. returns a handle to it (an object of type \emph{thread}).
  1460. It does not start the coroutine execution.
  1461. When you first call \IndexVerb{coroutine.resume},
  1462. passing as argument the thread returned by \verb|coroutine.create|,
  1463. the coroutine starts its execution,
  1464. at the first line of its main function.
  1465. Extra arguments passed to \verb|coroutine.resume| are given as
  1466. parameters for the coroutine main function.
  1467. After the coroutine starts running,
  1468. it runs until it terminates or it \emph{yields}.
  1469. A coroutine can terminate its execution in two ways:
  1470. Normally, when its main function returns
  1471. (explicitly or implicitly, after the last instruction);
  1472. and abnormally, if there is an unprotected error.
  1473. In the first case, \verb|coroutine.resume| returns \True,
  1474. plus any values returned by the coroutine main function.
  1475. In case of errors, \verb|coroutine.resume| returns \False
  1476. plus an error message.
  1477. A coroutine yields calling \IndexVerb{coroutine.yield}.
  1478. When a coroutine yields,
  1479. the corresponding \verb|coroutine.resume| returns immediately,
  1480. even if the yield happens inside nested function calls
  1481. (that is, not in the main function,
  1482. but in a function directly or indirectly called by the main function).
  1483. In the case of a yield, \verb|coroutine.resume| also returns \True,
  1484. plus any values passed to \verb|coroutine.yield|.
  1485. The next time you resume the same coroutine,
  1486. it continues its execution from the point where it yielded,
  1487. with the call to \verb|coroutine.yield| returning any extra
  1488. arguments passed to \verb|coroutine.resume|.
  1489. The \IndexVerb{coroutine.wrap} function creates a coroutine
  1490. like \verb|coroutine.create|,
  1491. but instead of returning the coroutine itself,
  1492. it returns a function that, when called, resumes the coroutine.
  1493. Any arguments passed to that function
  1494. go as extra arguments to resume.
  1495. The function returns all the values returned by resume,
  1496. but the first one (the boolean error code).
  1497. Unlike \verb|coroutine.resume|,
  1498. this function does not catch errors;
  1499. any error is propagated to the caller.
  1500. As a complete example,
  1501. consider the next code:
  1502. \begin{verbatim}
  1503. function foo1 (a)
  1504. print("foo", a)
  1505. return coroutine.yield(2*a)
  1506. end
  1507. co = coroutine.create(function (a,b)
  1508. print("co-body", a, b)
  1509. local r = foo1(a+1)
  1510. print("co-body", r)
  1511. local r, s = coroutine.yield(a+b, a-b)
  1512. print("co-body", r, s)
  1513. return b, "end"
  1514. end)
  1515. a, b = coroutine.resume(co, 1, 10)
  1516. print("main", a, b)
  1517. a, b, c = coroutine.resume(co, "r")
  1518. print("main", a, b, c)
  1519. a, b, c = coroutine.resume(co, "x", "y")
  1520. print("main", a, b, c)
  1521. a, b = coroutine.resume(co, "x", "y")
  1522. print("main", a, b)
  1523. \end{verbatim}
  1524. When you run it, it produces the following output:
  1525. \begin{verbatim}
  1526. co-body 1 10
  1527. foo 2
  1528. main true 4
  1529. co-body r
  1530. main true 11 -9
  1531. co-body x y
  1532. main true 10 end
  1533. main false cannot resume dead coroutine
  1534. \end{verbatim}
  1535. %------------------------------------------------------------------------------
  1536. \section{The Application Program Interface}\label{API}
  1537. \index{C API}
  1538. This section describes the API for Lua, that is,
  1539. the set of C~functions available to the host program to communicate
  1540. with Lua.
  1541. All API functions and related types and constants
  1542. are declared in the header file \verb|lua.h|.
  1543. \NOTE
  1544. Even when we use the term ``function'',
  1545. any facility in the API may be provided as a \emph{macro} instead.
  1546. All such macros use each of its arguments exactly once
  1547. (except for the first argument, which is always a Lua state),
  1548. and so do not generate hidden side-effects.
  1549. \subsection{States} \label{mangstate}
  1550. The Lua library is fully reentrant:
  1551. it has no global variables.
  1552. \index{state}
  1553. The whole state of the Lua interpreter
  1554. (global variables, stack, etc.)
  1555. is stored in a dynamically allocated structure of type \verb|lua_State|;
  1556. \DefAPI{lua_State}
  1557. this state must be passed as the first argument to
  1558. every function in the library (except \verb|lua_open| below).
  1559. Before calling any API function,
  1560. you must create a state by calling
  1561. \begin{verbatim}
  1562. lua_State *lua_open (void);
  1563. \end{verbatim}
  1564. \DefAPI{lua_open}
  1565. To release a state created with \verb|lua_open|, call
  1566. \begin{verbatim}
  1567. void lua_close (lua_State *L);
  1568. \end{verbatim}
  1569. \DefAPI{lua_close}
  1570. This function destroys all objects in the given Lua environment
  1571. (calling the corresponding garbage-collection metamethods, if any)
  1572. and frees all dynamic memory used by that state.
  1573. On several platforms, you may not need to call this function,
  1574. because all resources are naturally released when the host program ends.
  1575. On the other hand,
  1576. long-running programs ---
  1577. like a daemon or a web server ---
  1578. might need to release states as soon as they are not needed,
  1579. to avoid growing too large.
  1580. With the exception of \verb|lua_open|,
  1581. all functions in the Lua API need a state as their first argument.
  1582. \subsection{Threads}
  1583. Lua offers a partial support for multiple threads of execution.
  1584. If you have a C~library that offers multi-threading,
  1585. then Lua can cooperate with it to implement the equivalent facility in Lua.
  1586. Also, Lua implements its own coroutine system on top of threads.
  1587. The following function creates a new ``thread'' in Lua:
  1588. \begin{verbatim}
  1589. lua_State *lua_newthread (lua_State *L);
  1590. \end{verbatim}
  1591. \DefAPI{lua_newthread}
  1592. The new state returned by this function shares with the original state
  1593. all global environment (such as tables),
  1594. but has an independent run-time stack.
  1595. (The use of these multiple stacks must be ``syncronized'' with C.
  1596. How to explain that? TO BE WRITTEN.)
  1597. Each thread has an independent table for global variables.
  1598. When you create a thread, this table is the same as that of the given state,
  1599. but you can change each one independently.
  1600. You destroy threads with \DefAPI{lua_closethread}
  1601. \begin{verbatim}
  1602. void lua_closethread (lua_State *L, lua_State *thread);
  1603. \end{verbatim}
  1604. You cannot close the sole (or last) thread of a state.
  1605. Instead, you must close the state itself.
  1606. \subsection{The Stack and Indices}
  1607. Lua uses a virtual \emph{stack} to pass values to and from C.
  1608. Each element in this stack represents a Lua value
  1609. (\nil, number, string, etc.).
  1610. Each C invocation has its own stack.
  1611. Whenever Lua calls C, the called function gets a new stack,
  1612. which is independent of previous stacks or of stacks of still
  1613. active C functions.
  1614. That stack contains initially any arguments to the C function,
  1615. and it is where the C function pushes its results \see{LuacallC}.
  1616. For convenience,
  1617. most query operations in the API do not follow a strict stack discipline.
  1618. Instead, they can refer to any element in the stack by using an \emph{index}:
  1619. A positive index represents an \emph{absolute} stack position
  1620. (starting at~1);
  1621. a negative index represents an \emph{offset} from the top of the stack.
  1622. More specifically, if the stack has \M{n} elements,
  1623. then index~1 represents the first element
  1624. (that is, the element that was pushed onto the stack first),
  1625. and
  1626. index~\M{n} represents the last element;
  1627. index~\Math{-1} also represents the last element
  1628. (that is, the element at the top),
  1629. and index \Math{-n} represents the first element.
  1630. We say that an index is \emph{valid}
  1631. if it lies between~1 and the stack top
  1632. (that is, if \verb|1 <= abs(index) <= top|).
  1633. \index{stack index} \index{valid index}
  1634. At any time, you can get the index of the top element by calling
  1635. \begin{verbatim}
  1636. int lua_gettop (lua_State *L);
  1637. \end{verbatim}
  1638. \DefAPI{lua_gettop}
  1639. Because indices start at~1,
  1640. the result of \verb|lua_gettop| is equal to the number of elements in the stack
  1641. (and so 0~means an empty stack).
  1642. When you interact with Lua API,
  1643. \emph{you are responsible for controlling stack overflow}.
  1644. The function
  1645. \begin{verbatim}
  1646. int lua_checkstack (lua_State *L, int extra);
  1647. \end{verbatim}
  1648. \DefAPI{lua_checkstack}
  1649. grows the stack size to \verb|top + extra| elements;
  1650. it returns false if it cannot grow the stack to that size.
  1651. This function never shrinks the stack;
  1652. if the stack is already bigger than the new size,
  1653. it is left unchanged.
  1654. Whenever Lua calls C, \DefAPI{LUA_MINSTACK}
  1655. it ensures that \verb|lua_checkstack(L, LUA_MINSTACK)| is true,
  1656. that is,
  1657. at least \verb|LUA_MINSTACK| positions are still available.
  1658. \verb|LUA_MINSTACK| is defined in \verb|lua.h| as 20,
  1659. so that usually you do not have to worry about stack space
  1660. unless your code has loops pushing elements onto the stack.
  1661. Most query functions accept as indices any value inside the
  1662. available stack space, that is, indices up to the maximum stack size
  1663. you (or Lua) have set through \verb|lua_checkstack|.
  1664. Such indices are called \emph{acceptable indices}.
  1665. More formally, we define an \IndexEmph{acceptable index}
  1666. as follows:
  1667. \begin{verbatim}
  1668. (index < 0 && abs(index) <= top) || (index > 0 && index <= top + stackspace)
  1669. \end{verbatim}
  1670. Note that 0 is never an acceptable index.
  1671. Unless otherwise noticed,
  1672. any function that accepts valid indices can also be called with
  1673. \Index{pseudo-indices},
  1674. which represent some Lua values that are accessible to the C~code
  1675. but are not in the stack.
  1676. Pseudo-indices are used to access the table of globals \see{globals},
  1677. the registry, and the upvalues of a C function \see{c-closure}.
  1678. \subsection{Stack Manipulation}
  1679. The API offers the following functions for basic stack manipulation:
  1680. \begin{verbatim}
  1681. void lua_settop (lua_State *L, int index);
  1682. void lua_pushvalue (lua_State *L, int index);
  1683. void lua_remove (lua_State *L, int index);
  1684. void lua_insert (lua_State *L, int index);
  1685. void lua_replace (lua_State *L, int index);
  1686. \end{verbatim}
  1687. \DefAPI{lua_settop}\DefAPI{lua_pushvalue}
  1688. \DefAPI{lua_remove}\DefAPI{lua_insert}\DefAPI{lua_replace}
  1689. \verb|lua_settop| accepts any acceptable index,
  1690. or 0,
  1691. and sets the stack top to that index.
  1692. If the new top is larger than the old one,
  1693. then the new elements are filled with \nil.
  1694. If \verb|index| is 0, then all stack elements are removed.
  1695. A useful macro defined in the \verb|lua.h| is
  1696. \begin{verbatim}
  1697. #define lua_pop(L,n) lua_settop(L, -(n)-1)
  1698. \end{verbatim}
  1699. \DefAPI{lua_pop}
  1700. which pops \verb|n| elements from the stack.
  1701. \verb|lua_pushvalue| pushes onto the stack a copy of the element
  1702. at the given index.
  1703. \verb|lua_remove| removes the element at the given position,
  1704. shifting down the elements above that position to fill the gap.
  1705. \verb|lua_insert| moves the top element into the given position,
  1706. shifting up the elements above that position to open space.
  1707. \verb|lua_replace| moves the top element into the given position,
  1708. without shifting any element (therefore replacing the value at
  1709. the given position).
  1710. These functions accept only valid indices.
  1711. (Obviously, you cannot call \verb|lua_remove| or \verb|lua_insert| with
  1712. pseudo-indices, as they do not represent a stack position.)
  1713. As an example, if the stack starts as \verb|10 20 30 40 50*|
  1714. (from bottom to top; the \verb|*| marks the top),
  1715. then
  1716. \begin{verbatim}
  1717. lua_pushvalue(L, 3) --> 10 20 30 40 50 30*
  1718. lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30*
  1719. lua_remove(L, -3) --> 10 20 30 40 30 30*
  1720. lua_remove(L, 6) --> 10 20 30 40 30*
  1721. lua_insert(L, 1) --> 30 10 20 30 40*
  1722. lua_insert(L, -1) --> 30 10 20 30 40* (no effect)
  1723. lua_replace(L, 2) --> 30 40 20 30*
  1724. lua_settop(L, -3) --> 30 40*
  1725. lua_settop(L, 6) --> 30 40 nil nil nil nil*
  1726. \end{verbatim}
  1727. \subsection{Querying the Stack}
  1728. To check the type of a stack element,
  1729. the following functions are available:
  1730. \begin{verbatim}
  1731. int lua_type (lua_State *L, int index);
  1732. int lua_isnil (lua_State *L, int index);
  1733. int lua_isboolean (lua_State *L, int index);
  1734. int lua_isnumber (lua_State *L, int index);
  1735. int lua_isstring (lua_State *L, int index);
  1736. int lua_istable (lua_State *L, int index);
  1737. int lua_isfunction (lua_State *L, int index);
  1738. int lua_iscfunction (lua_State *L, int index);
  1739. int lua_isuserdata (lua_State *L, int index);
  1740. int lua_islightuserdata (lua_State *L, int index);
  1741. \end{verbatim}
  1742. \DefAPI{lua_type}
  1743. \DefAPI{lua_isnil}\DefAPI{lua_isnumber}\DefAPI{lua_isstring}
  1744. \DefAPI{lua_istable}\DefAPI{lua_isboolean}
  1745. \DefAPI{lua_isfunction}\DefAPI{lua_iscfunction}
  1746. \DefAPI{lua_isuserdata}\DefAPI{lua_islightuserdata}
  1747. These functions can be called with any acceptable index.
  1748. \verb|lua_type| returns the type of a value in the stack,
  1749. or \verb|LUA_TNONE| for a non-valid index
  1750. (that is, if that stack position is ``empty'').
  1751. The types are coded by the following constants
  1752. defined in \verb|lua.h|:
  1753. \verb|LUA_TNIL|,
  1754. \verb|LUA_TNUMBER|,
  1755. \verb|LUA_TBOOLEAN|,
  1756. \verb|LUA_TSTRING|,
  1757. \verb|LUA_TTABLE|,
  1758. \verb|LUA_TFUNCTION|,
  1759. \verb|LUA_TUSERDATA|,
  1760. \verb|LUA_TLIGHTUSERDATA|.
  1761. The following function translates such constants to a type name:
  1762. \begin{verbatim}
  1763. const char *lua_typename (lua_State *L, int type);
  1764. \end{verbatim}
  1765. \DefAPI{lua_typename}
  1766. The \verb|lua_is*| functions return~1 if the object is compatible
  1767. with the given type, and 0 otherwise.
  1768. \verb|lua_isboolean| is an exception to this rule,
  1769. and it succeeds only for boolean values
  1770. (otherwise it would be useless,
  1771. as any value has a boolean value).
  1772. They always return 0 for a non-valid index.
  1773. \verb|lua_isnumber| accepts numbers and numerical strings,
  1774. \verb|lua_isstring| accepts strings and numbers \see{coercion},
  1775. \verb|lua_isfunction| accepts both Lua functions and C~functions,
  1776. and \verb|lua_isuserdata| accepts both full and ligth userdata.
  1777. To distinguish between Lua functions and C~functions,
  1778. you should use \verb|lua_iscfunction|.
  1779. To distinguish between full and ligth userdata,
  1780. you can use \verb|lua_islightuserdata|.
  1781. To distinguish between numbers and numerical strings,
  1782. you can use \verb|lua_type|.
  1783. The API also has functions to compare two values in the stack:
  1784. \begin{verbatim}
  1785. int lua_equal (lua_State *L, int index1, int index2);
  1786. int lua_lessthan (lua_State *L, int index1, int index2);
  1787. \end{verbatim}
  1788. \DefAPI{lua_equal} \DefAPI{lua_lessthan}
  1789. These functions are equivalent to their counterparts in Lua \see{rel-ops}.
  1790. Both functions return 0 if any of the indices are non-valid.
  1791. \subsection{Getting Values from the Stack}\label{lua-to}
  1792. To translate a value in the stack to a specific C~type,
  1793. you can use the following conversion functions:
  1794. \begin{verbatim}
  1795. int lua_toboolean (lua_State *L, int index);
  1796. lua_Number lua_tonumber (lua_State *L, int index);
  1797. const char *lua_tostring (lua_State *L, int index);
  1798. size_t lua_strlen (lua_State *L, int index);
  1799. lua_CFunction lua_tocfunction (lua_State *L, int index);
  1800. void *lua_touserdata (lua_State *L, int index);
  1801. \end{verbatim}
  1802. \DefAPI{lua_tonumber}\DefAPI{lua_tostring}\DefAPI{lua_strlen}
  1803. \DefAPI{lua_tocfunction}\DefAPI{lua_touserdata}\DefAPI{lua_toboolean}
  1804. These functions can be called with any acceptable index.
  1805. When called with a non-valid index,
  1806. they act as if the given value had an incorrect type.
  1807. \verb|lua_toboolean| converts the Lua value at the given index
  1808. to a C ``boolean'' value (that is, 0 or 1).
  1809. Like all tests in Lua, it returns 1 for any Lua value different from
  1810. \False{} and \nil;
  1811. otherwise it returns 0.
  1812. It also returns 0 when called with a non-valid index.
  1813. (If you want to accept only real boolean values,
  1814. use \verb|lua_isboolean| to test the type of the value.)
  1815. \verb|lua_tonumber| converts the Lua value at the given index
  1816. to a number (by default, \verb|lua_Number| is \verb|double|).
  1817. \DefAPI{lua_Number}
  1818. The Lua value must be a number or a string convertible to number
  1819. \see{coercion}; otherwise, \verb|lua_tonumber| returns~0.
  1820. \verb|lua_tostring| converts the Lua value at the given index to a string
  1821. (\verb|const char*|).
  1822. The Lua value must be a string or a number;
  1823. otherwise, the function returns \verb|NULL|.
  1824. If the value is a number,
  1825. then \verb|lua_tostring| also
  1826. \emph{changes the actual value in the stack to a string}.
  1827. (This change confuses \verb|lua_next|
  1828. when \verb|lua_tostring| is applied to keys.)
  1829. \verb|lua_tostring| returns a fully aligned pointer
  1830. to a string inside the Lua environment.
  1831. This string always has a zero (\verb|'\0'|)
  1832. after its last character (as in~C),
  1833. but may contain other zeros in its body.
  1834. If you do not know whether a string may contain zeros,
  1835. you can use \verb|lua_strlen| to get its actual length.
  1836. Because Lua has garbage collection,
  1837. there is no guarantee that the pointer returned by \verb|lua_tostring|
  1838. will be valid after the corresponding value is removed from the stack.
  1839. So, if you need the string after the current function returns,
  1840. then you should duplicate it (or put it into the registry \see{registry}).
  1841. \verb|lua_tocfunction| converts a value in the stack to a C~function.
  1842. This value must be a C~function;
  1843. otherwise, \verb|lua_tocfunction| returns \verb|NULL|.
  1844. The type \verb|lua_CFunction| is explained in \See{LuacallC}.
  1845. \verb|lua_touserdata| is explained in \See{userdata}.
  1846. \subsection{Pushing Values onto the Stack}
  1847. The API has the following functions to
  1848. push C~values onto the stack:
  1849. \begin{verbatim}
  1850. void lua_pushboolean (lua_State *L, int b);
  1851. void lua_pushnumber (lua_State *L, lua_Number n);
  1852. void lua_pushlstring (lua_State *L, const char *s, size_t len);
  1853. void lua_pushstring (lua_State *L, const char *s);
  1854. void lua_pushnil (lua_State *L);
  1855. void lua_pushcfunction (lua_State *L, lua_CFunction f);
  1856. void lua_pushlightuserdata (lua_State *L, void *p);
  1857. \end{verbatim}
  1858. \DefAPI{lua_pushnumber}\DefAPI{lua_pushlstring}\DefAPI{lua_pushstring}
  1859. \DefAPI{lua_pushcfunction}\DefAPI{lua_pushlightuserdata}\DefAPI{lua_pushboolean}
  1860. \DefAPI{lua_pushnil}\label{pushing}
  1861. These functions receive a C~value,
  1862. convert it to a corresponding Lua value,
  1863. and push the result onto the stack.
  1864. In particular, \verb|lua_pushlstring| and \verb|lua_pushstring|
  1865. make an internal copy of the given string.
  1866. \verb|lua_pushstring| can only be used to push proper C~strings
  1867. (that is, strings that end with a zero and do not contain embedded zeros);
  1868. otherwise, you should use the more general \verb|lua_pushlstring|,
  1869. which accepts an explicit size.
  1870. You can also push ``formatted'' strings:
  1871. \begin{verbatim}
  1872. const char *lua_pushfstring (lua_State *L, const char *fmt, ...);
  1873. const char *lua_pushvfstring (lua_State *L, const char *fmt,
  1874. va_list argp);
  1875. \end{verbatim}
  1876. \DefAPI{lua_pushfstring}\DefAPI{lua_pushvfstring}
  1877. Both functions push onto the stack a formatted string,
  1878. and return a pointer to that string.
  1879. These functions are similar to \verb|sprintf| and \verb|vsprintf|,
  1880. but with some important differences:
  1881. \begin{itemize}
  1882. \item You do not have to allocate the space for the result;
  1883. the result is a Lua string, and Lua takes care of memory allocation
  1884. (and deallocation, later).
  1885. \item The conversion specifiers are quite restricted.
  1886. There are no flags, widths, or precisions.
  1887. The conversion specifiers can be simply
  1888. \verb|%%| (inserts a \verb|%| in the string),
  1889. \verb|%s| (inserts a zero-terminated string, with no size restrictions),
  1890. \verb|%f| (inserts a \verb|lua_Number|),
  1891. \verb|%d| (inserts an \verb|int|),
  1892. \verb|%c| (inserts an \verb|int| as a character).
  1893. \end{itemize}
  1894. \subsection{Controlling Garbage Collection}\label{GC-API}
  1895. Lua uses two numbers to control its garbage collection:
  1896. the \emph{count} and the \emph{threshold} \see{GC}.
  1897. The first counts the ammount of memory in use by Lua;
  1898. when the count reaches the threshold,
  1899. Lua runs its garbage collector.
  1900. After the collection, the count is updated,
  1901. and the threshold is set to twice the count value.
  1902. You can access the current values of these two numbers through the
  1903. following functions:
  1904. \begin{verbatim}
  1905. int lua_getgccount (lua_State *L);
  1906. int lua_getgcthreshold (lua_State *L);
  1907. \end{verbatim}
  1908. \DefAPI{lua_getgcthreshold} \DefAPI{lua_getgccount}
  1909. Both return their respective values in Kbytes.
  1910. You can change the threshold value with
  1911. \begin{verbatim}
  1912. void lua_setgcthreshold (lua_State *L, int newthreshold);
  1913. \end{verbatim}
  1914. \DefAPI{lua_setgcthreshold}
  1915. Again, the \verb|newthreshold| value is given in Kbytes.
  1916. When you call this function,
  1917. Lua sets the new threshold and checks it against the byte counter.
  1918. If the new threshold is smaller than the byte counter,
  1919. then Lua immediately runs the garbage collector.
  1920. In particular
  1921. \verb|lua_setgcthreshold(L,0)| forces a garbage collectiion.
  1922. After the collection,
  1923. a new threshold is set according to the previous rule.
  1924. %% TODO do we need a new way to do that??
  1925. % If you want to change the adaptive behavior of the garbage collector,
  1926. % you can use the garbage-collection tag method for \nil{} %
  1927. % to set your own threshold
  1928. % (the tag method is called after Lua resets the threshold).
  1929. \subsection{Userdata}\label{userdata}
  1930. Userdata represents C values in Lua.
  1931. Lua supports two types of userdata:
  1932. \Def{full userdata} and \Def{light userdata}.
  1933. A full userdata represents a block of memory.
  1934. It is an object (like a table):
  1935. You must create it, it can have its own metatable,
  1936. you can detect when it is being collected.
  1937. A full userdata is only equal to itself.
  1938. A light userdata represents a pointer.
  1939. It is a value (like a number):
  1940. You do not create it, it has no metatables,
  1941. it is not collected (as it was never created).
  1942. A light userdata is equal to ``any''
  1943. light userdata with the same address.
  1944. In Lua code, there is no way to test whether a userdata is full or light;
  1945. both have type \verb|userdata|.
  1946. In C code, \verb|lua_type| returns \verb|LUA_TUSERDATA| for full userdata,
  1947. and \verb|LUA_LIGHTUSERDATA| for light userdata.
  1948. You can create new full userdata with the following function:
  1949. \begin{verbatim}
  1950. void *lua_newuserdata (lua_State *L, size_t size);
  1951. \end{verbatim}
  1952. \DefAPI{lua_newuserdata}
  1953. It allocates a new block of memory with the given size,
  1954. pushes on the stack a new userdata with the block address,
  1955. and returns this address.
  1956. To push a light userdata into the stack you use
  1957. \verb|lua_pushlightuserdata| \see{pushing}.
  1958. \verb|lua_touserdata| \see{lua-to} retrieves the value of a userdata.
  1959. When applied on a full userdata, it returns the address of its block;
  1960. when applied on a light userdata, it returns its pointer;
  1961. when applied on a non-userdata value, it returns \verb|NULL|.
  1962. When Lua collects a full userdata,
  1963. it calls its \verb|gc| metamethod, if any,
  1964. and then it frees its corresponding memory.
  1965. \subsection{Metatables}
  1966. The following functions allow you do manipulate the metatables
  1967. of an object:
  1968. \begin{verbatim}
  1969. int lua_getmetatable (lua_State *L, int objindex);
  1970. int lua_setmetatable (lua_State *L, int objindex);
  1971. \end{verbatim}
  1972. \DefAPI{lua_getmetatable}\DefAPI{lua_setmetatable}
  1973. Both get at \verb|objindex| a valid index for an object.
  1974. \verb|lua_getmetatable| pushes on the stack the metatable of that object;
  1975. \verb|lua_setmetatable| sets the table on the top of the stack as the
  1976. new metatable for that object (and pops the table).
  1977. If the object does not have a metatable,
  1978. \verb|lua_getmetatable| returns 0, and pushes nothing on the stack.
  1979. \verb|lua_setmetatable| returns 0 when it cannot
  1980. set the metatable of the given object
  1981. (that is, when the object is not a userdata nor a table);
  1982. even then it pops the table from the stack.
  1983. \subsection{Loading Lua Chunks}
  1984. You can load a Lua chunk with
  1985. \begin{verbatim}
  1986. typedef const char * (*lua_Chunkreader)
  1987. (lua_State *L, void *data, size_t *size);
  1988. int lua_load (lua_State *L, lua_Chunkreader reader, void *data,
  1989. const char *chunkname);
  1990. \end{verbatim}
  1991. \DefAPI{Chunkreader}\DefAPI{lua_load}
  1992. The return values of \verb|lua_load| are:
  1993. \begin{itemize}
  1994. \item 0 --- no errors;
  1995. \item \IndexAPI{LUA_ERRSYNTAX} ---
  1996. syntax error during pre-compilation.
  1997. \item \IndexAPI{LUA_ERRMEM} ---
  1998. memory allocation error.
  1999. \end{itemize}
  2000. If there are no errors,
  2001. \verb|lua_load| pushes the compiled chunk as a Lua
  2002. function on top of the stack.
  2003. Otherwise, it pushes an error message.
  2004. \verb|lua_load| automatically detects whether the chunk is text or binary,
  2005. and loads it accordingly (see program \IndexVerb{luac}).
  2006. \verb|lua_load| uses the \emph{reader} to read the chunk.
  2007. Everytime it needs another piece of the chunk,
  2008. it calls the reader,
  2009. passing along its \verb|data| parameter.
  2010. The reader must return a pointer to a block of memory
  2011. with a new part of the chunk,
  2012. and set \verb|size| to the block size.
  2013. To signal the end of the chunk, the reader must return \verb|NULL|.
  2014. The reader function may return pieces of any size greater than zero.
  2015. In the current implementation,
  2016. the reader function cannot call any Lua function;
  2017. to ensure that, it always receives \verb|NULL| as the Lua state.
  2018. The \emph{chunkname} is used for error messages
  2019. and debug information \see{debugI}.
  2020. See the auxiliar library (\verb|lauxlib|)
  2021. for examples of how to use \verb|lua_load|,
  2022. and for some ready-to-use functions to load chunks
  2023. from files and from strings.
  2024. \subsection{Manipulating Tables}
  2025. Tables are created by calling
  2026. the function
  2027. \begin{verbatim}
  2028. void lua_newtable (lua_State *L);
  2029. \end{verbatim}
  2030. \DefAPI{lua_newtable}
  2031. This function creates a new, empty table and pushes it onto the stack.
  2032. To read a value from a table that resides somewhere in the stack,
  2033. call
  2034. \begin{verbatim}
  2035. void lua_gettable (lua_State *L, int index);
  2036. \end{verbatim}
  2037. \DefAPI{lua_gettable}
  2038. where \verb|index| points to the table.
  2039. \verb|lua_gettable| pops a key from the stack
  2040. and returns (on the stack) the contents of the table at that key.
  2041. The table is left where it was in the stack;
  2042. this is convenient for getting multiple values from a table.
  2043. As in Lua, this function may trigger a metamethod
  2044. for the ``gettable'' or ``index'' events \see{metatable}.
  2045. To get the real value of any table key,
  2046. without invoking any metamethod,
  2047. use the \emph{raw} version:
  2048. \begin{verbatim}
  2049. void lua_rawget (lua_State *L, int index);
  2050. \end{verbatim}
  2051. \DefAPI{lua_rawget}
  2052. To store a value into a table that resides somewhere in the stack,
  2053. you push the key and the value onto the stack
  2054. (in this order),
  2055. and then call
  2056. \begin{verbatim}
  2057. void lua_settable (lua_State *L, int index);
  2058. \end{verbatim}
  2059. \DefAPI{lua_settable}
  2060. where \verb|index| points to the table.
  2061. \verb|lua_settable| pops from the stack both the key and the value.
  2062. The table is left where it was in the stack;
  2063. this is convenient for setting multiple values in a table.
  2064. As in Lua, this operation may trigger a metamethod
  2065. for the ``settable'' or ``newindex'' events.
  2066. To set the real value of any table index,
  2067. without invoking any metamethod,
  2068. use the \emph{raw} version:
  2069. \begin{verbatim}
  2070. void lua_rawset (lua_State *L, int index);
  2071. \end{verbatim}
  2072. \DefAPI{lua_rawset}
  2073. You can traverse a table with the function
  2074. \begin{verbatim}
  2075. int lua_next (lua_State *L, int index);
  2076. \end{verbatim}
  2077. \DefAPI{lua_next}
  2078. where \verb|index| points to the table to be traversed.
  2079. The function pops a key from the stack,
  2080. and pushes a key-value pair from the table
  2081. (the ``next'' pair after the given key).
  2082. If there are no more elements, then \verb|lua_next| returns 0
  2083. (and pushes nothing).
  2084. Use a \nil{} key to signal the start of a traversal.
  2085. A typical traversal looks like this:
  2086. \begin{verbatim}
  2087. /* table is in the stack at index `t' */
  2088. lua_pushnil(L); /* first key */
  2089. while (lua_next(L, t) != 0) {
  2090. /* `key' is at index -2 and `value' at index -1 */
  2091. printf("%s - %s\n",
  2092. lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1)));
  2093. lua_pop(L, 1); /* removes `value'; keeps `key' for next iteration */
  2094. }
  2095. \end{verbatim}
  2096. NOTE:
  2097. While traversing a table,
  2098. do not call \verb|lua_tostring| on a key,
  2099. unless you know the key is actually a string.
  2100. Recall that \verb|lua_tostring| \emph{changes} the value at the given index;
  2101. this confuses the next call to \verb|lua_next|.
  2102. \subsection{Manipulating Global Variables} \label{globals}
  2103. All global variables are kept in an ordinary Lua table.
  2104. This table is always at pseudo-index \IndexAPI{LUA_GLOBALSINDEX}.
  2105. To access and change the value of global variables,
  2106. you can use regular table operations over the global table.
  2107. For instance, to access the value of a global variable, do
  2108. \begin{verbatim}
  2109. lua_pushstring(L, varname);
  2110. lua_gettable(L, LUA_GLOBALSINDEX);
  2111. \end{verbatim}
  2112. You can change the global table of a Lua thread using \verb|lua_replace|.
  2113. \subsection{Using Tables as Arrays}
  2114. The API has functions that help to use Lua tables as arrays,
  2115. that is,
  2116. tables indexed by numbers only:
  2117. \begin{verbatim}
  2118. void lua_rawgeti (lua_State *L, int index, int n);
  2119. void lua_rawseti (lua_State *L, int index, int n);
  2120. \end{verbatim}
  2121. \DefAPI{lua_rawgeti}
  2122. \DefAPI{lua_rawseti}
  2123. \verb|lua_rawgeti| pushes the value of the \M{n}-th element of the table
  2124. at stack position \verb|index|.
  2125. \verb|lua_rawseti| sets the value of the \M{n}-th element of the table
  2126. at stack position \verb|index| to the value at the top of the stack,
  2127. removing this value from the stack.
  2128. \subsection{Calling Functions}
  2129. Functions defined in Lua
  2130. and C~functions registered in Lua
  2131. can be called from the host program.
  2132. This is done using the following protocol:
  2133. First, the function to be called is pushed onto the stack;
  2134. then, the arguments to the function are pushed
  2135. in \emph{direct order}, that is, the first argument is pushed first.
  2136. Finally, the function is called using
  2137. \begin{verbatim}
  2138. void lua_call (lua_State *L, int nargs, int nresults);
  2139. \end{verbatim}
  2140. \DefAPI{lua_call}
  2141. \verb|nargs| is the number of arguments that you pushed onto the stack.
  2142. All arguments and the function value are popped from the stack,
  2143. and the function results are pushed.
  2144. The number of results are adjusted to \verb|nresults|,
  2145. unless \verb|nresults| is \IndexAPI{LUA_MULTRET}.
  2146. In that case, \emph{all} results from the function are pushed.
  2147. Lua takes care that the returned values fit into the stack space.
  2148. The function results are pushed onto the stack in direct order
  2149. (the first result is pushed first),
  2150. so that after the call the last result is on the top.
  2151. The following example shows how the host program may do the
  2152. equivalent to the Lua code:
  2153. \begin{verbatim}
  2154. a = f("how", t.x, 14)
  2155. \end{verbatim}
  2156. Here it is in~C:
  2157. \begin{verbatim}
  2158. lua_pushstring(L, "t");
  2159. lua_gettable(L, LUA_GLOBALSINDEX); /* global `t' (for later use) */
  2160. lua_pushstring(L, "a"); /* var name */
  2161. lua_pushstring(L, "f"); /* function name */
  2162. lua_gettable(L, LUA_GLOBALSINDEX); /* function to be called */
  2163. lua_pushstring(L, "how"); /* 1st argument */
  2164. lua_pushstring(L, "x"); /* push the string "x" */
  2165. lua_gettable(L, -5); /* push result of t.x (2nd arg) */
  2166. lua_pushnumber(L, 14); /* 3rd argument */
  2167. lua_call(L, 3, 1); /* call function with 3 arguments and 1 result */
  2168. lua_settable(L, LUA_GLOBALSINDEX); /* set global variable `a' */
  2169. lua_pop(L, 1); /* remove `t' from the stack */
  2170. \end{verbatim}
  2171. Notice that the code above is ``balanced'':
  2172. at its end, the stack is back to its original configuration.
  2173. This is considered good programming practice.
  2174. (We did this example using only the raw functions provided by Lua's API,
  2175. to show all the details.
  2176. Usually programmers use several macros and auxiliar functions that
  2177. provide higher level access to Lua.)
  2178. \subsection{Protected Calls}\label{pcall}
  2179. When you call a function with \verb|lua_call|,
  2180. any error inside the called function is propagated upwards
  2181. (with a \verb|longjmp|).
  2182. If you need to handle errors,
  2183. then you should use \verb|lua_pcall|:
  2184. \begin{verbatim}
  2185. int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);
  2186. \end{verbatim}
  2187. Both \verb|nargs| and \verb|nresults| have the same meaning as
  2188. in \verb|lua_call|.
  2189. If there are no errors during the call,
  2190. \verb|lua_pcall| behaves exactly like \verb|lua_call|.
  2191. Like \verb|lua_call|,
  2192. \verb|lua_pcall| always removes the function
  2193. and its arguments from the stack.
  2194. However, if there is any error,
  2195. \verb|lua_pcall| catches it,
  2196. pushes a single value at the stack (the error message),
  2197. and returns an error code.
  2198. If \verb|errfunc| is 0,
  2199. then the error message returned is exactly the original error message.
  2200. Otherwise, \verb|errfunc| gives the stack index for an
  2201. \emph{error handler function}.
  2202. (In the current implementation, that index cannot be a pseudo-index.)
  2203. In case of runtime errors,
  2204. that function will be called with the error message,
  2205. and its return value will be the message returned by \verb|lua_pcall|.
  2206. Typically, the error handler function is used to add more debug
  2207. information to the error message, such as a stack traceback.
  2208. Such information cannot be gathered after the return of \verb|lua_pcall|,
  2209. since by then the stack has unwound.
  2210. The \verb|lua_pcall| function returns 0 in case of success,
  2211. or one of the following error codes
  2212. (defined in \verb|lua.h|):
  2213. \begin{itemize}
  2214. \item \IndexAPI{LUA_ERRRUN} --- a runtime error.
  2215. \item \IndexAPI{LUA_ERRMEM} --- memory allocation error.
  2216. For such errors, Lua does not call the error handler function.
  2217. \item \IndexAPI{LUA_ERRERR} ---
  2218. error while running the error handler function.
  2219. \end{itemize}
  2220. \medskip
  2221. >>>>
  2222. %% TODO: mover essas 2 para algum lugar melhor.
  2223. Some special Lua functions have their own C~interfaces.
  2224. The host program can generate a Lua error calling the function
  2225. \begin{verbatim}
  2226. void lua_error (lua_State *L);
  2227. \end{verbatim}
  2228. \DefAPI{lua_error}
  2229. The error message (which actually can be any type of object)
  2230. is popped from the stack.
  2231. This function never returns.
  2232. If \verb|lua_error| is called from a C~function that
  2233. has been called from Lua,
  2234. then the corresponding Lua execution terminates,
  2235. as if an error had occurred inside Lua code.
  2236. Otherwise, the whole host program terminates with a call to
  2237. \verb|exit(EXIT_FAILURE)|.
  2238. %% TODO: at_panic
  2239. The function
  2240. \begin{verbatim}
  2241. void lua_concat (lua_State *L, int n);
  2242. \end{verbatim}
  2243. \DefAPI{lua_concat}
  2244. concatenates the \verb|n| values at the top of the stack,
  2245. pops them, and leaves the result at the top.
  2246. If \verb|n| is 1, the result is that single string
  2247. (that is, the function does nothing);
  2248. if \verb|n| is 0, the result is the empty string.
  2249. Concatenation is done following the usual semantics of Lua
  2250. \see{concat}.
  2251. \subsection{Defining C Functions} \label{LuacallC}
  2252. Lua can be extended with functions written in~C.
  2253. These functions must be of type \verb|lua_CFunction|,
  2254. which is defined as
  2255. \begin{verbatim}
  2256. typedef int (*lua_CFunction) (lua_State *L);
  2257. \end{verbatim}
  2258. \DefAPI{lua_CFunction}
  2259. A C~function receives a Lua environment and returns an integer,
  2260. the number of values it has returned to Lua.
  2261. In order to communicate properly with Lua,
  2262. a C~function must follow the following protocol,
  2263. which defines the way parameters and results are passed:
  2264. A C~function receives its arguments from Lua in its stack,
  2265. in direct order (the first argument is pushed first).
  2266. So, when the function starts,
  2267. its first argument (if any) is at index 1.
  2268. To return values to Lua, a C~function just pushes them onto the stack,
  2269. in direct order (the first result is pushed first),
  2270. and returns the number of results.
  2271. Like a Lua function, a C~function called by Lua can also return
  2272. many results.
  2273. As an example, the following function receives a variable number
  2274. of numerical arguments and returns their average and sum:
  2275. \begin{verbatim}
  2276. static int foo (lua_State *L) {
  2277. int n = lua_gettop(L); /* number of arguments */
  2278. lua_Number sum = 0;
  2279. int i;
  2280. for (i = 1; i <= n; i++) {
  2281. if (!lua_isnumber(L, i)) {
  2282. lua_pushstring(L, "incorrect argument to function `average'");
  2283. lua_error(L);
  2284. }
  2285. sum += lua_tonumber(L, i);
  2286. }
  2287. lua_pushnumber(L, sum/n); /* first result */
  2288. lua_pushnumber(L, sum); /* second result */
  2289. return 2; /* number of results */
  2290. }
  2291. \end{verbatim}
  2292. To register a C~function to Lua,
  2293. there is the following convenience macro:
  2294. \begin{verbatim}
  2295. #define lua_register(L,n,f) \
  2296. (lua_pushstring(L, n), \
  2297. lua_pushcfunction(L, f), \
  2298. lua_settable(L, LUA_GLOBALSINDEX))
  2299. /* const char *n; */
  2300. /* lua_CFunction f; */
  2301. \end{verbatim}
  2302. \DefAPI{lua_register}
  2303. which receives the name the function will have in Lua,
  2304. and a pointer to the function.
  2305. Thus,
  2306. the C~function `\verb|foo|' above may be registered in Lua as `\verb|average|'
  2307. by calling
  2308. \begin{verbatim}
  2309. lua_register(L, "average", foo);
  2310. \end{verbatim}
  2311. \subsection{Defining C Closures} \label{c-closure}
  2312. When a C~function is created,
  2313. it is possible to associate some values to it,
  2314. thus creating a \IndexEmph{C~closure};
  2315. these values are then accessible to the function whenever it is called.
  2316. To associate values to a C~function,
  2317. first these values should be pushed onto the stack
  2318. (when there are multiple values, the first value is pushed first).
  2319. Then the function
  2320. \begin{verbatim}
  2321. void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
  2322. \end{verbatim}
  2323. \DefAPI{lua_pushcclosure}
  2324. is used to push the C~function onto the stack,
  2325. with the argument \verb|n| telling how many values should be
  2326. associated with the function
  2327. (\verb|lua_pushcclosure| also pops these values from the stack);
  2328. in fact, the macro \verb|lua_pushcfunction| is defined as
  2329. \verb|lua_pushcclosure| with \verb|n| set to 0.
  2330. Then, whenever the C~function is called,
  2331. those values are located at specific pseudo-indices.
  2332. Those pseudo-indices are produced by a macro \IndexAPI{lua_upvalueindex}.
  2333. The first value associated with a function is at position
  2334. \verb|lua_upvalueindex(1)|, and so on.
  2335. For examples of C~functions and closures, see files
  2336. \verb|lbaselib.c|, \verb|liolib.c|, \verb|lmathlib.c|, and \verb|lstrlib.c|
  2337. in the official Lua distribution.
  2338. \subsubsection*{Registry} \label{registry}
  2339. Lua provides a pre-defined table that can be used by any C~code to
  2340. store whatever Lua value it needs to store,
  2341. especially if the C~code needs to keep that Lua value
  2342. outside the life span of a C~function.
  2343. This table is always located at pseudo-index
  2344. \IndexAPI{LUA_REGISTRYINDEX}.
  2345. Any C~library can store data into this table,
  2346. as long as it chooses keys different from other libraries.
  2347. Typically, you should use as key a string containing your library name,
  2348. or a light userdata with the address of a C object in your code.
  2349. The integer keys in the registry are used by the reference mechanism,
  2350. implemented by the auxiliar library,
  2351. and therefore should not be used by other purposes.
  2352. %------------------------------------------------------------------------------
  2353. \section{The Debug Interface} \label{debugI}
  2354. Lua has no built-in debugging facilities.
  2355. Instead, it offers a special interface,
  2356. by means of functions and \emph{hooks},
  2357. which allows the construction of different
  2358. kinds of debuggers, profilers, and other tools
  2359. that need ``inside information'' from the interpreter.
  2360. \subsection{Stack and Function Information}
  2361. The main function to get information about the interpreter stack is
  2362. \begin{verbatim}
  2363. int lua_getstack (lua_State *L, int level, lua_Debug *ar);
  2364. \end{verbatim}
  2365. \DefAPI{lua_getstack}
  2366. This function fills parts of a \verb|lua_Debug| structure with
  2367. an identification of the \emph{activation record}
  2368. of the function executing at a given level.
  2369. Level~0 is the current running function,
  2370. whereas level \Math{n+1} is the function that has called level \Math{n}.
  2371. Usually, \verb|lua_getstack| returns 1;
  2372. when called with a level greater than the stack depth,
  2373. it returns 0.
  2374. The structure \verb|lua_Debug| is used to carry different pieces of
  2375. information about an active function:
  2376. \begin{verbatim}
  2377. typedef struct lua_Debug {
  2378. int event;
  2379. const char *name; /* (n) */
  2380. const char *namewhat; /* (n) `global', `local', `field', `method' */
  2381. const char *what; /* (S) `Lua' function, `C' function, Lua `main' */
  2382. const char *source; /* (S) */
  2383. int currentline; /* (l) */
  2384. int nups; /* (u) number of upvalues */
  2385. int linedefined; /* (S) */
  2386. char short_src[LUA_IDSIZE]; /* (S) */
  2387. /* private part */
  2388. ...
  2389. } lua_Debug;
  2390. \end{verbatim}
  2391. \DefAPI{lua_Debug}
  2392. \verb|lua_getstack| fills only the private part
  2393. of this structure, for future use.
  2394. To fill the other fields of \verb|lua_Debug| with useful information,
  2395. call
  2396. \begin{verbatim}
  2397. int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
  2398. \end{verbatim}
  2399. \DefAPI{lua_getinfo}
  2400. This function returns 0 on error
  2401. (for instance, an invalid option in \verb|what|).
  2402. Each character in the string \verb|what|
  2403. selects some fields of \verb|ar| to be filled,
  2404. as indicated by the letter in parentheses in the definition of \verb|lua_Debug|
  2405. above:
  2406. `\verb|S|' fills in the fields \verb|source|, \verb|linedefined|,
  2407. and \verb|what|;
  2408. `\verb|l|' fills in the field \verb|currentline|, etc.
  2409. Moreover, `\verb|f|' pushes onto the stack the function that is
  2410. running at the given level.
  2411. To get information about a function that is not active (that is,
  2412. it is not in the stack),
  2413. you push the function onto the stack,
  2414. and start the \verb|what| string with the character `\verb|>|'.
  2415. For instance, to know in which line a function \verb|f| was defined,
  2416. you can write
  2417. \begin{verbatim}
  2418. lua_Debug ar;
  2419. lua_pushstring(L, "f");
  2420. lua_gettable(L, LUA_GLOBALSINDEX); /* get global `f' */
  2421. lua_getinfo(L, ">S", &ar);
  2422. printf("%d\n", ar.linedefined);
  2423. \end{verbatim}
  2424. The fields of \verb|lua_Debug| have the following meaning:
  2425. \begin{description}\leftskip=20pt
  2426. \item[source]
  2427. If the function was defined in a string,
  2428. then \verb|source| is that string;
  2429. if the function was defined in a file,
  2430. then \verb|source| starts with a \verb|@| followed by the file name.
  2431. \item[short\_src]
  2432. A ``printable'' version of \verb|source|, to be used in error messages.
  2433. \item[linedefined]
  2434. the line number where the definition of the function starts.
  2435. \item[what] the string \verb|"Lua"| if this is a Lua function,
  2436. \verb|"C"| if this is a C~function,
  2437. or \verb|"main"| if this is the main part of a chunk.
  2438. \item[currentline]
  2439. the current line where the given function is executing.
  2440. When no line information is available,
  2441. \verb|currentline| is set to \Math{-1}.
  2442. \item[name]
  2443. a reasonable name for the given function.
  2444. Because functions in Lua are first class values,
  2445. they do not have a fixed name:
  2446. Some functions may be the value of many global variables,
  2447. while others may be stored only in a table field.
  2448. The \verb|lua_getinfo| function checks how the function was
  2449. called or whether it is the value of a global variable to
  2450. find a suitable name.
  2451. If it cannot find a name,
  2452. then \verb|name| is set to \verb|NULL|.
  2453. \item[namewhat]
  2454. Explains the previous field.
  2455. It can be \verb|"global"|, \verb|"local"|, \verb|"method"|,
  2456. \verb|"field"|, or \verb|""| (the empty string),
  2457. according to how the function was called.
  2458. (Lua uses the empty string when no other option seems to apply.)
  2459. \item[nups]
  2460. Number of upvalues of the function.
  2461. \end{description}
  2462. \subsection{Manipulating Local Variables}
  2463. For the manipulation of local variables,
  2464. \verb|luadebug.h| uses indices:
  2465. The first parameter or local variable has index~1, and so on,
  2466. until the last active local variable.
  2467. The following functions allow the manipulation of the
  2468. local variables of a given activation record:
  2469. \begin{verbatim}
  2470. const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
  2471. const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
  2472. \end{verbatim}
  2473. \DefAPI{lua_getlocal}\DefAPI{lua_setlocal}
  2474. The parameter \verb|ar| must be a valid activation record,
  2475. filled by a previous call to \verb|lua_getstack| or
  2476. given as argument to a hook \see{sub-hooks}.
  2477. \verb|lua_getlocal| gets the index \verb|n| of a local variable,
  2478. pushes its value onto the stack,
  2479. and returns its name.
  2480. \verb|lua_setlocal| assigns the value at the top of the stack
  2481. to the variable and returns its name.
  2482. Both functions return \verb|NULL| on failure,
  2483. that is
  2484. when the index is greater than
  2485. the number of active local variables.
  2486. As an example, the following function lists the names of all
  2487. local variables for a function at a given level of the stack:
  2488. \begin{verbatim}
  2489. int listvars (lua_State *L, int level) {
  2490. lua_Debug ar;
  2491. int i = 1;
  2492. const char *name;
  2493. if (lua_getstack(L, level, &ar) == 0)
  2494. return 0; /* failure: no such level in the stack */
  2495. while ((name = lua_getlocal(L, &ar, i++)) != NULL) {
  2496. printf("%s\n", name);
  2497. lua_pop(L, 1); /* remove variable value */
  2498. }
  2499. return 1;
  2500. }
  2501. \end{verbatim}
  2502. \subsection{Hooks}\label{sub-hooks}
  2503. The Lua interpreter offers a mechanism of hooks:
  2504. user-defined C functions that are called during the program execution.
  2505. A hook may be called in four different events:
  2506. a \emph{call} event, when Lua calls a function;
  2507. a \emph{return} event, when Lua returns from a function;
  2508. a \emph{line} event, when Lua starts executing a new line of code;
  2509. and a \emph{count} event, that happens every ``count'' instructions.
  2510. Lua identifies them with the following constants:
  2511. \DefAPI{LUA_HOOKCALL}, \DefAPI{LUA_HOOKRET},
  2512. \DefAPI{LUA_HOOKLINE}, and \DefAPI{LUA_HOOKCOUNT}.
  2513. A hook has type \verb|lua_Hook|, defined as follows:
  2514. \begin{verbatim}
  2515. typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
  2516. \end{verbatim}
  2517. \DefAPI{lua_Hook}
  2518. You can set the hook with the following function:
  2519. \begin{verbatim}
  2520. int lua_sethook (lua_State *L, lua_Hook func, unsigned long mask);
  2521. \end{verbatim}
  2522. \DefAPI{lua_sethook}
  2523. \verb|func| is the hook,
  2524. and \verb|mask| specifies at which events it will be called.
  2525. It is formed by a disjunction of the constants
  2526. \verb|LUA_MASKCALL|,
  2527. \verb|LUA_MASKRET|,
  2528. \verb|LUA_MASKLINE|,
  2529. plus the macro \verb|LUA_MASKCOUNT(count)|.
  2530. For each event, the hook is called as explained below:
  2531. \begin{description}
  2532. \item{call hook} called when the interpreter calls a function.
  2533. The hook is called just after Lua ``enters'' the new function.
  2534. \item{return hook} called when the interpreter returns from a function.
  2535. The hook is called just before Lua ``leaves'' the function.
  2536. \item{line hook} called when the interpreter is about to
  2537. start the execution of a new line of code,
  2538. or when it jumps back (even for the same line).
  2539. (For obvious reasons, this event does not happens while Lua is executing
  2540. a C function.)
  2541. \item{count hook} called after the interpreter executes every
  2542. \verb|count| instructions.
  2543. (For obvious reasons, this event does not happens while Lua is executing
  2544. a C function.)
  2545. \end{description}
  2546. A hook is disabled with the mask zero.
  2547. You can get the current hook and the current mask with the next functions:
  2548. \begin{verbatim}
  2549. lua_Hook lua_gethook (lua_State *L);
  2550. unsigned long lua_gethookmask (lua_State *L);
  2551. \end{verbatim}
  2552. \DefAPI{lua_gethook}\DefAPI{lua_gethookmask}
  2553. You can get the count inside a mask with the macro \verb|lua_getmaskcount|.
  2554. Whenever a hook is called, its \verb|ar| argument has its field
  2555. \verb|event| set to the specific event that triggered the hook.
  2556. Moreover, for line events, the field \verb|currentline| is also set.
  2557. For the value of any other field, the hook must call \verb|lua_getinfo|.
  2558. While Lua is running a hook, it disables other calls to hooks.
  2559. Therefore, if a hook calls Lua to execute a function or a chunk,
  2560. that execution ocurrs without any calls to hooks.
  2561. %------------------------------------------------------------------------------
  2562. \section{Standard Libraries}\label{libraries}
  2563. The standard libraries provide useful functions
  2564. that are implemented directly through the standard C~API.
  2565. Some of these functions provide essential services to the language
  2566. (e.g. \verb|type| and \verb|getmetatable|);
  2567. others provide access to ``outside'' servides (e.g. I/O);
  2568. and others could be implemented in Lua itself,
  2569. but are quite useful or have critical performance to
  2570. deserve an implementation in C (e.g. \verb|sort|).
  2571. All libraries are implemented through the official C API,
  2572. and are provided as separate C~modules.
  2573. Currently, Lua has the following standard libraries:
  2574. \begin{itemize}
  2575. \item basic library;
  2576. \item string manipulation;
  2577. \item table manipulation;
  2578. \item mathematical functions (sin, log, etc.);
  2579. \item input and output;
  2580. \item operating system facilities;
  2581. \item debug facilities.
  2582. \end{itemize}
  2583. Except for the basic library,
  2584. each library provides all its functions as fields of a global table
  2585. or as methods of its objects.
  2586. To have access to these libraries,
  2587. the C~host program must call the functions
  2588. \verb|lua_baselibopen| (for the basic library),
  2589. \verb|lua_strlibopen| (for the string library),
  2590. \verb|lua_tablibopen| (for the table library),
  2591. \verb|lua_mathlibopen| (for the mathematical library),
  2592. \verb|lua_iolibopen| (for the I/O and the Operating System libraries),
  2593. and \verb|lua_dblibopen| (for the debug library),
  2594. which are declared in \verb|lualib.h|.
  2595. \DefAPI{lua_baselibopen}
  2596. \DefAPI{lua_strlibopen}
  2597. \DefAPI{lua_tablibopen}
  2598. \DefAPI{lua_mathlibopen}
  2599. \DefAPI{lua_iolibopen}
  2600. \DefAPI{lua_dblibopen}
  2601. \subsection{Basic Functions} \label{predefined}
  2602. The basic library provides some core functions to Lua.
  2603. If you do not include this library in your application,
  2604. you should check carefully whether you need to provide some alternative
  2605. implementation for some facilities.
  2606. The basic library also defines a global variable \IndexLIB{_VERSION}
  2607. with a string containing the current interpreter version.
  2608. The current content of this string is {\tt "Lua \Version"}.
  2609. \subsubsection*{\ff \T{assert (v [, message])}}\DefLIB{assert}
  2610. Issues an \emph{``assertion failed!''} error
  2611. when its argument \verb|v| is \nil;
  2612. otherwise, returns this argument.
  2613. This function is equivalent to the following Lua function:
  2614. \begin{verbatim}
  2615. function assert (v, m)
  2616. if not v then
  2617. error(m or "assertion failed!")
  2618. end
  2619. return v
  2620. end
  2621. \end{verbatim}
  2622. \subsubsection*{\ff \T{collectgarbage ([limit])}}\DefLIB{collectgarbage}
  2623. Sets the garbage-collection threshold for the given limit
  2624. (in Kbytes), and checks it against the byte counter.
  2625. If the new threshold is smaller than the byte counter,
  2626. then Lua immediately runs the garbage collector \see{GC}.
  2627. If \verb|limit| is absent, it defaults to zero
  2628. (thus forcing a garbage-collection cycle).
  2629. \subsubsection*{\ff \T{dofile (filename)}}\DefLIB{dofile}
  2630. Receives a file name,
  2631. opens the named file, and executes its contents as a Lua chunk.
  2632. When called without arguments,
  2633. \verb|dofile| executes the contents of the standard input (\verb|stdin|).
  2634. Returns any value returned by the chunk.
  2635. \subsubsection*{\ff \T{error (message [, level])}}
  2636. DefLIB{error}\label{pdf-error}
  2637. Terminates the last protected function called,
  2638. and returns \verb|message| as the error message.
  2639. Function \verb|error| never returns.
  2640. The \verb|level| argument affects to where the error
  2641. message points the error.
  2642. With level 1 (the default), the error position is where the
  2643. \verb|error| function was called.
  2644. Level 2 points the error to where the function
  2645. that called \verb|error| was called; and so on.
  2646. \subsubsection*{\ff \T{getglobals (function)}}\DefLIB{getglobals}
  2647. Returns the current table of globals in use by the function.
  2648. \verb|function| can be a Lua function or a number,
  2649. meaning the function at that stack level:
  2650. Level 1 is the function calling \verb|getglobals|.
  2651. If the given function is not a Lua function,
  2652. returns the ``global'' table of globals.
  2653. The default for \verb|function| is 1.
  2654. \subsubsection*{\ff \T{getmetatable (object)}}
  2655. \DefLIB{getmetatable}\label{pdf-getmetatable}
  2656. Returns the metatable of the given object.
  2657. If the object does not have a metatable, returns \nil.
  2658. \subsubsection*{\ff \T{gcinfo ()}}\DefLIB{gcinfo}
  2659. Returns the number of Kbytes of dynamic memory Lua is using,
  2660. and (as a second result) the
  2661. current garbage collector threshold (also in Kbytes).
  2662. \subsubsection*{\ff \T{ipairs (t)}}\DefLIB{ipairs}
  2663. Returns a generator function and the table \verb|t|,
  2664. so that the construction
  2665. \begin{verbatim}
  2666. for i,v in ipairs(t) do ... end
  2667. \end{verbatim}
  2668. will iterate over the pairs \verb|1, t[1]|, \verb|2, t[2]|, \ldots,
  2669. up to the first nil value of the table.
  2670. \subsubsection*{\ff \T{loadfile (filename)}}\DefLIB{loadfile}
  2671. Loads a file as a Lua chunk.
  2672. If there is no errors,
  2673. returns the compiled chunk as a function;
  2674. otherwise, returns \nil{} plus an error message.
  2675. \subsubsection*{\ff \T{loadstring (string [, chunkname])}}\DefLIB{loadstring}
  2676. Loads a string as a Lua chunk.
  2677. If there is no errors,
  2678. returns the compiled chunk as a function;
  2679. otherwise, returns \nil{} plus an error message.
  2680. The optional parameter \verb|chunkname|
  2681. is the ``name of the chunk'',
  2682. used in error messages and debug information.
  2683. To load and run a given string, use the idiom
  2684. \begin{verbatim}
  2685. assert(loadstring(s))()
  2686. \end{verbatim}
  2687. \subsubsection*{\ff \T{next (table, [index])}}\DefLIB{next}
  2688. Allows a program to traverse all fields of a table.
  2689. Its first argument is a table and its second argument
  2690. is an index in this table.
  2691. \verb|next| returns the next index of the table and the
  2692. value associated with the index.
  2693. When called with \nil{} as its second argument,
  2694. \verb|next| returns the first index
  2695. of the table and its associated value.
  2696. When called with the last index,
  2697. or with \nil{} in an empty table,
  2698. \verb|next| returns \nil.
  2699. If the second argument is absent, then it is interpreted as \nil.
  2700. Lua has no declaration of fields;
  2701. semantically, there is no difference between a
  2702. field not present in a table or a field with value \nil.
  2703. Therefore, \verb|next| only considers fields with non-\nil{} values.
  2704. The order in which the indices are enumerated is not specified,
  2705. \emph{even for numeric indices}
  2706. (to traverse a table in numeric order,
  2707. use a numerical \rwd{for} or the function \verb|ipairs|).
  2708. The behavior of \verb|next| is \emph{undefined} if you change
  2709. the table during the traversal.
  2710. \subsubsection*{\ff \T{pairs (t)}}\DefLIB{pairs}
  2711. Returns the function \verb|next| and the table \verb|t|,
  2712. so that the construction
  2713. \begin{verbatim}
  2714. for k,v in pairs(t) do ... end
  2715. \end{verbatim}
  2716. will iterate over all pairs of key--value of table \verb|t|.
  2717. \subsubsection*{\ff \T{pcall (func, arg1, arg2, ...)}}\DefLIB{pcall}
  2718. \label{pdf-pcall}
  2719. Calls function \verb|func| with
  2720. the given arguments in protected mode.
  2721. That means that any error inside \verb|func| is not propagated;
  2722. instead, \verb|pcall| catches the error,
  2723. returning a status code.
  2724. Its first result is the status code (a boolean),
  2725. true if the call succeeds without errors.
  2726. In such case, \verb|pcall| also returns all results from the call,
  2727. after this first result.
  2728. In case of any error, \verb|pcall| returns false plus the error message.
  2729. \subsubsection*{\ff \T{print (e1, e2, ...)}}\DefLIB{print}
  2730. Receives any number of arguments,
  2731. and prints their values in \verb|stdout|,
  2732. using the strings returned by \verb|tostring|.
  2733. This function is not intended for formatted output,
  2734. but only as a quick way to show a value,
  2735. typically for debugging.
  2736. For formatted output, see \verb|format| \see{format}.
  2737. \subsubsection*{\ff \T{rawget (table, index)}}\DefLIB{rawget}
  2738. Gets the real value of \verb|table[index]|,
  2739. without invoking any metamethod.
  2740. \verb|table| must be a table;
  2741. \verb|index| is any value different from \nil.
  2742. \subsubsection*{\ff \T{rawset (table, index, value)}}\DefLIB{rawset}
  2743. Sets the real value of \verb|table[index]| to \verb|value|,
  2744. without invoking any metamethod.
  2745. \verb|table| must be a table;
  2746. \verb|index| is any value different from \nil;
  2747. and \verb|value| is any Lua value.
  2748. \subsubsection*{\ff \T{require (packagename)}}\DefLIB{require}
  2749. Loads the given package.
  2750. The function starts by looking into the table \IndexVerb{_LOADED}
  2751. whether \verb|packagename| is already loaded.
  2752. If it is, then \verb|require| is done.
  2753. Otherwise, it searches a path looking for a file to load.
  2754. If the global variable \IndexVerb{LUA_PATH} is a string,
  2755. this string is the path.
  2756. Otherwise, \verb|require| tries the environment variable \verb|LUA_PATH|.
  2757. In the last resort, it uses a predefined path.
  2758. The path is a sequence of \emph{templates} separated by semicolons.
  2759. For each template, \verb|require| will change an eventual interrogation
  2760. mark in the template to \verb|packagename|,
  2761. and then will try to load the resulting file name.
  2762. So, for instance, if the path is
  2763. \begin{verbatim}
  2764. "./?.lua;./?.lc;/usr/local/?/init.lua;/lasttry"
  2765. \end{verbatim}
  2766. a \verb|require "mod"| will try to load the files
  2767. \verb|./mod.lua|,
  2768. \verb|./mod.lc|,
  2769. \verb|/usr/local/mod/init.lua|,
  2770. and \verb|/lasttry|, in that order.
  2771. The function stops the search as soon as it can load a file,
  2772. and then it runs the file.
  2773. If there is any error loading or running the file,
  2774. or if it cannot find any file in the path,
  2775. then \verb|require| signals an error.
  2776. Otherwise, it marks in table \verb|_LOADED|
  2777. that the package is loaded, and returns.
  2778. While running a packaged file,
  2779. \verb|require| defines the global variable \IndexVerb{_REQUIREDNAME}
  2780. with the package name.
  2781. \subsubsection*{\ff \T{setglobals (function, table)}}\DefLIB{setglobals}
  2782. Sets the current table of globals to be used by the given function.
  2783. \verb|function| can be a Lua function or a number,
  2784. meaning the function at that stack level:
  2785. Level 1 is the function calling \verb|setglobals|.
  2786. \subsubsection*{\ff \T{setmetatable (table, metatable)}}\DefLIB{setmetatable}
  2787. Sets the metatable for the given table.
  2788. (You cannot change the metatable of a userdata from Lua.)
  2789. If \verb|metatable| is \nil, removes the metatable of the given table.
  2790. \subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber}
  2791. Tries to convert its argument to a number.
  2792. If the argument is already a number or a string convertible
  2793. to a number, then \verb|tonumber| returns that number;
  2794. otherwise, it returns \nil.
  2795. An optional argument specifies the base to interpret the numeral.
  2796. The base may be any integer between 2 and 36, inclusive.
  2797. In bases above~10, the letter `A' (in either upper or lower case)
  2798. represents~10, `B' represents~11, and so forth, with `Z' representing 35.
  2799. In base 10 (the default), the number may have a decimal part,
  2800. as well as an optional exponent part \see{coercion}.
  2801. In other bases, only unsigned integers are accepted.
  2802. \subsubsection*{\ff \T{tostring (e)}}\DefLIB{tostring}
  2803. Receives an argument of any type and
  2804. converts it to a string in a reasonable format.
  2805. For complete control of how numbers are converted,
  2806. use \verb|format| \see{format}.
  2807. \subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type}
  2808. Returns the type of its only argument, coded as a string.
  2809. The possible results of this function are
  2810. \verb|"nil"| (a string, not the value \nil),
  2811. \verb|"number"|,
  2812. \verb|"string"|,
  2813. \verb|"table"|,
  2814. \verb|"function"|,
  2815. and \verb|"userdata"|.
  2816. \subsubsection*{\ff \T{unpack (list)}}\DefLIB{unpack}
  2817. Returns all elements from the given list.
  2818. This function is equivalent to
  2819. \begin{verbatim}
  2820. return list[1], list[2], ..., list[n]
  2821. \end{verbatim}
  2822. except that the above code can be valid only for a fixed \M{n}.
  2823. The number \M{n} of returned values
  2824. is either the value of \verb|list.n|, if it is a number,
  2825. or one less the index of the first absent (\nil) value.
  2826. \subsection{String Manipulation}
  2827. This library provides generic functions for string manipulation,
  2828. such as finding and extracting substrings and pattern matching.
  2829. When indexing a string in Lua, the first character is at position~1
  2830. (not at~0, as in C).
  2831. Indices are allowed to be negative and are interpreted as indexing backwards,
  2832. from the end of the string.
  2833. Thus, the last character is at position \Math{-1}, and so on.
  2834. The string library provides all its functions inside the table
  2835. \IndexLIB{string}.
  2836. \subsubsection*{\ff \T{string.byte (s [, i])}}\DefLIB{string.byte}
  2837. Returns the internal numerical code of the \M{i}-th character of \verb|s|.
  2838. If \verb|i| is absent, then it is assumed to be~1.
  2839. \verb|i| may be negative.
  2840. \NOTE
  2841. Numerical codes are not necessarily portable across platforms.
  2842. \subsubsection*{\ff \T{string.char (i1, i2, \ldots)}}\DefLIB{string.char}
  2843. Receives 0 or more integers.
  2844. Returns a string with length equal to the number of arguments,
  2845. in which each character has the internal numerical code equal
  2846. to its correspondent argument.
  2847. \NOTE
  2848. Numerical codes are not necessarily portable across platforms.
  2849. \subsubsection*{\ff \T{string.find (s, pattern [, init [, plain]])}}
  2850. \DefLIB{string.find}
  2851. Looks for the first \emph{match} of
  2852. \verb|pattern| in the string \verb|s|.
  2853. If it finds one, then \verb|find| returns the indices of \verb|s|
  2854. where this occurrence starts and ends;
  2855. otherwise, it returns \nil.
  2856. If the pattern specifies captures (see \verb|string.gsub| below),
  2857. the captured strings are returned as extra results.
  2858. A third, optional numerical argument \verb|init| specifies
  2859. where to start the search;
  2860. its default value is~1, and may be negative.
  2861. A value of \True{} as a fourth, optional argument \verb|plain|
  2862. turns off the pattern matching facilities,
  2863. so the function does a plain ``find substring'' operation,
  2864. with no characters in \verb|pattern| being considered ``magic''.
  2865. Note that if \verb|plain| is given, then \verb|init| must be given too.
  2866. \subsubsection*{\ff \T{string.len (s)}}\DefLIB{string.len}
  2867. Receives a string and returns its length.
  2868. The empty string \verb|""| has length 0.
  2869. Embedded zeros are counted,
  2870. and so \verb|"a\000b\000c"| has length 5.
  2871. \subsubsection*{\ff \T{string.lower (s)}}\DefLIB{string.lower}
  2872. Receives a string and returns a copy of that string with all
  2873. uppercase letters changed to lowercase.
  2874. All other characters are left unchanged.
  2875. The definition of what is an uppercase letter depends on the current locale.
  2876. \subsubsection*{\ff \T{string.rep (s, n)}}\DefLIB{string.rep}
  2877. Returns a string that is the concatenation of \verb|n| copies of
  2878. the string \verb|s|.
  2879. \subsubsection*{\ff \T{string.sub (s, i [, j])}}\DefLIB{string.sub}
  2880. Returns another string, which is a substring of \verb|s|,
  2881. starting at \verb|i| and running until \verb|j|;
  2882. \verb|i| and \verb|j| may be negative.
  2883. If \verb|j| is absent, then it is assumed to be equal to \Math{-1}
  2884. (which is the same as the string length).
  2885. In particular,
  2886. the call \verb|string.sub(s,1,j)| returns a prefix of \verb|s|
  2887. with length \verb|j|,
  2888. and the call \verb|string.sub(s, -i)| returns a suffix of \verb|s|
  2889. with length \verb|i|.
  2890. \subsubsection*{\ff \T{string.upper (s)}}\DefLIB{string.upper}
  2891. Receives a string and returns a copy of that string with all
  2892. lowercase letters changed to uppercase.
  2893. All other characters are left unchanged.
  2894. The definition of what is a lowercase letter depends on the current locale.
  2895. \subsubsection*{\ff \T{string.format (formatstring, e1, e2, \ldots)}}
  2896. \DefLIB{string.format}\label{format}
  2897. Returns a formatted version of its variable number of arguments
  2898. following the description given in its first argument (which must be a string).
  2899. The format string follows the same rules as the \verb|printf| family of
  2900. standard C~functions.
  2901. The only differences are that the options/modifiers
  2902. \verb|*|, \verb|l|, \verb|L|, \verb|n|, \verb|p|,
  2903. and \verb|h| are not supported,
  2904. and there is an extra option, \verb|q|.
  2905. The \verb|q| option formats a string in a form suitable to be safely read
  2906. back by the Lua interpreter:
  2907. The string is written between double quotes,
  2908. and all double quotes, returns, and backslashes in the string
  2909. are correctly escaped when written.
  2910. For instance, the call
  2911. \begin{verbatim}
  2912. string.format('%q', 'a string with "quotes" and \n new line')
  2913. \end{verbatim}
  2914. will produce the string:
  2915. \begin{verbatim}
  2916. "a string with \"quotes\" and \
  2917. new line"
  2918. \end{verbatim}
  2919. The options \verb|c|, \verb|d|, \verb|E|, \verb|e|, \verb|f|,
  2920. \verb|g|, \verb|G|, \verb|i|, \verb|o|, \verb|u|, \verb|X|, and \verb|x| all
  2921. expect a number as argument,
  2922. whereas \verb|q| and \verb|s| expect a string.
  2923. The \verb|*| modifier can be simulated by building
  2924. the appropriate format string.
  2925. For example, \verb|"%*g"| can be simulated with
  2926. \verb|"%"..width.."g"|.
  2927. \NOTE
  2928. String values to be formatted with
  2929. \verb|%s| cannot contain embedded zeros.
  2930. \subsubsection*{\ff \T{string.gfind (s, pat)}}
  2931. Returns a generator function that,
  2932. each time it is called,
  2933. returns the next captures from pattern \verb|pat| over string \verb|s|.
  2934. If \verb|pat| specifies no captures,
  2935. then the whole match is produced in each call.
  2936. As an example, the following loop
  2937. \begin{verbatim}
  2938. s = "hello world from Lua"
  2939. for w in string.gfind(s, "%a+") do
  2940. print(w)
  2941. end
  2942. \end{verbatim}
  2943. will iterate over all the words from string \verb|s|,
  2944. printing each one in a line.
  2945. The next example collects all pairs \verb|key=value| from the
  2946. given string into a table:
  2947. \begin{verbatim}
  2948. t = {}
  2949. s = "from=world, to=Lua"
  2950. for k, v in string.gfind(s, "(%w+)=(%w+)") do
  2951. t[k] = v
  2952. end
  2953. \end{verbatim}
  2954. \subsubsection*{\ff \T{string.gsub (s, pat, repl [, n])}}
  2955. \DefLIB{string.gsub}
  2956. Returns a copy of \verb|s|
  2957. in which all occurrences of the pattern \verb|pat| have been
  2958. replaced by a replacement string specified by \verb|repl|.
  2959. \verb|gsub| also returns, as a second value,
  2960. the total number of substitutions made.
  2961. If \verb|repl| is a string, then its value is used for replacement.
  2962. Any sequence in \verb|repl| of the form \verb|%|\M{n},
  2963. with \M{n} between 1 and 9,
  2964. stands for the value of the \M{n}-th captured substring.
  2965. If \verb|repl| is a function, then this function is called every time a
  2966. match occurs, with all captured substrings passed as arguments,
  2967. in order (see below);
  2968. if the pattern specifies no captures,
  2969. then the whole match is passed as a sole argument.
  2970. If the value returned by this function is a string,
  2971. then it is used as the replacement string;
  2972. otherwise, the replacement string is the empty string.
  2973. The last, optional parameter \verb|n| limits
  2974. the maximum number of substitutions to occur.
  2975. For instance, when \verb|n| is 1 only the first occurrence of
  2976. \verb|pat| is replaced.
  2977. Here are some examples:
  2978. \begin{verbatim}
  2979. x = string.gsub("hello world", "(%w+)", "%1 %1")
  2980. --> x="hello hello world world"
  2981. x = string.gsub("hello world", "(%w+)", "%1 %1", 1)
  2982. --> x="hello hello world"
  2983. x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
  2984. --> x="world hello Lua from"
  2985. x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
  2986. --> x="home = /home/roberto, user = roberto" (for instance)
  2987. x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
  2988. return loadstring(s)()
  2989. end)
  2990. --> x="4+5 = 9"
  2991. local t = {name="Lua", version="5.0"}
  2992. x = string.gsub("$name - $version", "%$(%w+)", function (v)
  2993. return t[v]
  2994. end)
  2995. --> x="Lua - 5.0"
  2996. \end{verbatim}
  2997. \subsubsection*{Patterns} \label{pm}
  2998. \paragraph{Character Class:}
  2999. a \Def{character class} is used to represent a set of characters.
  3000. The following combinations are allowed in describing a character class:
  3001. \begin{description}\leftskip=20pt
  3002. \item[\emph{x}] (where \emph{x} is not one of the magic characters
  3003. \verb|^$()%.[]*+-?|)
  3004. --- represents the character \emph{x} itself.
  3005. \item[\T{.}] --- (a dot) represents all characters.
  3006. \item[\T{\%a}] --- represents all letters.
  3007. \item[\T{\%c}] --- represents all control characters.
  3008. \item[\T{\%d}] --- represents all digits.
  3009. \item[\T{\%l}] --- represents all lowercase letters.
  3010. \item[\T{\%p}] --- represents all punctuation characters.
  3011. \item[\T{\%s}] --- represents all space characters.
  3012. \item[\T{\%u}] --- represents all uppercase letters.
  3013. \item[\T{\%w}] --- represents all alphanumeric characters.
  3014. \item[\T{\%x}] --- represents all hexadecimal digits.
  3015. \item[\T{\%z}] --- represents the character with representation 0.
  3016. \item[\T{\%\M{x}}] (where \M{x} is any non-alphanumeric character) ---
  3017. represents the character \M{x}.
  3018. This is the standard way to escape the magic characters.
  3019. We recommend that any punctuation character (even the non magic)
  3020. should be preceded by a \verb|%|
  3021. when used to represent itself in a pattern.
  3022. \item[\T{[\M{set}]}] ---
  3023. represents the class which is the union of all
  3024. characters in \M{set}.
  3025. A range of characters may be specified by
  3026. separating the end characters of the range with a \verb|-|.
  3027. All classes \verb|%|\emph{x} described above may also be used as
  3028. components in \M{set}.
  3029. All other characters in \M{set} represent themselves.
  3030. For example, \verb|[%w_]| (or \verb|[_%w]|)
  3031. represents all alphanumeric characters plus the underscore,
  3032. \verb|[0-7]| represents the octal digits,
  3033. and \verb|[0-7%l%-]| represents the octal digits plus
  3034. the lowercase letters plus the \verb|-| character.
  3035. The interaction between ranges and classes is not defined.
  3036. Therefore, patterns like \verb|[%a-z]| or \verb|[a-%%]|
  3037. have no meaning.
  3038. \item[\T{[\^\null\M{set}]}] ---
  3039. represents the complement of \M{set},
  3040. where \M{set} is interpreted as above.
  3041. \end{description}
  3042. For all classes represented by single letters (\verb|%a|, \verb|%c|, \ldots),
  3043. the corresponding uppercase letter represents the complement of the class.
  3044. For instance, \verb|%S| represents all non-space characters.
  3045. The definitions of letter, space, etc.\ depend on the current locale.
  3046. In particular, the class \verb|[a-z]| may not be equivalent to \verb|%l|.
  3047. The second form should be preferred for portability.
  3048. \paragraph{Pattern Item:}
  3049. a \Def{pattern item} may be
  3050. \begin{itemize}
  3051. \item
  3052. a single character class,
  3053. which matches any single character in the class;
  3054. \item
  3055. a single character class followed by \verb|*|,
  3056. which matches 0 or more repetitions of characters in the class.
  3057. These repetition items will always match the longest possible sequence;
  3058. \item
  3059. a single character class followed by \verb|+|,
  3060. which matches 1 or more repetitions of characters in the class.
  3061. These repetition items will always match the longest possible sequence;
  3062. \item
  3063. a single character class followed by \verb|-|,
  3064. which also matches 0 or more repetitions of characters in the class.
  3065. Unlike \verb|*|,
  3066. these repetition items will always match the \emph{shortest} possible sequence;
  3067. \item
  3068. a single character class followed by \verb|?|,
  3069. which matches 0 or 1 occurrence of a character in the class;
  3070. \item
  3071. \T{\%\M{n}}, for \M{n} between 1 and 9;
  3072. such item matches a substring equal to the \M{n}-th captured string
  3073. (see below);
  3074. \item
  3075. \T{\%b\M{xy}}, where \M{x} and \M{y} are two distinct characters;
  3076. such item matches strings that start with~\M{x}, end with~\M{y},
  3077. and where the \M{x} and \M{y} are \emph{balanced}.
  3078. This means that, if one reads the string from left to right,
  3079. counting \Math{+1} for an \M{x} and \Math{-1} for a \M{y},
  3080. the ending \M{y} is the first \M{y} where the count reaches 0.
  3081. For instance, the item \verb|%b()| matches expressions with
  3082. balanced parentheses.
  3083. \end{itemize}
  3084. \paragraph{Pattern:}
  3085. a \Def{pattern} is a sequence of pattern items.
  3086. A \verb|^| at the beginning of a pattern anchors the match at the
  3087. beginning of the subject string.
  3088. A \verb|$| at the end of a pattern anchors the match at the
  3089. end of the subject string.
  3090. At other positions,
  3091. \verb|^| and \verb|$| have no special meaning and represent themselves.
  3092. \paragraph{Captures:}
  3093. A pattern may contain sub-patterns enclosed in parentheses;
  3094. they describe \Def{captures}.
  3095. When a match succeeds, the substrings of the subject string
  3096. that match captures are stored (\emph{captured}) for future use.
  3097. Captures are numbered according to their left parentheses.
  3098. For instance, in the pattern \verb|"(a*(.)%w(%s*))"|,
  3099. the part of the string matching \verb|"a*(.)%w(%s*)"| is
  3100. stored as the first capture (and therefore has number~1);
  3101. the character matching \verb|.| is captured with number~2,
  3102. and the part matching \verb|%s*| has number~3.
  3103. As a special case, the empty capture \verb|()| captures
  3104. the current string position (a number).
  3105. For instance, if we apply the pattern \verb|"()aa()"| on the
  3106. string \verb|"flaaap"|, there will be two captures: 3 and 5.
  3107. \NOTE
  3108. A pattern cannot contain embedded zeros. Use \verb|%z| instead.
  3109. \subsection{Table Manipulation}
  3110. This library provides generic functions for table manipulation,
  3111. It provides all its functions inside the table \IndexLIB{table}.
  3112. Most functions in the table library library assume that the table
  3113. represents an array or a list.
  3114. For those functions, an important concept is the \emph{size} of the array.
  3115. There are three ways to specify that size:
  3116. \begin{itemize}
  3117. \item the field \verb|"n"| ---
  3118. When the table has a field \verb|"n"| with a numerical value,
  3119. that value is assumed as its size.
  3120. \item \verb|setn| ---
  3121. You can call the \verb|table.setn| function to explicitly set
  3122. the size of a table.
  3123. \item implicit size ---
  3124. Otherwise, the size of the object is one less the first integer index
  3125. with a \nil{} value.
  3126. \end{itemize}
  3127. For more details, see the descriptions of the \verb|table.getn| and
  3128. \verb|table.setn| functions.
  3129. \subsubsection*{\ff \T{table.concat (table [, sep [, i [, j]]])}}
  3130. \DefLIB{table.concat}
  3131. Returns \verb|table[i]..sep..table[i+1] ... sep..table[j]|.
  3132. The default value for \verb|sep| is the empty string,
  3133. the default for \verb|i| is 1,
  3134. and the default for \verb|j| is the size of the table.
  3135. If \verb|i| is greater than \verb|j|, returns the empty string.
  3136. \subsubsection*{\ff \T{table.foreach (table, func)}}\DefLIB{table.foreach}
  3137. Executes the given \verb|func| over all elements of \verb|table|.
  3138. For each element, \verb|func| is called with the index and
  3139. respective value as arguments.
  3140. If \verb|func| returns a non-\nil{} value,
  3141. then the loop is broken, and this value is returned
  3142. as the final value of \verb|foreach|.
  3143. The behavior of \verb|foreach| is \emph{undefined} if you change
  3144. the table \verb|t| during the traversal.
  3145. \subsubsection*{\ff \T{table.foreachi (table, func)}}\DefLIB{table.foreachi}
  3146. Executes the given \verb|func| over the
  3147. numerical indices of \verb|table|.
  3148. For each index, \verb|func| is called with the index and
  3149. respective value as arguments.
  3150. Indices are visited in sequential order,
  3151. from~1 to \verb|n|,
  3152. where \verb|n| is the size of the table \see{getn}.
  3153. If \verb|func| returns a non-\nil{} value,
  3154. then the loop is broken, and this value is returned
  3155. as the final value of \verb|foreachi|.
  3156. \subsubsection*{\ff \T{table.getn (table)}}\DefLIB{table.getn}\label{getn}
  3157. Returns the ``size'' of a table, when seen as a list.
  3158. If the table has an \verb|n| field with a numeric value,
  3159. this value is the ``size'' of the table.
  3160. Otherwise, if there was a previous call to
  3161. \verb|table.getn| or to \verb|table.setn| over this table,
  3162. the respective value is returned.
  3163. Otherwise, the ``size'' is one less the first integer index with
  3164. a \nil{} value.
  3165. Notice that the last option happens only once for a table.
  3166. If you call \verb|table.getn| again over the same table,
  3167. it will return the same previous result,
  3168. even if the table has been modified.
  3169. The only way to change the value of \verb|table.getn| is by calling
  3170. \verb|table.setn| or assigning to field \verb|"n"| in the table.
  3171. \subsubsection*{\ff \T{table.sort (table [, comp])}}\DefLIB{table.sort}
  3172. Sorts table elements in a given order, \emph{in-place},
  3173. from \verb|table[1]| to \verb|table[n]|,
  3174. where \verb|n| is the size of the table \see{getn}.
  3175. If \verb|comp| is given,
  3176. then it must be a function that receives two table elements,
  3177. and returns true
  3178. when the first is less than the second
  3179. (so that \verb|not comp(a[i+1],a[i])| will be true after the sort).
  3180. If \verb|comp| is not given,
  3181. then the standard Lua operator \verb|<| is used instead.
  3182. The sort algorithm is \emph{not} stable
  3183. (that is, elements considered equal by the given order
  3184. may have their relative positions changed by the sort).
  3185. \subsubsection*{\ff \T{table.insert (table, [pos,] value)}}\DefLIB{table.insert}
  3186. Inserts element \verb|value| at position \verb|pos| in \verb|table|,
  3187. shifting other elements up to open space, if necessary.
  3188. The default value for \verb|pos| is \verb|n+1|,
  3189. where \verb|n| is the size of the table \see{getn},
  3190. so that a call \verb|table.insert(t,x)| inserts \verb|x| at the end
  3191. of table \verb|t|.
  3192. This function also updates the size of the table,
  3193. calling \verb|table.setn(table, n+1)|.
  3194. \subsubsection*{\ff \T{table.remove (table [, pos])}}\DefLIB{table.remove}
  3195. Removes from \verb|table| the element at position \verb|pos|,
  3196. shifting other elements down to close the space, if necessary.
  3197. Returns the value of the removed element.
  3198. The default value for \verb|pos| is \verb|n|,
  3199. where \verb|n| is the size of the table \see{getn},
  3200. so that a call \verb|tremove(t)| removes the last element
  3201. of table \verb|t|.
  3202. This function also updates the size of the table,
  3203. calling \verb|table.setn(table, n-1)|.
  3204. \subsubsection*{\ff \T{table.setn (table, n)}}\DefLIB{table.setn}
  3205. Updates the ``size'' of a table.
  3206. If the table has a field \verb|"n"| with a numerical value,
  3207. that value is changed to the given \verb|n|.
  3208. Otherwise, it updates an internal state of the \verb|table| library
  3209. so that subsequent calls to \verb|table.getn(table)| return \verb|n|.
  3210. \subsection{Mathematical Functions} \label{mathlib}
  3211. This library is an interface to most functions of the standard C~math library.
  3212. (Some have slightly different names.)
  3213. It provides all its functions inside the table \DefLIB{math}.
  3214. In addition,
  3215. it registers a ??tag method for the binary exponentiation operator \verb|^|
  3216. that returns \Math{x^y} when applied to numbers \verb|x^y|.
  3217. The library provides the following functions:
  3218. \DefLIB{math.abs}\DefLIB{math.acos}\DefLIB{math.asin}\DefLIB{math.atan}
  3219. \DefLIB{math.atan2}\DefLIB{math.ceil}\DefLIB{math.cos}
  3220. \DefLIB{math.def}\DefLIB{math.exp}
  3221. \DefLIB{math.floor}\DefLIB{math.log}\DefLIB{math.log10}
  3222. \DefLIB{math.max}\DefLIB{math.min}
  3223. \DefLIB{math.mod}\DefLIB{math.rad}\DefLIB{math.sin}
  3224. \DefLIB{math.sqrt}\DefLIB{math.tan}
  3225. \DefLIB{math.frexp}\DefLIB{math.ldexp}\DefLIB{math.random}
  3226. \DefLIB{math.randomseed}
  3227. \begin{verbatim}
  3228. math.abs math.acos math.asin math.atan math.atan2
  3229. math.ceil math.cos math.deg math.exp math.floor
  3230. math.log math.log10 math.max math.min math.mod
  3231. math.rad math.sin math.sqrt math.tan math.frexp
  3232. math.ldexp math.random math.randomseed
  3233. \end{verbatim}
  3234. plus a variable \IndexLIB{math.pi}.
  3235. Most of them
  3236. are only interfaces to the homonymous functions in the C~library.
  3237. All trigonometric functions work in radians.
  3238. The functions \verb|math.deg| and \verb|math.rad| convert
  3239. between radians and degrees.
  3240. The function \verb|math.max| returns the maximum
  3241. value of its numeric arguments.
  3242. Similarly, \verb|math.min| computes the minimum.
  3243. Both can be used with 1, 2, or more arguments.
  3244. The functions \verb|math.random| and \verb|math.randomseed|
  3245. are interfaces to the simple random generator functions
  3246. \verb|rand| and \verb|srand|, provided by ANSI~C.
  3247. (No guarantees can be given for their statistical properties.)
  3248. When called without arguments,
  3249. \verb|math.random| returns a pseudo-random real number
  3250. in the range \Math{[0,1)}. %]
  3251. When called with a number \Math{n},
  3252. \verb|math.random| returns a pseudo-random integer in the range \Math{[1,n]}.
  3253. When called with two arguments, \Math{l} and \Math{u},
  3254. \verb|math.random| returns a pseudo-random integer in the range \Math{[l,u]}.
  3255. The \verb|math.randomseed| function sets a ``seed''
  3256. for the pseudo-random generator:
  3257. Equal seeds produce equal sequences of numbers.
  3258. \subsection{Input and Output Facilities} \label{libio}
  3259. The I/O library provides two different styles for file manipulation.
  3260. The first one uses implicit file descriptors;
  3261. that is, there are operations to set a default input file and a
  3262. default output file,
  3263. and all input/output operations are over those default files.
  3264. The second style uses explicit file descriptors.
  3265. When using implicit file descriptors,
  3266. all operations are supplied by table \IndexLIB{io}.
  3267. When using explicit file descriptors,
  3268. the operation \IndexLIB{io.open} returns a file descriptor,
  3269. and then all operations are supplied as methods by the file descriptor.
  3270. Moreover, the table \verb|io| also provides
  3271. three predefined file descriptors:
  3272. \IndexLIB{io.stdin}, \IndexLIB{io.stdout}, and \IndexLIB{io.stderr},
  3273. with their usual meaning from C.
  3274. A file handle is a userdata containing the file stream (\verb|FILE*|),
  3275. with a distinctive metatable created by the I/O library.
  3276. Unless otherwise stated,
  3277. all I/O functions return \nil{} on failure
  3278. (plus an error message as a second result)
  3279. and some value different from \nil{} on success.
  3280. \subsubsection*{\ff \T{io.close ([handle])}}\DefLIB{io.close}
  3281. Equivalent to \verb|file:close()|.
  3282. Without a \verb|handle|, closes the default output file.
  3283. \subsubsection*{\ff \T{io.flush ()}}\DefLIB{io.flush}
  3284. Equivalent to \verb|file:flush| over the default output file.
  3285. \subsubsection*{\ff \T{io.input ([file])}}\DefLIB{io.input}
  3286. When called with a file name, it opens the named file (in text mode),
  3287. and sets its handle as the default input file
  3288. (and returns nothing).
  3289. When called with a file handle,
  3290. it simply sets that file handle as the default input file.
  3291. When called without parameters,
  3292. it returns the current default input file.
  3293. In case of errors this function raises the error,
  3294. instead of returning an error code.
  3295. \subsubsection*{\ff \T{io.lines ([filename])}}\DefLIB{io.lines}
  3296. Opens the given file name in read mode,
  3297. and returns a generator function that,
  3298. each time it is called,
  3299. returns a new line from the file.
  3300. Therefore, the construction
  3301. \begin{verbatim}
  3302. for lines in io.lines(filename) do ... end
  3303. \end{verbatim}
  3304. will iterate over all lines of the file.
  3305. When the generator function detects the end of file,
  3306. it returns nil (to finish the loop) and automatically closes the file.
  3307. The call \verb|io.lines()| (without a file name) is equivalent
  3308. to \verb|io.input():lines()|, that is, it iterates over the
  3309. lines of the default input file.
  3310. \subsubsection*{\ff \T{io.open (filename, mode)}}\DefLIB{io.open}
  3311. This function opens a file,
  3312. in the mode specified in the string \verb|mode|.
  3313. It returns a new file handle,
  3314. or, in case of errors, \nil{} plus an error message.
  3315. The \verb|mode| string can be any of the following:
  3316. \begin{description}\leftskip=20pt
  3317. \item[``r''] read mode;
  3318. \item[``w''] write mode;
  3319. \item[``a''] append mode;
  3320. \item[``r+''] update mode, all previous data is preserved;
  3321. \item[``w+''] update mode, all previous data is erased;
  3322. \item[``a+''] append update mode, previous data is preserved,
  3323. writing is only allowed at the end of file.
  3324. \end{description}
  3325. The \verb|mode| string may also have a \verb|b| at the end,
  3326. which is needed in some systems to open the file in binary mode.
  3327. This string is exactly what is used in the standard~C function \verb|fopen|.
  3328. \subsubsection*{\ff \T{io.output ([file])}}\DefLIB{io.output}
  3329. Similar to \verb|io.input|, but operates over the default output file.
  3330. \subsubsection*{\ff \T{io.read (format1, ...)}}\DefLIB{io.read}
  3331. Equivalent to \verb|file:read| over the default input file.
  3332. \subsubsection*{\ff \T{io.tmpfile ()}}\DefLIB{io.tmpfile}
  3333. Returns a handle for a temporary file.
  3334. This file is open in read/write mode,
  3335. and it is automatically removed when the program ends.
  3336. \subsubsection*{\ff \T{io.write (value1, ...)}}\DefLIB{io.write}
  3337. Equivalent to \verb|file:write| over the default output file.
  3338. \subsubsection*{\ff \T{file:close ()}}\DefLIB{file:close}
  3339. Closes the file \verb|file|.
  3340. \subsubsection*{\ff \T{file:flush ()}}\DefLIB{file:flush}
  3341. Saves any written data to the file \verb|file|.
  3342. \subsubsection*{\ff \T{file:lines ()}}\DefLIB{file:lines}
  3343. Returns a generator function that,
  3344. each time it is called,
  3345. returns a new line from the file.
  3346. Therefore, the construction
  3347. \begin{verbatim}
  3348. for lines in file:lines() do ... end
  3349. \end{verbatim}
  3350. will iterate over all lines of the file.
  3351. (Unlike \verb|io.lines|, this function does not close the file
  3352. when the loop ends.)
  3353. \subsubsection*{\ff \T{file:read (format1, ...)}}\DefLIB{file:read}
  3354. Reads the file \verb|file|,
  3355. according to the given formats, which specify what to read.
  3356. For each format,
  3357. the function returns a string (or a number) with the characters read,
  3358. or \nil{} if it cannot read data with the specified format.
  3359. When called without formats,
  3360. it uses a default format that reads the entire next line
  3361. (see below).
  3362. The available formats are
  3363. \begin{description}\leftskip=20pt
  3364. \item[``*n''] reads a number;
  3365. this is the only format that returns a number instead of a string.
  3366. \item[``*a''] reads the whole file, starting at the current position.
  3367. On end of file, it returns the empty string.
  3368. \item[``*l''] reads the next line (skipping the end of line),
  3369. returning \nil{} on end of file.
  3370. This is the default format.
  3371. \item[\emph{number}] reads a string with up to that number of characters,
  3372. or \nil{} on end of file.
  3373. If number is zero,
  3374. it reads nothing and returns an empty string,
  3375. or \nil{} on end of file.
  3376. \end{description}
  3377. \subsubsection*{\ff \T{file:seek ([whence] [, offset])}}\DefLIB{file:seek}
  3378. Sets and gets the file position,
  3379. measured in bytes from the beginning of the file,
  3380. to the position given by \verb|offset| plus a base
  3381. specified by the string \verb|whence|, as follows:
  3382. \begin{description}\leftskip=20pt
  3383. \item[``set''] base is position 0 (beginning of the file);
  3384. \item[``cur''] base is current position;
  3385. \item[``end''] base is end of file;
  3386. \end{description}
  3387. In case of success, function \verb|seek| returns the final file position,
  3388. measured in bytes from the beginning of the file.
  3389. If this function fails, it returns \nil,
  3390. plus a string describing the error.
  3391. The default value for \verb|whence| is \verb|"cur"|,
  3392. and for \verb|offset| is 0.
  3393. Therefore, the call \verb|file:seek()| returns the current
  3394. file position, without changing it;
  3395. the call \verb|file:seek("set")| sets the position to the
  3396. beginning of the file (and returns 0);
  3397. and the call \verb|file:seek("end")| sets the position to the
  3398. end of the file, and returns its size.
  3399. \subsubsection*{\ff \T{file:write (value1, ...)}}\DefLIB{file:write}
  3400. Writes the value of each of its arguments to
  3401. the filehandle \verb|file|.
  3402. The arguments must be strings or numbers.
  3403. To write other values,
  3404. use \verb|tostring| or \verb|format| before \verb|write|.
  3405. If this function fails, it returns \nil,
  3406. plus a string describing the error.
  3407. \subsection{Operating System Facilities} \label{libiosys}
  3408. This library is implemented through table \IndexLIB{os}.
  3409. \subsubsection*{\ff \T{os.clock ()}}\DefLIB{os.clock}
  3410. Returns an approximation of the amount of CPU time
  3411. used by the program, in seconds.
  3412. \subsubsection*{\ff \T{os.date ([format [, time]])}}\DefLIB{os.date}
  3413. Returns a string or a table containing date and time,
  3414. formatted according to the given string \verb|format|.
  3415. If the \verb|time| argument is present,
  3416. this is the time to be formatted
  3417. (see the \verb|time| function for a description of this value).
  3418. Otherwise, \verb|date| formats the current time.
  3419. If \verb|format| starts with \verb|!|,
  3420. then the date is formatted in Coordinated Universal Time.
  3421. After that optional character,
  3422. if \verb|format| is \verb|*t|,
  3423. then \verb|date| returns a table with the following fields:
  3424. \verb|year| (four digits), \verb|month| (1--12), \verb|day| (1--31),
  3425. \verb|hour| (0--23), \verb|min| (0--59), \verb|sec| (0--61),
  3426. \verb|wday| (weekday, Sunday is 1),
  3427. \verb|yday| (day of the year),
  3428. and \verb|isdst| (daylight saving flag, a boolean).
  3429. If format is not \verb|*t|,
  3430. then \verb|date| returns the date as a string,
  3431. formatted according with the same rules as the C~function \verb|strftime|.
  3432. When called without arguments,
  3433. \verb|date| returns a reasonable date and time representation that depends on
  3434. the host system and on the current locale
  3435. (that is, \verb|os.date()| is equivalent to \verb|os.date("%c")|).
  3436. \subsubsection*{\ff \T{os.difftime (t1, t2)}}\DefLIB{os.difftime}
  3437. Returns the number of seconds from time \verb|t1| to time \verb|t2|.
  3438. In Posix, Windows, and some other systems,
  3439. this value is exactly \verb|t1|\Math{-}\verb|t2|.
  3440. \subsubsection*{\ff \T{os.execute (command)}}\DefLIB{os.execute}
  3441. This function is equivalent to the C~function \verb|system|.
  3442. It passes \verb|command| to be executed by an operating system shell.
  3443. It returns a status code, which is system-dependent.
  3444. \subsubsection*{\ff \T{os.exit ([code])}}\DefLIB{os.exit}
  3445. Calls the C~function \verb|exit|,
  3446. with an optional \verb|code|,
  3447. to terminate the host program.
  3448. The default value for \verb|code| is the success code.
  3449. \subsubsection*{\ff \T{os.getenv (varname)}}\DefLIB{os.getenv}
  3450. Returns the value of the process environment variable \verb|varname|,
  3451. or \nil{} if the variable is not defined.
  3452. \subsubsection*{\ff \T{os.remove (filename)}}\DefLIB{os.remove}
  3453. Deletes the file with the given name.
  3454. If this function fails, it returns \nil,
  3455. plus a string describing the error.
  3456. \subsubsection*{\ff \T{os.rename (name1, name2)}}\DefLIB{os.rename}
  3457. Renames file named \verb|name1| to \verb|name2|.
  3458. If this function fails, it returns \nil,
  3459. plus a string describing the error.
  3460. \subsubsection*{\ff \T{os.setlocale (locale [, category])}}\DefLIB{os.setlocale}
  3461. This function is an interface to the C~function \verb|setlocale|.
  3462. \verb|locale| is a string specifying a locale;
  3463. \verb|category| is an optional string describing which category to change:
  3464. \verb|"all"|, \verb|"collate"|, \verb|"ctype"|,
  3465. \verb|"monetary"|, \verb|"numeric"|, or \verb|"time"|;
  3466. the default category is \verb|"all"|.
  3467. The function returns the name of the new locale,
  3468. or \nil{} if the request cannot be honored.
  3469. \subsubsection*{\ff \T{os.time ([table])}}\DefLIB{os.time}
  3470. Returns the current time when called without arguments,
  3471. or a time representing the date and time specified by the given table.
  3472. This table must have fields \verb|year|, \verb|month|, and \verb|day|,
  3473. and may have fields \verb|hour|, \verb|min|, \verb|sec|, and \verb|isdst|
  3474. (for a description of these fields, see the \verb|os.date| function).
  3475. The returned value is a number, whose meaning depends on your system.
  3476. In Posix, Windows, and some other systems, this number counts the number
  3477. of seconds since some given start time (the ``epoch'').
  3478. In other systems, the meaning is not specified,
  3479. and the number returned bt \verb|time| can be used only as an argument to
  3480. \verb|date| and \verb|difftime|.
  3481. \subsubsection*{\ff \T{os.tmpname ()}}\DefLIB{os.tmpname}
  3482. Returns a string with a file name that can
  3483. be used for a temporary file.
  3484. The file must be explicitly opened before its use
  3485. and removed when no longer needed.
  3486. This function is equivalent to the \verb|tmpnam| C~function,
  3487. and many people (and even some compilers!) advise against its use,
  3488. because between the time you call the function
  3489. and the time you open the file,
  3490. it is possible for another process
  3491. to create a file with the same name.
  3492. \subsection{The Reflexive Debug Interface}
  3493. The library \verb|ldblib| provides
  3494. the functionality of the debug interface to Lua programs.
  3495. You should exert great care when using this library.
  3496. The functions provided here should be used exclusively for debugging
  3497. and similar tasks, such as profiling.
  3498. Please resist the temptation to use them as a
  3499. usual programming tool:
  3500. They can be very slow.
  3501. Moreover, \verb|setlocal| and \verb|getlocal|
  3502. violate the privacy of local variables,
  3503. and therefore can compromise some (otherwise) secure code.
  3504. All functions in this library are provided
  3505. inside a \IndexVerb{debug} table.
  3506. \subsubsection*{\ff \T{debug.getinfo (function, [what])}}\DefLIB{debug.getinfo}
  3507. This function returns a table with information about a function.
  3508. You can give the function directly,
  3509. or you can give a number as the value of \verb|function|,
  3510. which means the function running at level \verb|function| of the stack:
  3511. Level 0 is the current function (\verb|getinfo| itself);
  3512. level 1 is the function that called \verb|getinfo|;
  3513. and so on.
  3514. If \verb|function| is a number larger than the number of active functions,
  3515. then \verb|getinfo| returns \nil.
  3516. The returned table contains all the fields returned by \verb|lua_getinfo|,
  3517. with the string \verb|what| describing what to get.
  3518. The default for \verb|what| is to get all information available.
  3519. If present,
  3520. the option \verb|f|
  3521. adds a field named \verb|func| with the function itself.
  3522. For instance, the expression \verb|getinfo(1,"n").name| returns
  3523. the name of the current function, if a reasonable name can be found,
  3524. and \verb|getinfo(print)| returns a table with all available information
  3525. about the \verb|print| function.
  3526. \subsubsection*{\ff \T{debug.getlocal (level, local)}}\DefLIB{debug.getlocal}
  3527. This function returns the name and the value of the local variable
  3528. with index \verb|local| of the function at level \verb|level| of the stack.
  3529. (The first parameter or local variable has index~1, and so on,
  3530. until the last active local variable.)
  3531. The function returns \nil{} if there is no local
  3532. variable with the given index,
  3533. and raises an error when called with a \verb|level| out of range.
  3534. (You can call \verb|getinfo| to check whether the level is valid.)
  3535. \subsubsection*{\ff \T{debug.setlocal (level, local, value)}}
  3536. \DefLIB{debug.setlocal}
  3537. This function assigns the value \verb|value| to the local variable
  3538. with index \verb|local| of the function at level \verb|level| of the stack.
  3539. The function returns \nil{} if there is no local
  3540. variable with the given index,
  3541. and raises an error when called with a \verb|level| out of range.
  3542. (You can call \verb|getinfo| to check whether the level is valid.)
  3543. \subsubsection*{\ff \T{debug.sethook (hook, mask [, count])}}
  3544. \DefLIB{debug.sethook}
  3545. Sets the given function as a hook.
  3546. The string \verb|mask| and the number \verb|count| describe
  3547. when the hook will be called.
  3548. The string mask may have the following characters,
  3549. with the given meaning:
  3550. \begin{description}
  3551. \item[{\tt "c"}] The hook is called every time Lua calls a function;
  3552. \item[{\tt "r"}] The hook is called every time Lua returns from a function;
  3553. \item[{\tt "l"}] The hook is called every time Lua enters a new line of code.
  3554. \end{description}
  3555. With a \verb|count| different from zero,
  3556. the hook is called after every \verb|count| instructions.
  3557. When called without arguments,
  3558. the \verb|debug.sethook| function turns off the hook.
  3559. When the hook is called, its first parameter is always a string
  3560. describing the event that triggered its call:
  3561. \verb|"call"|, \verb|"return"|, \verb|"line"|, and \verb|"count"|.
  3562. Moreover, for line events,
  3563. it also gets as its second parameter the new line number.
  3564. Inside a hook,
  3565. you can call \verb|getinfo| with level 2 to get more information about
  3566. the running function
  3567. (level~0 is the \verb|getinfo| function,
  3568. and level~1 is the hook function).
  3569. \subsubsection*{\ff \T{debug.gethook ()}}\DefLIB{debug.gethook}
  3570. Returns the current hook settings, as three values:
  3571. the current hook function, the current hook mask,
  3572. and the current hook count (as set by the \verb|debug.sethook| function).
  3573. %------------------------------------------------------------------------------
  3574. \section{\Index{Lua Stand-alone}} \label{lua-sa}
  3575. Although Lua has been designed as an extension language,
  3576. to be embedded in a host C~program,
  3577. it is also frequently used as a stand-alone language.
  3578. An interpreter for Lua as a stand-alone language,
  3579. called simply \verb|lua|,
  3580. is provided with the standard distribution.
  3581. The stand-alone interpreter includes
  3582. all standard libraries plus the reflexive debug interface.
  3583. Its usage is:
  3584. \begin{verbatim}
  3585. lua [options] [script [args]]
  3586. \end{verbatim}
  3587. The options are:
  3588. \begin{description}\leftskip=20pt
  3589. \item[\T{-} ] executes \verb|stdin| as a file;
  3590. \item[\T{-e} \rm\emph{stat}] executes string \emph{stat};
  3591. \item[\T{-l} \rm\emph{file}] ``requires'' \emph{file};
  3592. \item[\T{-i}] enters interactive mode after running \emph{script};
  3593. \item[\T{-v}] prints version information;
  3594. \item[\T{--}] stop handling options.
  3595. \end{description}
  3596. After handling its options, \verb|lua| runs the given \emph{script},
  3597. passing to it the given \emph{args}.
  3598. When called without arguments,
  3599. \verb|lua| behaves as \verb|lua -v -i| when \verb|stdin| is a terminal,
  3600. and as \verb|lua -| otherwise.
  3601. Before running any argument,
  3602. the intepreter checks for an environment variable \IndexVerb{LUA_INIT}.
  3603. If its format is \verb|@|\emph{filename},
  3604. then lua executes the file.
  3605. Otherwise, lua executes the string itself.
  3606. All options are handled in order, except \verb|-i|.
  3607. For instance, an invocation like
  3608. \begin{verbatim}
  3609. $ lua -e'a=1' -e 'print(a)' script.lua
  3610. \end{verbatim}
  3611. will first set \verb|a| to 1, then print \verb|a|,
  3612. and finally run the file \verb|script.lua|.
  3613. (Here, \verb|$| is the shell prompt. Your prompt may be different.)
  3614. Before starting to run the script,
  3615. \verb|lua| collects all arguments in the command line
  3616. in a global table called \verb|arg|.
  3617. The script name is stored in index 0,
  3618. the first argument after the script name goes to index 1,
  3619. and so on.
  3620. The field \verb|n| gets the number of arguments after the script name.
  3621. Any arguments before the script name
  3622. (that is, the interpreter name plus the options)
  3623. go to negative indices.
  3624. For instance, in the call
  3625. \begin{verbatim}
  3626. $ lua -la.lua b.lua t1 t2
  3627. \end{verbatim}
  3628. the interpreter first runs the file \T{a.lua},
  3629. then creates a table
  3630. \begin{verbatim}
  3631. arg = { [-2] = "lua", [-1] = "-la.lua", [0] = "b.lua",
  3632. [1] = "t1", [2] = "t2"; n = 2 }
  3633. \end{verbatim}
  3634. and finally runs the file \T{b.lua}.
  3635. In interactive mode,
  3636. if you write an incomplete statement,
  3637. the interpreter waits for its completion.
  3638. If the global variable \IndexVerb{_PROMPT} is defined as a string,
  3639. then its value is used as the prompt.
  3640. Therefore, the prompt can be changed directly on the command line:
  3641. \begin{verbatim}
  3642. $ lua -e"_PROMPT='myprompt> '" -i
  3643. \end{verbatim}
  3644. (the first pair of quotes is for the shell,
  3645. the second is for Lua),
  3646. or in any Lua programs by assigning to \verb|_PROMPT|.
  3647. Note the use of \verb|-i| to enter interactive mode; otherwise,
  3648. the program would end just after the assignment to \verb|_PROMPT|.
  3649. In Unix systems, Lua scripts can be made into executable programs
  3650. by using \verb|chmod +x| and the~\verb|#!| form,
  3651. as in
  3652. \begin{verbatim}
  3653. #!/usr/local/bin/lua
  3654. \end{verbatim}
  3655. (Of course,
  3656. the location of the Lua interpreter may be different in your machine.
  3657. If \verb|lua| is in your \verb|PATH|,
  3658. then a more portable solution is
  3659. \begin{verbatim}
  3660. #!/usr/bin/env lua
  3661. \end{verbatim}
  3662. %------------------------------------------------------------------------------
  3663. \section*{Acknowledgments}
  3664. The Lua team is grateful to \tecgraf{} for its continued support to Lua.
  3665. We thank everyone at \tecgraf{},
  3666. specially the head of the group, Marcelo Gattass.
  3667. At the risk of omitting several names,
  3668. we also thank the following individuals for supporting,
  3669. contributing to, and spreading the word about Lua:
  3670. Alan Watson.
  3671. Andr\'e Clinio,
  3672. Andr\'e Costa,
  3673. Antonio Scuri,
  3674. Bret Mogilefsky,
  3675. Cameron Laird,
  3676. Carlos Cassino,
  3677. Carlos Henrique Levy,
  3678. Claudio Terra,
  3679. David Jeske,
  3680. Edgar Toernig,
  3681. Erik Hougaard,
  3682. Jim Mathies,
  3683. John Belmonte,
  3684. John Passaniti,
  3685. John Roll,
  3686. Jon Erickson,
  3687. Jon Kleiser,
  3688. Mark Ian Barlow,
  3689. Nick Trout,
  3690. Noemi Rodriguez,
  3691. Norman Ramsey,
  3692. Philippe Lhoste,
  3693. Renata Ratton,
  3694. Renato Borges,
  3695. Renato Cerqueira,
  3696. Reuben Thomas,
  3697. Stephan Herrmann,
  3698. Steve Dekorte,
  3699. Thatcher Ulrich,
  3700. Tom\'as Gorham,
  3701. Vincent Penquerc'h,
  3702. Thank you!
  3703. \appendix
  3704. \section*{Incompatibilities with Previous Versions}
  3705. \addcontentsline{toc}{section}{Incompatibilities with Previous Versions}
  3706. \subsection*{Incompatibilities with \Index{version 4.0}}
  3707. \subsubsection*{Changes in the Language}
  3708. \begin{itemize}
  3709. \item
  3710. Function calls written between parentheses result in exactly one value.
  3711. \item
  3712. A function call as the last expression in a list constructor
  3713. (like \verb|{a,b,f()}|) has all its return values inserted in the list.
  3714. \item
  3715. The precedence of \rwd{or} is smaller than the precedence of \rwd{and}.
  3716. \item
  3717. \rwd{in} is a reserved word.
  3718. \item
  3719. The old construction \verb|for k,v in t|, where \verb|t| is a table,
  3720. is deprecated (although it is still supported).
  3721. Use \verb|for k,v in pairs(t)| instead.
  3722. \item
  3723. When a literal string of the form \verb|[[...]]| starts with a newline,
  3724. this newline is ignored.
  3725. \item Old pre-compiled code is obsolete, and must be re-compiled.
  3726. \end{itemize}
  3727. \subsubsection*{Changes in the Libraries}
  3728. \begin{itemize}
  3729. \item
  3730. Most library functions now are defined inside tables.
  3731. There is a compatibility script (\verb|compat.lua|) that
  3732. redefine most of them as global names.
  3733. \item
  3734. In the math library, angles are expressed in radians.
  3735. With the compatibility script (\verb|compat.lua|),
  3736. functions still work in degrees.
  3737. \item
  3738. The \verb|call| function is deprecated.
  3739. Use \verb|f(unpack(tab))| instead of \verb|call(f, tab)|
  3740. for unprotected calls,
  3741. or the new \verb|pcall| function for protected calls.
  3742. \item
  3743. \verb|dofile| do not handle errors, but simply propagate them.
  3744. \item
  3745. The \verb|read| option \verb|*w| is obsolete.
  3746. \item
  3747. The \verb|format| option \verb|%n$| is obsolete.
  3748. \end{itemize}
  3749. \subsubsection*{Changes in the API}
  3750. \begin{itemize}
  3751. \item
  3752. Userdata!!
  3753. \end{itemize}
  3754. %{===============================================================
  3755. \newpage
  3756. \section*{The Complete Syntax of Lua} \label{BNF}
  3757. \addcontentsline{toc}{section}{The Complete Syntax of Lua}
  3758. The notation used here is the usual extended BNF,
  3759. in which
  3760. \rep{\emph{a}}~means 0 or more \emph{a}'s, and
  3761. \opt{\emph{a}}~means an optional \emph{a}.
  3762. Non-terminals are shown in \emph{italics},
  3763. keywords are shown in {\bf bold},
  3764. and other terminal symbols are shown in {\tt typewriter} font,
  3765. enclosed in single quotes.
  3766. \renewenvironment{Produc}{\vspace{0.8ex}\par\noindent\hspace{3ex}\it\begin{tabular}{rrl}}{\end{tabular}\vspace{0.8ex}\par\noindent}
  3767. \renewcommand{\OrNL}{\\ & \Or & }
  3768. %\newcommand{\Nter}[1]{{\rm{\tt#1}}}
  3769. %\newcommand{\Nter}[1]{\ter{#1}}
  3770. \index{grammar}
  3771. \begin{Produc}
  3772. \produc{chunk}{\rep{stat \opt{\ter{;}}}}
  3773. \produc{block}{chunk}
  3774. \produc{stat}{%
  3775. varlist1 \ter{=} explist1
  3776. \OrNL functioncall
  3777. \OrNL \rwd{do} block \rwd{end}
  3778. \OrNL \rwd{while} exp \rwd{do} block \rwd{end}
  3779. \OrNL \rwd{repeat} block \rwd{until} exp
  3780. \OrNL \rwd{if} exp \rwd{then} block
  3781. \rep{\rwd{elseif} exp \rwd{then} block}
  3782. \opt{\rwd{else} block} \rwd{end}
  3783. \OrNL \rwd{return} \opt{explist1}
  3784. \OrNL \rwd{break}
  3785. \OrNL \rwd{for} \Nter{Name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp}
  3786. \rwd{do} block \rwd{end}
  3787. \OrNL \rwd{for} \Nter{Name} \rep{\ter{,} \Nter{Name}} \rwd{in} explist1
  3788. \rwd{do} block \rwd{end}
  3789. \OrNL \rwd{function} funcname funcbody
  3790. \OrNL \rwd{local} \rwd{function} \Nter{Name} funcbody
  3791. \OrNL \rwd{local} namelist \opt{init}
  3792. }
  3793. \produc{funcname}{\Nter{Name} \rep{\ter{.} \Nter{Name}}
  3794. \opt{\ter{:} \Nter{Name}}}
  3795. \produc{varlist1}{var \rep{\ter{,} var}}
  3796. \produc{var}{%
  3797. \Nter{Name}
  3798. \Or prefixexp \ter{[} exp \ter{]}
  3799. \Or prefixexp \ter{.} \Nter{Name}
  3800. }
  3801. \produc{namelist}{\Nter{Name} \rep{\ter{,} \Nter{Name}}}
  3802. \produc{init}{\ter{=} explist1}
  3803. \produc{explist1}{\rep{exp \ter{,}} exp}
  3804. \produc{exp}{%
  3805. \rwd{nil}
  3806. \rwd{false}
  3807. \rwd{true}
  3808. \Or \Nter{Number}
  3809. \OrNL \Nter{Literal}
  3810. \Or function
  3811. \Or prefixexp
  3812. \OrNL tableconstructor
  3813. \Or exp binop exp
  3814. \Or unop exp
  3815. }
  3816. \produc{prefixexp}{var \Or functioncall \Or \ter{(} exp \ter{)}}
  3817. \produc{functioncall}{%
  3818. prefixexp args
  3819. \Or prefixexp \ter{:} \Nter{Name} args
  3820. }
  3821. \produc{args}{%
  3822. \ter{(} \opt{explist1} \ter{)}
  3823. \Or tableconstructor
  3824. \Or \Nter{Literal}
  3825. }
  3826. \produc{function}{\rwd{function} funcbody}
  3827. \produc{funcbody}{\ter{(} \opt{parlist1} \ter{)} block \rwd{end}}
  3828. \produc{parlist1}{%
  3829. \Nter{Name} \rep{\ter{,} \Nter{Name}} \opt{\ter{,} \ter{\ldots}}
  3830. \Or \ter{\ldots}
  3831. }
  3832. \produc{tableconstructor}{\ter{\{} \opt{fieldlist} \ter{\}}}
  3833. \produc{fieldlist}{field \rep{fieldsep field} \opt{fieldsep}}
  3834. \produc{field}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp \Or exp}
  3835. \produc{fieldsep}{\ter{,} \Or \ter{;}}
  3836. \produc{binop}{\ter{+} \Or \ter{-} \Or \ter{*} \Or \ter{/} \Or \ter{\^{ }} \Or
  3837. \ter{..} \Or \ter{<} \Or \ter{<=} \Or \ter{>} \Or \ter{>=}
  3838. \Or \ter{==} \Or \ter{\~{ }=} \OrNL \rwd{and} \Or \rwd{or}}
  3839. \produc{unop}{\ter{-} \Or \rwd{not}}
  3840. \end{Produc}
  3841. %}===============================================================
  3842. % Index
  3843. \newpage
  3844. \addcontentsline{toc}{section}{Index}
  3845. \input{manual.id}
  3846. \end{document}
  3847. %)]}