manual.tex 94 KB

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