manual.tex 88 KB

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