2
0

manual.tex 138 KB

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