manual.tex 113 KB

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