manual.tex 118 KB

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