2
0

manual.tex 106 KB

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