manual.tex 78 KB

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