manual.tex 140 KB

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