manual.tex 124 KB

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