manual.tex 147 KB

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