manual.tex 103 KB

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