manual.tex 140 KB

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