manual.tex 99 KB

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