manual.tex 133 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797
  1. % $Id: manual.tex,v 1.40 2000/08/09 19:09:20 roberto Exp roberto $
  2. \documentclass[11pt]{article}
  3. \usepackage{fullpage,bnf}
  4. \usepackage{graphicx}
  5. %\usepackage{times}
  6. \catcode`\_=12
  7. \newcommand{\See}[1]{Section~\ref{#1}}
  8. \newcommand{\see}[1]{(see \See{#1})}
  9. \newcommand{\M}[1]{\rm\emph{#1}}
  10. \newcommand{\T}[1]{{\tt #1}}
  11. \newcommand{\Math}[1]{$#1$}
  12. \newcommand{\nil}{{\bf nil}}
  13. \def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}}
  14. \newcommand{\Index}[1]{#1\index{#1}}
  15. \newcommand{\IndexVerb}[1]{\T{#1}\index{#1}}
  16. \newcommand{\IndexEmph}[1]{\emph{#1}\index{#1}}
  17. \newcommand{\Def}[1]{\emph{#1}\index{#1}}
  18. \newcommand{\Deffunc}[1]{\index{#1}}
  19. \newcommand{\ff}{$\bullet$\ }
  20. \newcommand{\Version}{4.0}
  21. % LHF
  22. \renewcommand{\ter}[1]{{\rm`{\tt#1}'}}
  23. \newcommand{\NOTE}{\par\noindent\emph{NOTE}: }
  24. \makeindex
  25. \begin{document}
  26. %{===============================================================
  27. \thispagestyle{empty}
  28. \pagestyle{empty}
  29. {
  30. \parindent=0pt
  31. \vglue1.5in
  32. {\LARGE\bf
  33. The Programming Language Lua}
  34. \hfill
  35. \vskip4pt \hrule height 4pt width \hsize \vskip4pt
  36. \hfill
  37. Reference Manual for Lua version \Version
  38. \\
  39. \null
  40. \hfill
  41. Last revised on \today
  42. \\
  43. \vfill
  44. \centering
  45. \includegraphics[width=0.7\textwidth]{nolabel.ps}
  46. \vfill
  47. \vskip4pt \hrule height 2pt width \hsize
  48. }
  49. \newpage
  50. \begin{quotation}
  51. \parskip=10pt
  52. \footnotesize
  53. \null\vfill
  54. \noindent
  55. Copyright \copyright\ 1994--2000 TeCGraf, PUC-Rio. All rights reserved.
  56. \noindent
  57. Permission is hereby granted, without written agreement and without license
  58. or royalty fees, to use, copy, modify, and distribute this software and its
  59. documentation for any purpose, including commercial applications, subject to
  60. the following conditions:
  61. \begin{itemize}
  62. \item The above copyright notice and this permission notice shall appear in all
  63. copies or substantial portions of this software.
  64. \item The origin of this software must not be misrepresented; you must not
  65. claim that you wrote the original software. If you use this software in a
  66. product, an acknowledgment in the product documentation would be greatly
  67. appreciated (but it is not required).
  68. \item Altered source versions must be plainly marked as such, and must not be
  69. misrepresented as being the original software.
  70. \end{itemize}
  71. The authors specifically disclaim any warranties, including, but not limited
  72. to, the implied warranties of merchantability and fitness for a particular
  73. purpose. The software provided hereunder is on an ``as is'' basis, and the
  74. authors have no obligation to provide maintenance, support, updates,
  75. enhancements, or modifications. In no event shall TeCGraf, PUC-Rio, or the
  76. authors be held liable to any party for direct, indirect, special,
  77. incidental, or consequential damages arising out of the use of this software
  78. and its documentation.
  79. \noindent
  80. The Lua language and this implementation have been entirely designed and
  81. written by Waldemar Celes, Roberto Ierusalimschy and Luiz Henrique de
  82. Figueiredo at TeCGraf, PUC-Rio.
  83. \noindent
  84. This implementation contains no third-party code.
  85. \noindent
  86. Copies of this manual can be obtained at
  87. \verb|http://www.tecgraf.puc-rio.br/lua/|.
  88. \end{quotation}
  89. %}===============================================================
  90. \newpage
  91. \title{Reference Manual of the Programming Language Lua \Version}
  92. \author{%
  93. Roberto Ierusalimschy\quad
  94. Luiz Henrique de Figueiredo\quad
  95. Waldemar Celes
  96. \vspace{1.0ex}\\
  97. \smallskip
  98. \small\tt [email protected]
  99. \vspace{2.0ex}\\
  100. %MCC 08/95 ---
  101. \tecgraf\ --- Computer Science Department --- PUC-Rio
  102. }
  103. \date{{\small \tt\$Date: 2000/08/09 19:09:20 $ $}}
  104. \maketitle
  105. \thispagestyle{empty}
  106. \pagestyle{empty}
  107. \begin{abstract}
  108. \noindent
  109. Lua is a powerful, light-weight programming language
  110. designed for extending applications.
  111. Lua is also frequently used as a general-purpose, stand-alone language.
  112. Lua combines simple procedural syntax
  113. (similar to Pascal)
  114. with
  115. powerful data description constructs
  116. based on associative arrays and extensible semantics.
  117. Lua is
  118. dynamically typed,
  119. interpreted from bytecodes,
  120. and has automatic memory management with garbage collection,
  121. making it ideal for
  122. configuration,
  123. scripting,
  124. and
  125. rapid prototyping.
  126. This document describes version \Version\ of the Lua programming language
  127. and the API that allows interaction between Lua programs and their
  128. host C programs.
  129. \end{abstract}
  130. \def\abstractname{Resumo}
  131. \begin{abstract}
  132. \noindent
  133. Lua \'e uma linguagem de programa\c{c}\~ao
  134. poderosa e leve,
  135. projetada para extender aplica\c{c}\~oes.
  136. Lua tamb\'em \'e frequentemente usada como uma linguagem de prop\'osito geral.
  137. Lua combina programa\c{c}\~ao procedural
  138. (com sintaxe semelhante \`a de Pascal)
  139. com
  140. poderosas constru\c{c}\~oes para descri\c{c}\~ao de dados,
  141. baseadas em tabelas associativas e sem\^antica extens\'\i vel.
  142. Lua \'e
  143. tipada dinamicamente,
  144. interpretada a partir de \emph{bytecodes},
  145. e tem gerenciamento autom\'atico de mem\'oria com coleta de lixo.
  146. Essas caracter\'{\i}sticas fazem de Lua uma linguagem ideal para
  147. configura\c{c}\~ao,
  148. automa\c{c}\~ao (\emph{scripting})
  149. e prototipagem r\'apida.
  150. Este documento descreve a vers\~ao \Version\ da linguagem de
  151. programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite
  152. a intera\c{c}\~ao entre programas Lua e programas C hospedeiros.
  153. \end{abstract}
  154. \newpage
  155. \null
  156. \newpage
  157. \tableofcontents
  158. \newpage
  159. \setcounter{page}{1}
  160. \pagestyle{plain}
  161. \section{Introduction}
  162. Lua is an extension programming language designed to support
  163. general procedural programming with data description
  164. facilities.
  165. Lua is intended to be used as a powerful, light-weight
  166. configuration language for any program that needs one.
  167. Lua is implemented as a library, written in C.
  168. Being an extension language, Lua has no notion of a ``main'' program:
  169. it only works \emph{embedded} in a host client,
  170. called the \emph{embedding} program.
  171. This host program can invoke functions to execute a piece of
  172. code in Lua, can write and read Lua variables,
  173. and can register C~functions to be called by Lua code.
  174. Through the use of C~functions, Lua can be augmented to cope with
  175. a wide range of different domains,
  176. thus creating customized programming languages sharing a syntactical framework.
  177. Lua is free-distribution software,
  178. and provided as usual with no guarantees,
  179. as stated in its copyright notice.
  180. The implementation described in this manual is available
  181. at the following URL's:
  182. \begin{verbatim}
  183. http://www.tecgraf.puc-rio.br/lua/
  184. ftp://ftp.tecgraf.puc-rio.br/pub/lua/
  185. \end{verbatim}
  186. Like any other reference manual,
  187. this document is dry in places.
  188. For a discussion of the decisions behind the design of Lua,
  189. see the papers below,
  190. which are available at the web site above.
  191. \begin{itemize}
  192. \item
  193. R.~Ierusalimschy, L.~H.~de Figueiredo, and W.~Celes.
  194. Lua---an extensible extension language.
  195. \emph{Software: Practice \& Experience} {\bf 26} \#6 (1996) 635--652.
  196. \item
  197. L.~H.~de Figueiredo, R.~Ierusalimschy, and W.~Celes.
  198. The design and implementation of a language for extending applications.
  199. \emph{Proceedings of XXI Brazilian Seminar on Software and Hardware} (1994) 273--283.
  200. \item
  201. L.~H.~de Figueiredo, R.~Ierusalimschy, and W.~Celes.
  202. Lua: an extensible embedded language.
  203. \emph{Dr. Dobb's Journal} {\bf 21} \#12 (Dec 1996) 26--33.
  204. \end{itemize}
  205. \section{Environment and Chunks}
  206. All statements in Lua are executed in a \Def{global environment}.
  207. This environment is initialized with a call from the embedding program to
  208. \verb|lua_newstate| and
  209. persists until a call to \verb|lua_close|,
  210. or the end of the embedding program.
  211. Optionally, a user can create multiple independent global
  212. environments, and freely switch between them \see{mangstate}.
  213. The global environment can be manipulated by Lua code or
  214. by the embedding program,
  215. which can read and write global variables
  216. using API functions from the library that implements Lua.
  217. \Index{Global variables} do not need declaration.
  218. Any variable is assumed to be global unless explicitly declared local
  219. \see{localvar}.
  220. Before the first assignment, the value of a global variable is \nil;
  221. this default can be changed \see{tag-method}.
  222. A ``table of globals'' (called \emph{tog}) is used to keep all
  223. global names and values.
  224. The unit of execution of Lua is called a \Def{chunk}.
  225. A chunk is simply a sequence of statements,
  226. which are executed sequentially.
  227. Each statement can be optionally followed by a semicolon:
  228. \begin{Produc}
  229. \produc{chunk}{\rep{stat} \opt{\ter{;}}}
  230. \end{Produc}%
  231. Statements are described in \See{stats}.
  232. (The notation above is the usual extended BNF,
  233. in which
  234. \rep{\emph{a}} means 0 or more \emph{a}'s,
  235. \opt{\emph{a}} means an optional \emph{a}, and
  236. \oneormore{\emph{a}} means one or more \emph{a}'s.)
  237. A chunk may be in a file or in a string inside the host program.
  238. When a chunk is executed, first all its code is pre-compiled,
  239. and then the statements are executed in sequential order.
  240. All modifications a chunk effects on the global environment persist
  241. after the chunk ends.
  242. Chunks may also be pre-compiled into binary form;
  243. see program \IndexVerb{luac} for details.
  244. Text files with chunks and their binary pre-compiled forms
  245. are interchangeable.
  246. Lua automatically detects the file type and acts accordingly.
  247. \index{pre-compilation}
  248. \section{\Index{Types and Tags}} \label{TypesSec}
  249. Lua is a \emph{dynamically typed language}.
  250. This means that
  251. variables do not have types; only values do.
  252. Therefore, there are no type definitions in the language.
  253. All values carry their own type.
  254. Besides a type, all values also have a \IndexEmph{tag}.
  255. There are six \Index{basic types} in Lua: \Def{nil}, \Def{number},
  256. \Def{string}, \Def{function}, \Def{userdata}, and \Def{table}.
  257. \emph{Nil} is the type of the value \nil,
  258. whose main property is to be different from any other value.
  259. \emph{Number} represents real (double-precision floating-point) numbers,
  260. while \emph{string} has the usual meaning.
  261. Lua is \Index{eight-bit clean},
  262. and so strings may contain any 8-bit character,
  263. \emph{including} embedded zeros (\verb|'\0'|) \see{lexical}.
  264. The \verb|type| function returns a string describing the type
  265. of a given value \see{pdf-type}.
  266. Functions are considered \emph{first-class values} in Lua.
  267. This means that functions can be stored in variables,
  268. passed as arguments to other functions, and returned as results.
  269. Lua can call (and manipulate) functions written in Lua and
  270. functions written in C.
  271. The kinds of functions can be distinguished by their tags:
  272. all Lua functions have the same tag,
  273. and all C~functions have the same tag,
  274. which is different from the tag of Lua functions.
  275. The \verb|tag| function returns the tag
  276. of a given value \see{pdf-tag}.
  277. The type \emph{userdata} is provided to allow
  278. arbitrary \Index{C pointers} to be stored in Lua variables.
  279. It corresponds to a \verb|void*| and has no pre-defined operations in Lua,
  280. besides assignment and equality test.
  281. However, by using \emph{tag methods},
  282. the programmer can define operations for \emph{userdata} values
  283. \see{tag-method}.
  284. The type \emph{table} implements \Index{associative arrays},
  285. that is, \Index{arrays} that can be indexed not only with numbers,
  286. but with any value (except \nil).
  287. Therefore, this type may be used not only to represent ordinary arrays,
  288. but also symbol tables, sets, records, etc.
  289. Tables are the main data structuring mechanism in Lua.
  290. To represent \Index{records}, Lua uses the field name as an index.
  291. The language supports this representation by
  292. providing \verb|a.name| as syntactic sugar for \verb|a["name"]|.
  293. Tables may also carry \emph{methods}:
  294. Because functions are first class values,
  295. table fields may contain functions.
  296. The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|,
  297. which calls the method \verb|f| from the table \verb|t| passing
  298. itself as the first parameter \see{func-def}.
  299. Note that tables are \emph{objects}, and not values.
  300. Variables cannot contain tables, only \emph{references} to them.
  301. Assignment, parameter passing, and returns always manipulate references
  302. to tables, and do not imply any kind of copy.
  303. Moreover, tables must be explicitly created before used
  304. \see{tableconstructor}.
  305. Tags are mainly used to select \emph{tag methods} when
  306. some events occur.
  307. Tag methods are the main mechanism for extending the
  308. semantics of Lua \see{tag-method}.
  309. Each of the types \M{nil}, \M{number}, and \M{string} has a different tag.
  310. All values of each of these types have the same pre-defined tag.
  311. Values of type \M{function} can have two different tags,
  312. depending on whether they are Lua functions or C~functions.
  313. Finally,
  314. values of type \M{userdata} and \M{table} have
  315. variable tags, assigned by the program \see{tag-method}.
  316. Tags are created with the function \verb|newtag|,
  317. and the function \verb|tag| returns the tag of a given value.
  318. To change the tag of a given table,
  319. there is the function \verb|settag| \see{pdf-newtag}.
  320. \section{The Language}
  321. This section describes the lexis, the syntax, and the semantics of Lua.
  322. \subsection{Lexical Conventions} \label{lexical}
  323. \IndexEmph{Identifiers} in Lua can be any string of letters,
  324. digits, and underscores,
  325. not beginning with a digit.
  326. This coincides with the definition of identifiers in most languages,
  327. except that
  328. the definition of letter depends on the current locale:
  329. Any character considered alphabetic by the current locale
  330. can be used in an identifier.
  331. The following words are \emph{reserved}, and cannot be used as identifiers:
  332. \index{reserved words}
  333. \begin{verbatim}
  334. and break do else
  335. elseif end for function
  336. if local nil not
  337. or repeat return then
  338. until while
  339. \end{verbatim}
  340. Lua is a case-sensitive language:
  341. \T{and} is a reserved word, but \T{And} and \T{\'and}
  342. (if the locale permits) are two different, valid identifiers.
  343. As a convention, identifiers starting with underscore followed by
  344. uppercase letters (such as \verb|_INPUT|)
  345. are reserved for internal variables.
  346. The following strings denote other \Index{tokens}:
  347. \begin{verbatim}
  348. ~= <= >= < > == = + - * / %
  349. ( ) { } [ ] ; , . .. ...
  350. \end{verbatim}
  351. \IndexEmph{Literal strings}
  352. can be delimited by matching single or double quotes,
  353. and can contain the C-like escape sequences
  354. \verb|'\a'| (bell),
  355. \verb|'\b'| (backspace),
  356. \verb|'\f'| (form feed),
  357. \verb|'\n'| (newline),
  358. \verb|'\r'| (carriage return),
  359. \verb|'\t'| (horizontal tab),
  360. \verb|'\v'| (vertical tab),
  361. \verb|'\\'|, (backslash),
  362. \verb|'\"'|, (double quote),
  363. \verb|'\''| (single quote),
  364. and \verb|'\|\emph{newline}\verb|'| (that is, a backslash followed by a real newline,
  365. which results in a newline in the string).
  366. A character in a string may also be specified by its numerical value,
  367. through the escape sequence \verb|'\ddd'|,
  368. where \verb|ddd| is a sequence of up to three \emph{decimal} digits.
  369. Strings in Lua may contain any 8-bit value, including embedded zeros,
  370. which can be specified as \verb|'\000'|.
  371. Literal strings can also be delimited by matching \verb|[[| \dots\ \verb|]]|.
  372. Literals in this bracketed form may run for several lines,
  373. may contain nested \verb|[[ ... ]]| pairs,
  374. and do not interpret escape sequences.
  375. This form is specially convenient for
  376. writing strings that contain program pieces or
  377. other quoted strings.
  378. As an example, in a system using ASCII,
  379. the following three literals are equivalent:
  380. \begin{verbatim}
  381. 1) "alo\n123\""
  382. 2) '\97lo\10\04923"'
  383. 3) [[alo
  384. 123"]]
  385. \end{verbatim}
  386. \Index{Comments} start anywhere outside a string with a
  387. double hyphen (\verb|--|) and run until the end of the line.
  388. Moreover,
  389. the first line of a chunk is skipped if it starts with \verb|#|.
  390. This facility allows the use of Lua as a script interpreter
  391. in Unix systems \see{lua-sa}.
  392. \Index{Numerical constants} may be written with an optional decimal part,
  393. and an optional decimal exponent.
  394. Examples of valid numerical constants are
  395. \begin{verbatim}
  396. 3 3.0 3.1416 314.16e-2 0.31416E1
  397. \end{verbatim}
  398. \subsection{\Index{Coercion}} \label{coercion}
  399. Lua provides some automatic conversions between values at run time.
  400. Any arithmetic operation applied to a string tries to convert
  401. that string to a number, following the usual rules.
  402. Conversely, whenever a number is used when a string is expected,
  403. that number is converted to a string, in a reasonable format.
  404. The format is chosen so that
  405. a conversion from number to string then back to number
  406. reproduces the original number \emph{exactly}.
  407. Thus,
  408. the conversion does not necessarily produces nice-looking text for some numbers.
  409. For complete control of how numbers are converted to strings,
  410. use the \verb|format| function \see{format}.
  411. \subsection{\Index{Adjustment}} \label{adjust}
  412. Functions in Lua can return many values.
  413. Because there are no type declarations,
  414. when a function is called
  415. the system does not know how many values the function will return,
  416. or how many parameters it needs.
  417. Therefore, sometimes, a list of values must be \emph{adjusted}, at run time,
  418. to a given length.
  419. If there are more values than are needed,
  420. then the excess values are thrown away.
  421. If there are less values than are needed,
  422. then the list is extended with as many \nil's as needed.
  423. This adjustment occurs in multiple assignments \see{assignment}
  424. and function calls \see{functioncall}.
  425. \subsection{Statements}\label{stats}
  426. Lua supports an almost conventional set of \Index{statements},
  427. similar to those in Pascal or C.
  428. The conventional commands include
  429. assignment, control structures, and procedure calls.
  430. Non-conventional commands include table constructors
  431. \see{tableconstructor}
  432. and local variable declarations \see{localvar}.
  433. \subsubsection{Blocks}
  434. A \Index{block} is a list of statements;
  435. syntatically, this is equal to a chunk:
  436. \begin{Produc}
  437. \produc{block}{chunk}
  438. \end{Produc}%
  439. A block may be explicitly delimited:
  440. \begin{Produc}
  441. \produc{stat}{\rwd{do} block \rwd{end}}
  442. \end{Produc}%
  443. This is useful to control the scope of local variables \see{localvar},
  444. and to add a \rwd{return} or \rwd{break} statement in the middle
  445. of another block; for instance,
  446. \begin{verbatim}
  447. do return end -- return is the last statement in this block
  448. \end{verbatim}
  449. \subsubsection{\Index{Assignment}} \label{assignment}
  450. The language allows \Index{multiple assignment}.
  451. Therefore, the syntax for assignment
  452. defines a list of variables on the left side
  453. and a list of expressions on the right side.
  454. Both lists have their elements separated by commas:
  455. \begin{Produc}
  456. \produc{stat}{varlist1 \ter{=} explist1}
  457. \produc{varlist1}{var \rep{\ter{,} var}}
  458. \end{Produc}%
  459. This statement first evaluates all values on the right side
  460. and eventual indices on the left side,
  461. and then makes the assignments.
  462. So
  463. \begin{verbatim}
  464. i = 3
  465. i, a[i] = 4, 20
  466. \end{verbatim}
  467. sets \verb|a[3]| to 20, but does not affect \verb|a[4]|.
  468. Multiple assignment can be used to exchange two values, as in
  469. \begin{verbatim}
  470. x, y = y, x
  471. \end{verbatim}
  472. The two lists in a multiple assignment may have different lengths.
  473. Before the assignment, the list of values is adjusted to
  474. the length of the list of variables \see{adjust}.
  475. A single name can denote a global variable, a local variable,
  476. or a formal parameter:
  477. \begin{Produc}
  478. \produc{var}{name}
  479. \end{Produc}%
  480. Square brackets are used to index a table:
  481. \begin{Produc}
  482. \produc{var}{varorfunc \ter{[} exp1 \ter{]}}
  483. \produc{varorfunc}{var \Or functioncall}
  484. \end{Produc}%
  485. The \M{varorfunc} should result in a table value,
  486. from where the field indexed by the expression \M{exp1}
  487. value gets the assigned value.
  488. The syntax \verb|var.NAME| is just syntactic sugar for
  489. \verb|var["NAME"]|:
  490. \begin{Produc}
  491. \produc{var}{varorfunc \ter{.} name}
  492. \end{Produc}%
  493. The meaning of assignments and evaluations of global variables and
  494. indexed variables can be changed by tag methods \see{tag-method}.
  495. Actually,
  496. an assignment \verb|x = val|, where \verb|x| is a global variable,
  497. is equivalent to a call \verb|setglobal("x", val)|;
  498. an assignment \verb|t[i] = val| is equivalent to
  499. \verb|settable_event(t,i,val)|.
  500. See \See{tag-method} for a complete description of these functions.
  501. (The function \verb|setglobal| is pre-defined in Lua.
  502. The function \T{settable\_event} is used only for explanatory purposes.)
  503. \subsubsection{Control Structures}
  504. The control structures
  505. \index{while-do}\index{repeat-until}\index{if-then-else}%
  506. \T{if}, \T{while}, and \T{repeat} have the usual meaning and
  507. familiar syntax:
  508. \begin{Produc}
  509. \produc{stat}{\rwd{while} exp1 \rwd{do} block \rwd{end}}
  510. \produc{stat}{\rwd{repeat} block \rwd{until} exp1}
  511. \produc{stat}{\rwd{if} exp1 \rwd{then} block
  512. \rep{\rwd{elseif} exp1 \rwd{then} block}
  513. \opt{\rwd{else} block} \rwd{end}}
  514. \end{Produc}%
  515. The \Index{condition expression} \M{exp1} of a control structure may return any value.
  516. All values different from \nil\ are considered true;
  517. only \nil\ is considered false.
  518. \index{return}
  519. The \rwd{return} statement is used to return values
  520. from a function or from a chunk.
  521. \label{return}
  522. Because functions or chunks may return more than one value,
  523. the syntax for a \Index{return statement} is
  524. \begin{Produc}
  525. \produc{stat}{\rwd{return} \opt{explist1}}
  526. \end{Produc}%
  527. \index{break}
  528. The \rwd{break} statement can be used to terminate the execution of a loop,
  529. skipping to the next statement after the loop:
  530. \begin{Produc}
  531. \produc{stat}{\rwd{break}}
  532. \end{Produc}%
  533. A \rwd{break} ends the innermost enclosing loop
  534. (while, repeat, or for).
  535. \NOTE
  536. For syntactic reasons, \rwd{return} and \rwd{break}
  537. statements can only be written as the last statements of a block.
  538. \subsubsection{For Statement} \label{for}\index{for}
  539. The \rwd{for} statement has two forms,
  540. one for numbers and one for tables.
  541. The numerical \rwd{for} loop has the following syntax:
  542. \begin{Produc}
  543. \produc{stat}{\rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1}
  544. \rwd{do} block \rwd{end}}
  545. \end{Produc}%
  546. A \rwd{for} statement like
  547. \begin{verbatim}
  548. for var=e1,e2,e3 do block end
  549. \end{verbatim}
  550. is equivalent to the following code:
  551. \begin{verbatim}
  552. do
  553. local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3)
  554. if not (var and _limit and _step) then error() end
  555. while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do
  556. block
  557. var = var+_step
  558. end
  559. end
  560. \end{verbatim}
  561. Notice the following:
  562. \begin{itemize}\itemsep=0pt
  563. \item \verb|_limit| and \verb|_step| are invisible variables.
  564. The names are here for explanatory purposes only.
  565. \item The behavior is \emph{undefined} if you assign to \verb|var| inside
  566. the block.
  567. \item If the third expression (the step) is absent, then a step of 1 is used.
  568. \item Both the limit and the step are evaluated only once,
  569. before the loop starts.
  570. \item The variable \verb|var| is local to the statement;
  571. you cannot use its value after the \rwd{for} ends.
  572. \item You can use \rwd{break} to exit a \rwd{for}.
  573. If you need the value of the index,
  574. assign it to another variable before breaking.
  575. \end{itemize}
  576. The table \rwd{for} statement traverses all pairs
  577. index--value of a given table.
  578. It has the following syntax:
  579. \begin{Produc}
  580. \produc{stat}{\rwd{for} name \ter{,} name \rwd{in} exp
  581. \rwd{do} block \rwd{end}}
  582. \end{Produc}%
  583. A \rwd{for} statement like
  584. \begin{verbatim}
  585. for index, value in exp do block end
  586. \end{verbatim}
  587. is equivalent to the following code:
  588. \begin{verbatim}
  589. do
  590. local _t = exp
  591. local index, value = next(t, nil)
  592. while index do
  593. block
  594. index, value = next(t, index)
  595. end
  596. end
  597. \end{verbatim}
  598. Notice the following:
  599. \begin{itemize}\itemsep=0pt
  600. \item \verb|_t| is an invisible variable.
  601. The name is here for explanatory purposes only.
  602. \item The behavior is undefined if you assign to \verb|index| inside
  603. the block.
  604. \item The behavior is undefined if you create
  605. new indices in table \verb|_t| during the traversal.
  606. However, it is safe to change the values associated with present indices.
  607. \item The variables \verb|index| and \verb|value| are local to the statement;
  608. you cannot use their values after the \rwd{for} ends.
  609. \item You can use \rwd{break} to exit a \rwd{for}.
  610. If you need the value of \verb|index| or \verb|value|,
  611. assign them to other variables before breaking.
  612. \item The order that table elements are traversed is completely undefined,
  613. \emph{even for numerical indices}.
  614. If you want to traverse indices in numerical order,
  615. use a numerical \rwd{for}.
  616. \end{itemize}
  617. \subsubsection{Function Calls as Statements} \label{funcstat}
  618. Because of possible side-effects,
  619. function calls can be executed as statements:
  620. \begin{Produc}
  621. \produc{stat}{functioncall}
  622. \end{Produc}%
  623. In this case, all returned values are thrown away.
  624. Function calls are explained in \See{functioncall}.
  625. \subsubsection{Local Declarations} \label{localvar}
  626. \Index{Local variables} may be declared anywhere inside a block.
  627. The declaration may include an initial assignment:
  628. \begin{Produc}
  629. \produc{stat}{\rwd{local} declist \opt{init}}
  630. \produc{declist}{name \rep{\ter{,} name}}
  631. \produc{init}{\ter{=} explist1}
  632. \end{Produc}%
  633. If present, an initial assignment has the same semantics
  634. of a multiple assignment.
  635. Otherwise, all variables are initialized with \nil.
  636. The scope of local variables begins \emph{after}
  637. the declaration and lasts until the end of the block.
  638. Thus, the code
  639. \verb|local print=print|
  640. creates a local variable called \verb|print| whose
  641. initial value is that of the \emph{global} variable of the same name.
  642. \subsection{\Index{Expressions}}
  643. \subsubsection{\Index{Basic Expressions}}
  644. The basic expressions in Lua are
  645. \begin{Produc}
  646. \produc{exp}{\ter{(} exp \ter{)}}
  647. \produc{exp}{\rwd{nil}}
  648. \produc{exp}{number}
  649. \produc{exp}{literal}
  650. \produc{exp}{function}
  651. \produc{exp}{var}
  652. \produc{exp}{upvalue}
  653. \produc{exp}{functioncall}
  654. \produc{exp}{tableconstructor}
  655. \end{Produc}%
  656. Numbers (numerical constants) and
  657. literal strings are explained in \See{lexical};
  658. variables are explained in \See{assignment};
  659. upvalues are explained in \See{upvalue};
  660. function definitions (\M{function}) are explained in \See{func-def};
  661. function calls are explained in \See{functioncall}.
  662. Table constructors are explained in \See{tableconstructor}.
  663. An access to a global variable \verb|x| is equivalent to a
  664. call \verb|getglobal("x")|;
  665. an access to an indexed variable \verb|t[i]| is equivalent to
  666. a call \verb|gettable_event(t,i)|.
  667. See \See{tag-method} for a description of these functions.
  668. (Function \verb|getglobal| is pre-defined in Lua.
  669. Function \T{gettable\_event} is used only for explanatory purposes.)
  670. The non-terminal \M{exp1} is used to indicate that the values
  671. returned by an expression must be adjusted to one single value:
  672. \begin{Produc}
  673. \produc{exp1}{exp}
  674. \end{Produc}%
  675. \subsubsection{Arithmetic Operators}
  676. Lua supports the usual \Index{arithmetic operators}:
  677. the binary \verb|+| (addition),
  678. \verb|-| (subtraction), \verb|*| (multiplication),
  679. \verb|/| (division) and \verb|^| (exponentiation),
  680. and unary \verb|-| (negation).
  681. If the operands are numbers, or strings that can be converted to
  682. numbers (according to the rules given in \See{coercion}),
  683. then all operations except exponentiation have the usual meaning.
  684. Otherwise, an appropriate tag method is called \see{tag-method}.
  685. An exponentiation always calls a tag method.
  686. The standard mathematical library redefines this method for numbers,
  687. giving the expected meaning to \Index{exponentiation}
  688. \see{mathlib}.
  689. \subsubsection{Relational Operators}
  690. Lua provides the following \Index{relational operators}:
  691. \begin{verbatim}
  692. == ~= < > <= >=
  693. \end{verbatim}
  694. All these return \nil\ as false and a value different from \nil\ as true.
  695. Equality first compares the tags of its operands.
  696. If they are different, then the result is \nil.
  697. Otherwise, their values are compared.
  698. Numbers and strings are compared in the usual way.
  699. Tables, userdata, and functions are compared by reference,
  700. that is, two tables are considered equal only if they are the \emph{same} table.
  701. The operator \verb|~=| is exactly the negation of equality (\verb|==|).
  702. \NOTE
  703. The conversion rules of \See{coercion}
  704. \emph{do not} apply to equality comparisons.
  705. Thus, \verb|"0"==0| evaluates to \emph{false},
  706. and \verb|t[0]| and \verb|t["0"]| denote different
  707. entries in a table.
  708. The order operators work as follows.
  709. If both arguments are numbers, then they are compared as such.
  710. Otherwise, if both arguments are strings,
  711. then their values are compared using lexicographical order.
  712. Otherwise, the ``lt'' tag method is called \see{tag-method}.
  713. \subsubsection{Logical Operators}
  714. The \Index{logical operators} are
  715. \index{and}\index{or}\index{not}
  716. \begin{verbatim}
  717. and or not
  718. \end{verbatim}
  719. Like control structures, all logical operators
  720. consider \nil\ as false and anything else as true.
  721. The conjunction operator \verb|and| returns \nil\ if its first argument is \nil;
  722. otherwise, it returns its second argument.
  723. The disjunction operator \verb|or| returns its first argument
  724. if it is different from \nil;
  725. otherwise, it returns its second argument.
  726. Both \verb|and| and \verb|or| use \Index{short-cut evaluation},
  727. that is,
  728. the second operand is evaluated only when necessary.
  729. There are two useful Lua idioms with logical operators.
  730. The first idiom is \verb|x = x or v|,
  731. which is equivalent to
  732. \begin{verbatim}
  733. if x == nil then x = v end
  734. \end{verbatim}
  735. i.e., it sets \verb|x| to a default value \verb|v| when
  736. \verb|x| is not set.
  737. The other idiom is \verb|x = a and b or c|,
  738. which should be read as \verb|x = a and (b or c)|,
  739. is equivalent to
  740. \begin{verbatim}
  741. if a then x = b else x = c end
  742. \end{verbatim}
  743. provided that \verb|b| is not \nil.
  744. \subsubsection{Concatenation}
  745. The string \Index{concatenation} operator in Lua is
  746. denoted by ``\IndexVerb{..}''.
  747. If both operands are strings or numbers, they are converted to
  748. strings according to the rules in \See{coercion}.
  749. Otherwise, the ``concat'' tag method is called \see{tag-method}.
  750. \subsubsection{Precedence}
  751. \Index{Operator precedence} follows the table below,
  752. from the lower to the higher priority:
  753. \begin{verbatim}
  754. and or
  755. < > <= >= ~= ==
  756. ..
  757. + -
  758. * /
  759. not - (unary)
  760. ^
  761. \end{verbatim}
  762. All binary operators are left associative,
  763. except for \verb|^| (exponentiation),
  764. which is right associative.
  765. \NOTE
  766. The pre-compiler may rearrange the order of evaluation of
  767. associative operators (such as~\verb|..| or~\verb|+|),
  768. as long as these optimizations do not change normal results.
  769. However, these optimizations may change some results
  770. if you define non-associative
  771. tag methods for these operators.
  772. \subsubsection{Table Constructors} \label{tableconstructor}
  773. Table \Index{constructors} are expressions that create tables;
  774. every time a constructor is evaluated, a new table is created.
  775. Constructors can be used to create empty tables,
  776. or to create a table and initialize some fields.
  777. The general syntax for constructors is
  778. \begin{Produc}
  779. \produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}}
  780. \produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist
  781. \Or ffieldlist \ter{;} lfieldlist}
  782. \produc{lfieldlist}{\opt{lfieldlist1}}
  783. \produc{ffieldlist}{\opt{ffieldlist1}}
  784. \end{Produc}%
  785. The form \emph{lfieldlist1} is used to initialize lists:
  786. \begin{Produc}
  787. \produc{lfieldlist1}{exp \rep{\ter{,} exp} \opt{\ter{,}}}
  788. \end{Produc}%
  789. The expressions in the list are assigned to consecutive numerical indices,
  790. starting with 1.
  791. For example,
  792. \begin{verbatim}
  793. a = {"v1", "v2", 34}
  794. \end{verbatim}
  795. is equivalent to
  796. \begin{verbatim}
  797. do
  798. local temp = {}
  799. temp[1] = "v1"
  800. temp[2] = "v2"
  801. temp[3] = 34
  802. a = temp
  803. end
  804. \end{verbatim}
  805. The form \emph{ffieldlist1} initializes other fields in a table:
  806. \begin{Produc}
  807. \produc{ffieldlist1}{ffield \rep{\ter{,} ffield} \opt{\ter{,}}}
  808. \produc{ffield}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp}
  809. \end{Produc}%
  810. For example,
  811. \begin{verbatim}
  812. a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c}
  813. \end{verbatim}
  814. is equivalent to
  815. \begin{verbatim}
  816. do
  817. local temp = {}
  818. temp[f(k)] = g(y)
  819. temp.x = 1 -- or temp["x"] = 1
  820. temp.y = 3 -- or temp["y"] = 3
  821. temp[0] = b+c
  822. a = temp
  823. end
  824. \end{verbatim}
  825. An expression like \verb|{x = 1, y = 4}| is
  826. in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|.
  827. Both forms may have an optional trailing comma,
  828. and can be used in the same constructor separated by
  829. a semi-colon.
  830. For example, all forms below are correct.
  831. \begin{verbatim}
  832. x = {;}
  833. x = {"a", "b",}
  834. x = {type="list"; "a", "b"}
  835. x = {f(0), f(1), f(2),; n=3,}
  836. \end{verbatim}
  837. \subsubsection{Function Calls} \label{functioncall}
  838. A \Index{function call} has the following syntax:
  839. \begin{Produc}
  840. \produc{functioncall}{varorfunc args}
  841. \end{Produc}%
  842. First, \M{varorfunc} is evaluated.
  843. If its value has type \emph{function},
  844. then this function is called,
  845. with the given arguments.
  846. Otherwise, the ``function'' tag method is called,
  847. having as first parameter the value of \M{varorfunc},
  848. and then the original call arguments.
  849. The form
  850. \begin{Produc}
  851. \produc{functioncall}{varorfunc \ter{:} name args}
  852. \end{Produc}%
  853. can be used to call ``methods''.
  854. A call \verb|varorfunc:name(...)|
  855. is syntactic sugar for
  856. \begin{verbatim}
  857. varorfunc.name(varorfunc, ...)
  858. \end{verbatim}
  859. except that \verb|varorfunc| is evaluated only once.
  860. Arguments have the following syntax:
  861. \begin{Produc}
  862. \produc{args}{\ter{(} \opt{explist1} \ter{)}}
  863. \produc{args}{tableconstructor}
  864. \produc{args}{\ter{literal}}
  865. \produc{explist1}{\rep{exp1 \ter{,}} exp}
  866. \end{Produc}%
  867. All argument expressions are evaluated before the call.
  868. A call of the form \verb|f{...}| is syntactic sugar for
  869. \verb|f({...})|, that is,
  870. the parameter list is a single new table.
  871. A call of the form \verb|f'...'|
  872. (or \verb|f"..."| or \verb|f[[...]]|) is syntactic sugar for
  873. \verb|f('...')|, that is,
  874. the parameter list is a single literal string.
  875. Because a function can return any number of results
  876. \see{return},
  877. the number of results must be adjusted before they are used.
  878. If the function is called as a statement \see{funcstat},
  879. then its return list is adjusted to~0,
  880. thus discarding all returned values.
  881. If the function is called in a place that needs a single value
  882. (syntactically denoted by the non-terminal \M{exp1}),
  883. then its return list is adjusted to~1,
  884. thus discarding all returned values but the first one.
  885. If the function is called in a place that can hold many values
  886. (syntactically denoted by the non-terminal \M{exp}),
  887. then no adjustment is made.
  888. The only places that can hold many values
  889. is the last (or the only) expression in an assignment,
  890. in an argument list, or in a return statement.
  891. Here are some examples.
  892. \begin{verbatim}
  893. f(); -- adjusted to 0 results
  894. g(f(), x); -- f() is adjusted to 1 result
  895. g(x, f()); -- g gets x plus all values returned by f()
  896. a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil)
  897. a,b,c = x, f(); -- f() is adjusted to 2
  898. a,b,c = f(); -- f() is adjusted to 3
  899. return f(); -- returns all values returned by f()
  900. return x,y,f(); -- returns a, b, and all values returned by f()
  901. \end{verbatim}
  902. \subsubsection{\Index{Function Definitions}} \label{func-def}
  903. The syntax for function definition is
  904. \begin{Produc}
  905. \produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)}
  906. block \rwd{end}}
  907. \produc{stat}{\rwd{function} funcname \ter{(} \opt{parlist1} \ter{)}
  908. block \rwd{end}}
  909. \produc{funcname}{name \Or name \ter{.} name \Or name \ter{:} name}
  910. \end{Produc}%
  911. The statement
  912. \begin{verbatim}
  913. function f ()
  914. ...
  915. end
  916. \end{verbatim}
  917. is just syntactic sugar for
  918. \begin{verbatim}
  919. f = function ()
  920. ...
  921. end
  922. \end{verbatim}
  923. and the statement
  924. \begin{verbatim}
  925. function o.f ()
  926. ...
  927. end
  928. \end{verbatim}
  929. is syntactic sugar for
  930. \begin{verbatim}
  931. o.f = function ()
  932. ...
  933. end
  934. \end{verbatim}
  935. A function definition is an executable expression,
  936. whose value has type \emph{function}.
  937. When Lua pre-compiles a chunk,
  938. all its function bodies are pre-compiled, too.
  939. Then, whenever Lua executes the function definition,
  940. its upvalues are fixed \see{upvalue},
  941. and the function is \emph{instantiated} (or \emph{closed}).
  942. This function instance (or \emph{closure})
  943. is the final value of the expression.
  944. Different instances of the same function
  945. may have different upvalues.
  946. Parameters act as local variables,
  947. initialized with the argument values:
  948. \begin{Produc}
  949. \produc{parlist1}{\ter{\ldots}}
  950. \produc{parlist1}{name \rep{\ter{,} name} \opt{\ter{,} \ter{\ldots}}}
  951. \end{Produc}%
  952. \label{vararg}
  953. When a function is called,
  954. the list of \Index{arguments} is adjusted to
  955. the length of the list of parameters \see{adjust},
  956. unless the function is a \Def{vararg} function,
  957. which is
  958. indicated by the dots (\ldots) at the end of its parameter list.
  959. A vararg function does not adjust its argument list;
  960. instead, it collects all extra arguments into an implicit parameter,
  961. called \IndexVerb{arg}.
  962. The value of \verb|arg| is a table,
  963. with a field~\verb|n| whose value is the number of extra arguments,
  964. and the extra arguments at positions 1,~2,~\ldots,\M{n}.
  965. As an example, consider the following definitions:
  966. \begin{verbatim}
  967. function f(a, b) end
  968. function g(a, b, ...) end
  969. function r() return 1,2,3 end
  970. \end{verbatim}
  971. Then, we have the following mapping from arguments to parameters:
  972. \begin{verbatim}
  973. CALL PARAMETERS
  974. f(3) a=3, b=nil
  975. f(3, 4) a=3, b=4
  976. f(3, 4, 5) a=3, b=4
  977. f(r(), 10) a=1, b=10
  978. f(r()) a=1, b=2
  979. g(3) a=3, b=nil, arg={n=0}
  980. g(3, 4) a=3, b=4, arg={n=0}
  981. g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2}
  982. g(5, r()) a=5, b=1, arg={2, 3; n=2}
  983. \end{verbatim}
  984. Results are returned using the \rwd{return} statement \see{return}.
  985. If control reaches the end of a function
  986. without encountering a \rwd{return} statement,
  987. then the function returns with no results.
  988. The syntax
  989. \begin{Produc}
  990. \produc{funcname}{name \ter{:} name}
  991. \end{Produc}%
  992. is used for defining \Index{methods},
  993. that is, functions that have an implicit extra parameter \IndexVerb{self}:
  994. Thus, the statement
  995. \begin{verbatim}
  996. function v:f (...)
  997. ...
  998. end
  999. \end{verbatim}
  1000. is equivalent to
  1001. \begin{verbatim}
  1002. v.f = function (self, ...)
  1003. ...
  1004. end
  1005. \end{verbatim}
  1006. that is, the function gets an extra formal parameter called \verb|self|.
  1007. Note that the variable \verb|v| must have been
  1008. previously initialized with a table value.
  1009. \subsection{Visibility and Upvalues} \label{upvalue}
  1010. \index{Visibility} \index{Upvalues}
  1011. A function body may refer to its own local variables
  1012. (which include its parameters) and to global variables,
  1013. as long as they are not \emph{shadowed} by local
  1014. variables from enclosing functions.
  1015. A function \emph{cannot} access a local
  1016. variable from an enclosing function,
  1017. since such variables may no longer exist when the function is called.
  1018. However, a function may access the \emph{value} of a local variable
  1019. from an enclosing function, using \emph{upvalues},
  1020. whose syntax is
  1021. \begin{Produc}
  1022. \produc{upvalue}{\ter{\%} name}
  1023. \end{Produc}%
  1024. An upvalue is somewhat similar to a variable expression,
  1025. but whose value is \emph{frozen} when the function wherein it
  1026. appears is instantiated.
  1027. The name used in an upvalue may be the name of any variable visible
  1028. at the point where the function is defined,
  1029. that is
  1030. global variables and local variables from the immediately enclosing function.
  1031. Notice that when the upvalue is a table,
  1032. only the reference to that table
  1033. (which is the value of the upvalue) is frozen;
  1034. the table contents can be changed at will.
  1035. Here are some examples:
  1036. \begin{verbatim}
  1037. a,b,c = 1,2,3 -- global variables
  1038. local d
  1039. function f (x)
  1040. local b = {} -- x and b are local to f; b shadows the global b
  1041. local g = function (a)
  1042. local y -- a and y are local to g
  1043. p = a -- OK, access local 'a'
  1044. p = c -- OK, access global 'c'
  1045. p = b -- ERROR: cannot access a variable in outer scope
  1046. p = %b -- OK, access frozen value of 'b' (local to 'f')
  1047. %b = 3 -- ERROR: cannot change an upvalue
  1048. %b.x = 3 -- OK, change the table contents
  1049. p = %c -- OK, access frozen value of global 'c'
  1050. p = %y -- ERROR: 'y' is not visible where 'g' is defined
  1051. p = %d -- ERROR: 'd' is not visible where 'g' is defined
  1052. end -- g
  1053. end -- f
  1054. \end{verbatim}
  1055. \subsection{Error Handling} \label{error}
  1056. Because Lua is an extension language,
  1057. all Lua actions start from C~code in the host program
  1058. calling a function from the Lua library.
  1059. Whenever an error occurs during Lua compilation or execution,
  1060. the function \verb|_ERRORMESSAGE| is called \Deffunc{_ERRORMESSAGE}
  1061. (provided it is different from \nil),
  1062. and then the corresponding function from the library
  1063. (\verb|lua_dofile|, \verb|lua_dostring|,
  1064. \verb|lua_dobuffer|, or \verb|lua_callfunction|)
  1065. is terminated, returning an error condition.
  1066. Memory allocation error is an exception to the previous rule.
  1067. When a \verb|malloc| fails, Lua may not be able to execute the
  1068. \verb|_ERRORMESSAGE| function.
  1069. So, for this kind of error, Lua does not call
  1070. the \verb|_ERRORMESSAGE| function;
  1071. instead, the corresponding function from the library
  1072. returns immeditely with a special error code.
  1073. The only argument to \verb|_ERRORMESSAGE| is a string
  1074. describing the error.
  1075. The default definition for
  1076. this function calls \verb|_ALERT|, \Deffunc{_ALERT}
  1077. which prints the message to \verb|stderr| \see{alert}.
  1078. The standard I/O library redefines \verb|_ERRORMESSAGE|,
  1079. and uses the debug facilities \see{debugI}
  1080. to print some extra information,
  1081. such as a call stack traceback.
  1082. Lua code can explicitly generate an error by calling the built-in
  1083. function \verb|error| \see{pdf-error}.
  1084. Lua code can ``catch'' an error using the built-in function
  1085. \verb|call| \see{pdf-call}.
  1086. \subsection{Tag Methods} \label{tag-method}
  1087. Lua provides a powerful mechanism to extend its semantics,
  1088. called \Def{tag methods}.
  1089. A tag method is a programmer-defined function
  1090. that is called at specific key points during the evaluation of a program,
  1091. allowing the programmer to change the standard Lua behavior at these points.
  1092. Each of these points is called an \Def{event}.
  1093. The tag method called for any specific event is selected
  1094. according to the tag of the values involved
  1095. in the event \see{TypesSec}.
  1096. The function \IndexVerb{settagmethod} changes the tag method
  1097. associated with a given pair \M{(tag, event)}.
  1098. Its first parameter is the tag, the second parameter is the event name
  1099. (a string; see below),
  1100. and the third parameter is the new method (a function),
  1101. or \nil\ to restore the default behavior for the pair.
  1102. The \verb|settagmethod| function returns the previous tag method for that pair.
  1103. Another function, \IndexVerb{gettagmethod},
  1104. receives a tag and an event name and returns the
  1105. current method associated with the pair.
  1106. Tag methods are called in the following events,
  1107. identified by the given names.
  1108. The semantics of tag methods is better explained by a Lua function
  1109. describing the behavior of the interpreter at each event.
  1110. This function not only shows when a tag method is called,
  1111. but also its arguments, its results, and the default behavior.
  1112. The code shown here is only \emph{illustrative};
  1113. the real behavior is hard coded in the interpreter,
  1114. and it is much more efficient than this simulation.
  1115. All functions used in these descriptions
  1116. (\verb|rawget|, \verb|tonumber|, \verb|call|, etc.)
  1117. are described in \See{predefined}.
  1118. \begin{description}
  1119. \item[``add'':]\index{add event}
  1120. called when a \verb|+| operation is applied to non-numerical operands.
  1121. The function \verb|getbinmethod| defines how Lua chooses a tag method
  1122. for a binary operation.
  1123. First, Lua tries the first operand.
  1124. If its tag does not define a tag method for the operation,
  1125. then Lua tries the second operand.
  1126. If it also fails, then it gets a tag method from tag~0:
  1127. \begin{verbatim}
  1128. function getbinmethod (op1, op2, event)
  1129. return gettagmethod(tag(op1), event) or
  1130. gettagmethod(tag(op2), event) or
  1131. gettagmethod(0, event)
  1132. end
  1133. \end{verbatim}
  1134. Using this function,
  1135. the tag method for the ``add' event is
  1136. \begin{verbatim}
  1137. function add_event (op1, op2)
  1138. local o1, o2 = tonumber(op1), tonumber(op2)
  1139. if o1 and o2 then -- both operands are numeric
  1140. return o1+o2 -- '+' here is the primitive 'add'
  1141. else -- at least one of the operands is not numeric
  1142. local tm = getbinmethod(op1, op2, "add")
  1143. if tm then
  1144. -- call the method with both operands and an extra
  1145. -- argument with the event name
  1146. return tm(op1, op2, "add")
  1147. else -- no tag method available: default behavior
  1148. error("unexpected type at arithmetic operation")
  1149. end
  1150. end
  1151. end
  1152. \end{verbatim}
  1153. All global variables are kept in a table.
  1154. You can get this table calling the \verb|globals| function.
  1155. \item[``sub'':]\index{sub event}
  1156. called when a \verb|-| operation is applied to non-numerical operands.
  1157. Behavior similar to the ``add'' event.
  1158. \item[``mul'':]\index{mul event}
  1159. called when a \verb|*| operation is applied to non-numerical operands.
  1160. Behavior similar to the ``add'' event.
  1161. \item[``div'':]\index{div event}
  1162. called when a \verb|/| operation is applied to non-numerical operands.
  1163. Behavior similar to the ``add'' event.
  1164. \item[``pow'':]\index{pow event}
  1165. called when a \verb|^| operation (exponentiation) is applied.
  1166. \begin{verbatim}
  1167. function pow_event (op1, op2)
  1168. local tm = getbinmethod(op1, op2, "pow")
  1169. if tm then
  1170. -- call the method with both operands and an extra
  1171. -- argument with the event name
  1172. return tm(op1, op2, "pow")
  1173. else -- no tag method available: default behavior
  1174. error("unexpected type at arithmetic operation")
  1175. end
  1176. end
  1177. \end{verbatim}
  1178. \item[``unm'':]\index{unm event}
  1179. called when a unary \verb|-| operation is applied to a non-numerical operand.
  1180. \begin{verbatim}
  1181. function unm_event (op)
  1182. local o = tonumber(op)
  1183. if o then -- operand is numeric
  1184. return -o -- '-' here is the primitive 'unm'
  1185. else -- the operand is not numeric.
  1186. -- Try to get a tag method from the operand;
  1187. -- if it does not have one, try a "global" one (tag 0)
  1188. local tm = gettagmethod(tag(op), "unm") or
  1189. gettagmethod(0, "unm")
  1190. if tm then
  1191. -- call the method with the operand, nil, and an extra
  1192. -- argument with the event name
  1193. return tm(op, nil, "unm")
  1194. else -- no tag method available: default behavior
  1195. error("unexpected type at arithmetic operation")
  1196. end
  1197. end
  1198. end
  1199. \end{verbatim}
  1200. \item[``lt'':]\index{lt event}
  1201. called when an order operation is applied to non-numerical
  1202. or non-string operands.
  1203. It corresponds to the \verb|<| operator.
  1204. \begin{verbatim}
  1205. function lt_event (op1, op2)
  1206. if type(op1) == "number" and type(op2) == "number" then
  1207. return op1 < op2 -- numeric comparison
  1208. elseif type(op1) == "string" and type(op2) == "string" then
  1209. return op1 < op2 -- lexicographic comparison
  1210. else
  1211. local tm = getbinmethod(op1, op2, "lt")
  1212. if tm then
  1213. return tm(op1, op2, "lt")
  1214. else
  1215. error("unexpected type at comparison");
  1216. end
  1217. end
  1218. end
  1219. \end{verbatim}
  1220. The other order operators use this tag method according to the
  1221. usual equivalences:
  1222. \begin{verbatim}
  1223. a>b <=> b<a
  1224. a<=b <=> not (b<a)
  1225. a>=b <=> not (a<b)
  1226. \end{verbatim}
  1227. \item[``concat'':]\index{concatenation event}
  1228. called when a concatenation is applied to non-string operands.
  1229. \begin{verbatim}
  1230. function concat_event (op1, op2)
  1231. if (type(op1) == "string" or type(op1) == "number") and
  1232. (type(op2) == "string" or type(op2) == "number") then
  1233. return op1..op2 -- primitive string concatenation
  1234. else
  1235. local tm = getbinmethod(op1, op2, "concat")
  1236. if tm then
  1237. return tm(op1, op2, "concat")
  1238. else
  1239. error("unexpected type for concatenation")
  1240. end
  1241. end
  1242. end
  1243. \end{verbatim}
  1244. \item[``index'':]\index{index event}
  1245. called when Lua tries to retrieve the value of an index
  1246. not present in a table.
  1247. See event ``gettable'' for its semantics.
  1248. \item[``getglobal'':]\index{getglobal event}
  1249. called whenever Lua needs the value of a global variable.
  1250. This method can only be set for \nil\ and for tags
  1251. created by \verb|newtag|.
  1252. Note that
  1253. the tag is that of the \emph{current value} of the global variable.
  1254. \begin{verbatim}
  1255. function getglobal (varname)
  1256. -- access the table of globals
  1257. local value = rawget(globals(), varname)
  1258. local tm = gettagmethod(tag(value), "getglobal")
  1259. if not tm then
  1260. return value
  1261. else
  1262. return tm(varname, value)
  1263. end
  1264. end
  1265. \end{verbatim}
  1266. The function \verb|getglobal| is pre-defined in Lua \see{predefined}.
  1267. \item[``setglobal'':]\index{setglobal event}
  1268. called whenever Lua assigns to a global variable.
  1269. This method cannot be set for numbers, strings, and tables and
  1270. userdata with default tags.
  1271. \begin{verbatim}
  1272. function setglobal (varname, newvalue)
  1273. local oldvalue = rawget(globals(), varname)
  1274. local tm = gettagmethod(tag(oldvalue), "setglobal")
  1275. if not tm then
  1276. rawset(globals(), varname, newvalue)
  1277. else
  1278. tm(varname, oldvalue, newvalue)
  1279. end
  1280. end
  1281. \end{verbatim}
  1282. The function \verb|setglobal| is pre-defined in Lua \see{predefined}.
  1283. \item[``gettable'':]\index{gettable event}
  1284. called whenever Lua accesses an indexed variable.
  1285. This method cannot be set for tables with default tag.
  1286. \begin{verbatim}
  1287. function gettable_event (table, index)
  1288. local tm = gettagmethod(tag(table), "gettable")
  1289. if tm then
  1290. return tm(table, index)
  1291. elseif type(table) ~= "table" then
  1292. error("indexed expression not a table");
  1293. else
  1294. local v = rawget(table, index)
  1295. tm = gettagmethod(tag(table), "index")
  1296. if v == nil and tm then
  1297. return tm(table, index)
  1298. else
  1299. return v
  1300. end
  1301. end
  1302. end
  1303. \end{verbatim}
  1304. \item[``settable'':]\index{settable event}
  1305. called when Lua assigns to an indexed variable.
  1306. This method cannot be set for tables with default tag.
  1307. \begin{verbatim}
  1308. function settable_event (table, index, value)
  1309. local tm = gettagmethod(tag(table), "settable")
  1310. if tm then
  1311. tm(table, index, value)
  1312. elseif type(table) ~= "table" then
  1313. error("indexed expression not a table")
  1314. else
  1315. rawset(table, index, value)
  1316. end
  1317. end
  1318. \end{verbatim}
  1319. \item[``function'':]\index{function event}
  1320. called when Lua tries to call a non-function value.
  1321. \begin{verbatim}
  1322. function function_event (func, ...)
  1323. if type(func) == "function" then
  1324. return call(func, arg)
  1325. else
  1326. local tm = gettagmethod(tag(func), "function")
  1327. if tm then
  1328. for i=arg.n,1,-1 do
  1329. arg[i+1] = arg[i]
  1330. end
  1331. arg.n = arg.n+1
  1332. arg[1] = func
  1333. return call(tm, arg)
  1334. else
  1335. error("call expression not a function")
  1336. end
  1337. end
  1338. end
  1339. \end{verbatim}
  1340. \item[``gc'':]\index{gc event}
  1341. called when Lua is ``garbage collecting'' a userdata.
  1342. This tag method can be set only from~C,
  1343. and cannot be set for a userdata with default tag.
  1344. For each userdata to be collected,
  1345. Lua does the equivalent of the following function:
  1346. \begin{verbatim}
  1347. function gc_event (obj)
  1348. local tm = gettagmethod(tag(obj), "gc")
  1349. if tm then
  1350. tm(obj)
  1351. end
  1352. end
  1353. \end{verbatim}
  1354. Moreover, at the end of a garbage collection cycle,
  1355. Lua does the equivalent of the call \verb|gc_event(nil)|.
  1356. \end{description}
  1357. \section{The Application Program Interface}
  1358. This section describes the API for Lua, that is,
  1359. the set of C~functions available to the host program to communicate
  1360. with the Lua library.
  1361. The API functions can be classified into the following categories:
  1362. \begin{enumerate}
  1363. \item managing states;
  1364. \item exchanging values between C and Lua;
  1365. \item executing Lua code;
  1366. \item manipulating (reading and writing) Lua objects;
  1367. \item calling Lua functions;
  1368. \item defining C~functions to be called by Lua;
  1369. \item manipulating references to Lua Objects.
  1370. \end{enumerate}
  1371. All API functions and related types and constants
  1372. are declared in the header file \verb|lua.h|.
  1373. \NOTE
  1374. Even when we use the term \emph{function},
  1375. \emph{any facility in the API may be provided as a macro instead}.
  1376. All such macros use each of its arguments exactly once,
  1377. and so do not generate hidden side-effects.
  1378. \subsection{States} \label{mangstate}
  1379. The Lua library is reentrant:
  1380. it does not have any global variable.
  1381. The whole state of the Lua interpreter
  1382. (global variables, stack, tag methods, etc.)
  1383. is stored in a dynamic structure; \Deffunc{lua_State}
  1384. this state must be passed as the first argument to almost
  1385. every function in the library.
  1386. Before calling any API function,
  1387. you must create a state.
  1388. This is done by calling\Deffunc{lua_newstate}
  1389. \begin{verbatim}
  1390. lua_State *lua_newstate (int stacksize, int builtin);
  1391. \end{verbatim}
  1392. The arguments to this function are
  1393. the stack size for the interpreter and a boolean that
  1394. indicates whether the predefined functions should be loaded or not.
  1395. Each function call needs one stack position for each local variable
  1396. and temporary variables, plus one position for book-keeping.
  1397. The stack must also have at least ten extra positions available.
  1398. For very small implementations, without recursive functions,
  1399. a stack size of 100 should be enough.
  1400. A value 0 for \verb|stacksize| uses a default size of 1024 positions.
  1401. For instance, the call
  1402. \begin{verbatim}
  1403. lua_State *L = lua_newstate(0, 1);
  1404. \end{verbatim}
  1405. creates a new state with a stack of 1024 positions
  1406. and with the predefined functions loaded;
  1407. the call
  1408. \begin{verbatim}
  1409. lua_State *L = lua_newstate(100, 0)
  1410. \end{verbatim}
  1411. creates a new state with a stack of 100 positions,
  1412. without the predefined functions.
  1413. When you create a state without the builtin function,
  1414. you must provide by yourself any function that your interpreter may need
  1415. (such as \verb|_ALERT| and \verb|_ERRORMESSAGE| for error report, etc.).
  1416. To release a state, you call
  1417. \begin{verbatim}
  1418. void lua_close (lua_State *L);
  1419. \end{verbatim}
  1420. This function destroys all objects in the current Lua environment
  1421. (calling the corresponding garbage collection tag methods)
  1422. and frees all dynamic memory used by the state.
  1423. Frequently, you do not need to call this function,
  1424. because all resources are naturally released when the program ends.
  1425. On the other hand,
  1426. long-running programs ---
  1427. like a daemon or web server, for example ---
  1428. might need to release states as soon as they are not needed,
  1429. to avoid growing too big.
  1430. With the exception of \verb|lua_newstate|,
  1431. all functions in the API need a state as their first argument.
  1432. >>>>>>>>>>>>
  1433. However, most applications use a single state.
  1434. To avoid the burden of passing this only state explicitly to all
  1435. functions, and also to keep compatibility with old versions of Lua,
  1436. the API provides a set of macros and one global variable that
  1437. take care of this state argument for single-state applications:
  1438. \begin{verbatim}
  1439. #ifndef LUA_REENTRANT
  1440. \end{verbatim}
  1441. \begin{verbatim}
  1442. extern lua_State *lua_state;
  1443. \end{verbatim}
  1444. \begin{verbatim}
  1445. #define lua_close() (lua_close)(lua_state)
  1446. #define lua_dofile(filename) (lua_dofile)(lua_state, filename)
  1447. #define lua_dostring(str) (lua_dostring)(lua_state, str)
  1448. ...
  1449. \end{verbatim}
  1450. \begin{verbatim}
  1451. #endif
  1452. \end{verbatim}
  1453. For each function in the API, there is a macro with the same name
  1454. that supplies \verb|lua_state| as the first argument to the call.
  1455. (The parentheses around the function name avoid it being expanded
  1456. again as a macro.)
  1457. The only exception is \verb|lua_newstate|;
  1458. in this case, the corresponding macro is
  1459. \begin{verbatim}
  1460. #define lua_open() ((void)(lua_state?0:(lua_state=lua_newstate(0, 1))))
  1461. \end{verbatim}
  1462. This code checks whether the global state has been initialized;
  1463. if not, it creates a new state with default settings and
  1464. assigns it to \verb|lua_state|.
  1465. By default, the single-state macros are all active.
  1466. If you need to use multiple states,
  1467. and therefore will provide the state argument explicitly in each call,
  1468. you should define \IndexVerb{LUA_REENTRANT} before
  1469. including \verb|lua.h| in your code:
  1470. \begin{verbatim}
  1471. #define LUA_REENTRANT
  1472. #include "lua.h"
  1473. \end{verbatim}
  1474. <<<<<<<<<
  1475. \subsection{Exchanging Values between C and Lua} \label{valuesCLua}
  1476. Because Lua has no static type system,
  1477. all values passed between Lua and C have type
  1478. \verb|lua_Object|\Deffunc{lua_Object},
  1479. which works like an abstract type in C that can hold any Lua value.
  1480. Values of type \verb|lua_Object| have no meaning outside Lua;
  1481. for instance,
  1482. you cannot compare two \verb|lua_Object|s directly.
  1483. Instead, you should use the following function:
  1484. \Deffunc{lua_equal}
  1485. \begin{verbatim}
  1486. int lua_equal (lua_State *L, lua_Object o1, lua_Object o2);
  1487. \end{verbatim}
  1488. To check the type of a \verb|lua_Object|,
  1489. the following functions are available:
  1490. \Deffunc{lua_isnil}\Deffunc{lua_isnumber}\Deffunc{lua_isstring}
  1491. \Deffunc{lua_istable}\Deffunc{lua_iscfunction}\Deffunc{lua_isuserdata}
  1492. \Deffunc{lua_isfunction}
  1493. \Deffunc{lua_type}
  1494. \begin{verbatim}
  1495. int lua_isnil (lua_State *L, lua_Object object);
  1496. int lua_isnumber (lua_State *L, lua_Object object);
  1497. int lua_isstring (lua_State *L, lua_Object object);
  1498. int lua_istable (lua_State *L, lua_Object object);
  1499. int lua_isfunction (lua_State *L, lua_Object object);
  1500. int lua_iscfunction (lua_State *L, lua_Object object);
  1501. int lua_isuserdata (lua_State *L, lua_Object object);
  1502. const char *lua_type (lua_State *L, lua_Object object);
  1503. \end{verbatim}
  1504. The \verb|lua_is*| functions return 1 if the object is compatible
  1505. with the given type, and 0 otherwise.
  1506. The function \verb|lua_isnumber| accepts numbers and numerical strings,
  1507. \verb|lua_isstring| accepts strings and numbers \see{coercion},
  1508. and \verb|lua_isfunction| accepts Lua functions and C~functions.
  1509. To distinguish between Lua functions and C~functions,
  1510. you should use \verb|lua_iscfunction|.
  1511. To distinguish between numbers and numerical strings,
  1512. you can use \verb|lua_type|.
  1513. The \verb|lua_type| returns one of the following strings,
  1514. describing the type of the given object:
  1515. \verb|"nil"|, \verb|"number"|, \verb|"string"|, \verb|"table"|,
  1516. \verb|"function"|, \verb|"userdata"|, or \verb|"NOOBJECT"|.
  1517. To get the tag of a \verb|lua_Object|,
  1518. use the following function:
  1519. \Deffunc{lua_tag}
  1520. \begin{verbatim}
  1521. int lua_tag (lua_State *L, lua_Object object);
  1522. \end{verbatim}
  1523. To translate a value from type \verb|lua_Object| to a specific C type,
  1524. you can use the following conversion functions:
  1525. \Deffunc{lua_getnumber}\Deffunc{lua_getstring}\Deffunc{lua_strlen}
  1526. \Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata}
  1527. \begin{verbatim}
  1528. double lua_getnumber (lua_State *L, lua_Object object);
  1529. const char *lua_getstring (lua_State *L, lua_Object object);
  1530. size_t lua_strlen (lua_State *L, lua_Object object);
  1531. lua_CFunction lua_getcfunction (lua_State *L, lua_Object object);
  1532. void *lua_getuserdata (lua_State *L, lua_Object object);
  1533. \end{verbatim}
  1534. \verb|lua_getnumber| converts a \verb|lua_Object| to a floating-point number.
  1535. This \verb|lua_Object| must be a number or a string convertible to number
  1536. \see{coercion}; otherwise, \verb|lua_getnumber| returns~0.
  1537. \verb|lua_getstring| converts a \verb|lua_Object| to a string
  1538. (\verb|const char*|).
  1539. This \verb|lua_Object| must be a string or a number;
  1540. otherwise, the function returns \verb|NULL|.
  1541. This function does not create a new string,
  1542. but returns a pointer to a string inside the Lua environment.
  1543. Those strings always have a 0 after their last character (like in C),
  1544. but may contain other zeros in their body.
  1545. If you do not know whether a string may contain zeros,
  1546. you should use \verb|lua_strlen| to get the actual length.
  1547. Because Lua has garbage collection,
  1548. there is no guarantee that the pointer returned by \verb|lua_getstring|
  1549. will be valid after the block ends
  1550. \see{GC}.
  1551. \verb|lua_getcfunction| converts a \verb|lua_Object| to a C~function.
  1552. This \verb|lua_Object| must be a C~function;
  1553. otherwise, \verb|lua_getcfunction| returns \verb|NULL|.
  1554. The type \verb|lua_CFunction| is explained in \See{LuacallC}.
  1555. \verb|lua_getuserdata| converts a \verb|lua_Object| to \verb|void*|.
  1556. This \verb|lua_Object| must have type \emph{userdata};
  1557. otherwise, \verb|lua_getuserdata| returns \verb|NULL|.
  1558. \subsection{Communication between Lua and C}\label{Lua-C-protocol}
  1559. All communication between Lua and C is done through two
  1560. abstract data types, called \Def{lua2C} and \Def{C2lua}.
  1561. The first one, as the name implies, is used to pass values
  1562. from Lua to C:
  1563. parameters when Lua calls C and results when C calls Lua.
  1564. The structure C2lua is used in the reverse direction:
  1565. parameters when C calls Lua and results when Lua calls C.
  1566. The structure lua2C is an \emph{abstract array}
  1567. that can be indexed with the function:
  1568. \Deffunc{lua_lua2C}
  1569. \begin{verbatim}
  1570. lua_Object lua_lua2C (lua_State *L, int number);
  1571. \end{verbatim}
  1572. where \verb|number| starts with 1.
  1573. When called with a number larger than the array size,
  1574. this function returns \verb|LUA_NOOBJECT|\Deffunc{LUA_NOOBJECT}.
  1575. In this way, it is possible to write C~functions that receive
  1576. a variable number of parameters,
  1577. and to call Lua functions that return a variable number of results.
  1578. Note that the structure lua2C cannot be directly modified by C code.
  1579. The structure C2lua is an \emph{abstract stack}.
  1580. Pushing elements into this stack
  1581. is done with the following functions:
  1582. \Deffunc{lua_pushnumber}\Deffunc{lua_pushlstring}\Deffunc{lua_pushstring}
  1583. \Deffunc{lua_pushcfunction}\Deffunc{lua_pushusertag}
  1584. \Deffunc{lua_pushnil}\Deffunc{lua_pushobject}
  1585. \Deffunc{lua_pushuserdata}\label{pushing}
  1586. \begin{verbatim}
  1587. void lua_pushnumber (lua_State *L, double n);
  1588. void lua_pushlstring (lua_State *L, const char *s, size_t len);
  1589. void lua_pushstring (lua_State *L, const char *s);
  1590. void lua_pushusertag (lua_State *L, void *u, int tag);
  1591. void lua_pushnil (lua_State *L);
  1592. void lua_pushobject (lua_State *L, lua_Object object);
  1593. void lua_pushcfunction (lua_State *L, lua_CFunction f); /* macro */
  1594. \end{verbatim}
  1595. All of them receive a C value,
  1596. convert it to a corresponding \verb|lua_Object|,
  1597. and leave the result on the top of C2lua.
  1598. In particular, functions \verb|lua_pushlstring| and \verb|lua_pushstring|
  1599. make an internal copy of the given string.
  1600. Function \verb|lua_pushstring| can only be used to push proper C strings
  1601. (that is, strings that end with a zero and do not contain embedded zeros);
  1602. otherwise you should use the more general \verb|lua_pushlstring|.
  1603. The function
  1604. \Deffunc{lua_pop}
  1605. \begin{verbatim}
  1606. lua_Object lua_pop (lua_State *L);
  1607. \end{verbatim}
  1608. returns a reference to the object at the top of the C2lua stack,
  1609. and pops it.
  1610. When C code calls Lua repeatedly, as in a loop,
  1611. objects returned by these calls accumulate,
  1612. and may cause a stack overflow.
  1613. To avoid this,
  1614. nested blocks can be defined with the functions
  1615. \begin{verbatim}
  1616. void lua_beginblock (lua_State *L);
  1617. void lua_endblock (lua_State *L);
  1618. \end{verbatim}
  1619. After the end of the block,
  1620. all \verb|lua_Object|s created inside it are released.
  1621. The \verb|lua_endblock| function also empties the C2Lua stack.
  1622. \subsection{Garbage Collection}\label{GC}
  1623. Because Lua has automatic memory management and garbage collection,
  1624. a \verb|lua_Object| has a limited scope,
  1625. and is only valid inside the \emph{block} where it has been created.
  1626. A C~function called from Lua is a block,
  1627. and its parameters are valid only until its end.
  1628. It is good programming practice to convert Lua objects to C values
  1629. as soon as they are available,
  1630. and never to store \verb|lua_Object|s in C global variables.
  1631. A garbage collection cycle can be forced by:
  1632. \Deffunc{lua_collectgarbage}
  1633. \begin{verbatim}
  1634. long lua_collectgarbage (lua_State *L, long limit);
  1635. \end{verbatim}
  1636. This function returns the number of objects collected.
  1637. The argument \verb|limit| makes the next cycle occur only
  1638. after that number of new objects have been created.
  1639. If \verb|limit| is 0,
  1640. then Lua uses an adaptive heuristic to set this limit.
  1641. \subsection{Userdata and Tags}\label{C-tags}
  1642. Because userdata are objects,
  1643. the function \verb|lua_pushusertag| may create a new userdata.
  1644. If Lua has a userdata with the given value (\verb|void*|) and tag,
  1645. then that userdata is pushed.
  1646. Otherwise, a new userdata is created, with the given value and tag.
  1647. If this function is called with
  1648. \verb|tag| equal to \verb|LUA_ANYTAG|\Deffunc{LUA_ANYTAG},
  1649. then Lua will try to find any userdata with the given value,
  1650. regardless of its tag.
  1651. If there is no userdata with that value, then a new one is created,
  1652. with tag equal to 0.
  1653. Userdata can have different tags,
  1654. whose semantics are only known to the host program.
  1655. Tags are created with the function
  1656. \Deffunc{lua_newtag}
  1657. \begin{verbatim}
  1658. int lua_newtag (lua_State *L);
  1659. \end{verbatim}
  1660. The function \verb|lua_settag| changes the tag of
  1661. the object on the top of C2lua (and pops it);
  1662. the object must be a userdata or a table:
  1663. \Deffunc{lua_settag}
  1664. \begin{verbatim}
  1665. void lua_settag (lua_State *L, int tag);
  1666. \end{verbatim}
  1667. The given \verb|tag| must be a value created with \verb|lua_newtag|.
  1668. \subsection{Executing Lua Code}
  1669. A host program can execute Lua chunks written in a file or in a string
  1670. using the following functions:%
  1671. \Deffunc{lua_dofile}\Deffunc{lua_dostring}\Deffunc{lua_dobuffer}
  1672. \begin{verbatim}
  1673. int lua_dofile (lua_State *L, const char *filename);
  1674. int lua_dostring (lua_State *L, const char *string);
  1675. int lua_dobuffer (lua_State *L, const char *buff,
  1676. size_t size, const char *name);
  1677. \end{verbatim}
  1678. All these functions return
  1679. 0, in case of success, or one of the following error codes:
  1680. \begin{itemize}
  1681. \item \verb|LUA_ERRRUN| ---
  1682. error while running the chunk.
  1683. \item \verb|LUA_ERRSYNTAX| ---
  1684. syntax error during pre-compilation.
  1685. \item \verb|LUA_ERRMEM| ---
  1686. memory allocation error;
  1687. for such errors, Lua does not call the \verb|LUA_ERRORMESSAGE| function.
  1688. \item \verb|LUA_ERRFILE| ---
  1689. error opening the file (only for \verb|lua_dofile|).
  1690. In this case,
  1691. you may want to
  1692. check \verb|errno|,
  1693. call \verb|strerror|,
  1694. or call \verb|perror| to tell the user what went wrong.
  1695. \end{itemize}
  1696. When called with argument \verb|NULL|,
  1697. \verb|lua_dofile| executes the \verb|stdin| stream.
  1698. Functions \verb|lua_dofile| and \verb|lua_dobuffer|
  1699. are both able to execute pre-compiled chunks.
  1700. They automatically detect whether the chunk is text or binary,
  1701. and load it accordingly (see program \IndexVerb{luac}).
  1702. Function \verb|lua_dostring| executes only source code,
  1703. given in textual form.
  1704. The third parameter to \verb|lua_dobuffer| (\verb|name|)
  1705. is the ``name of the chunk'',
  1706. used in error messages and debug information.
  1707. If \verb|name| is \verb|NULL|,
  1708. then Lua gives a default name to the chunk.
  1709. These functions return, in structure lua2C,
  1710. any values eventually returned by the chunks.
  1711. They also empty the stack C2lua.
  1712. \subsection{Manipulating Lua Objects}
  1713. To read the value of any global Lua variable,
  1714. one uses the function
  1715. \Deffunc{lua_getglobal}
  1716. \begin{verbatim}
  1717. lua_Object lua_getglobal (lua_State *L, const char *varname);
  1718. \end{verbatim}
  1719. As in Lua, this function may trigger a tag method
  1720. for the ``getglobal'' event.
  1721. To read the real value of a global variable,
  1722. without invoking any tag method,
  1723. use the \emph{lua_rawget} function over the table of globals.
  1724. To store a value previously pushed onto C2lua in a global variable,
  1725. there is the function
  1726. \Deffunc{lua_setglobal}
  1727. \begin{verbatim}
  1728. void lua_setglobal (lua_State *L, const char *varname);
  1729. \end{verbatim}
  1730. As in Lua, this function may trigger a tag method
  1731. for the ``setglobal'' event.
  1732. To set the real value of a global variable,
  1733. without invoking any tag method,
  1734. use the \emph{lua_rawset} function over the table of globals.
  1735. To get the table of globals,
  1736. you should call
  1737. \Deffunc{lua_pushglobals}
  1738. \begin{verbatim}
  1739. void lua_pushglobals (lua_State *L);
  1740. \end{verbatim}
  1741. To set another table as the table of globals,
  1742. you use
  1743. \Deffunc{lua_setglobals}
  1744. \begin{verbatim}
  1745. void lua_setglobals (lua_State *L, lua_Object newtable);
  1746. \end{verbatim}
  1747. Tables can also be manipulated via the API.
  1748. The function
  1749. \Deffunc{lua_gettable}
  1750. \begin{verbatim}
  1751. lua_Object lua_gettable (lua_State *L);
  1752. \end{verbatim}
  1753. pops a table and an index from the stack C2lua,
  1754. and returns the contents of the table at that index.
  1755. As in Lua, this operation may trigger a tag method
  1756. for the ``gettable'' event.
  1757. To get the real value of any table index,
  1758. without invoking any tag method,
  1759. use the \emph{raw} version:
  1760. \Deffunc{lua_rawget}
  1761. \begin{verbatim}
  1762. lua_Object lua_rawget (lua_State *L);
  1763. \end{verbatim}
  1764. To store a value in an index,
  1765. the program must push the table, the index, and the value onto C2lua
  1766. (in this order),
  1767. and then call the function
  1768. \Deffunc{lua_settable}
  1769. \begin{verbatim}
  1770. void lua_settable (lua_State *L);
  1771. \end{verbatim}
  1772. As in Lua, this operation may trigger a tag method
  1773. for the ``settable'' event.
  1774. To set the real value of any table index,
  1775. without invoking any tag method,
  1776. use the \emph{raw} version:
  1777. \Deffunc{lua_rawset}
  1778. \begin{verbatim}
  1779. void lua_rawset (lua_State *L);
  1780. \end{verbatim}
  1781. Finally, the function
  1782. \Deffunc{lua_createtable}
  1783. \begin{verbatim}
  1784. lua_Object lua_createtable (lua_State *L);
  1785. \end{verbatim}
  1786. creates and returns a new, empty table.
  1787. \subsection{Calling Lua Functions}
  1788. Functions defined in Lua by a chunk
  1789. can be called from the host program.
  1790. This is done using the following protocol:
  1791. first, the arguments to the function are pushed onto C2lua
  1792. \see{pushing}, in direct order, i.e., the first argument is pushed first.
  1793. Then, the function is called using
  1794. \Deffunc{lua_callfunction}
  1795. \begin{verbatim}
  1796. int lua_callfunction (lua_State *L, lua_Object function);
  1797. \end{verbatim}
  1798. This function returns the same error codes that \verb|lua_dostring|.
  1799. Finally, the results are returned in structure lua2C
  1800. (recall that a Lua function may return many values),
  1801. and can be retrieved with the macro \verb|lua_getresult|,
  1802. \Deffunc{lua_getresult}
  1803. which is just another name for the function \verb|lua_lua2C|.
  1804. Note that \verb|lua_callfunction|
  1805. pops all elements from the C2lua stack.
  1806. The following example shows how the host program may do the
  1807. equivalent to the Lua code:
  1808. \begin{verbatim}
  1809. a,b = f("how", t.x, 4)
  1810. \end{verbatim}
  1811. \begin{verbatim}
  1812. lua_pushstring(L, "how"); /* 1st argument */
  1813. lua_pushobject(L, lua_getglobal(L, "t")) /* push value of global 't' */
  1814. lua_pushstring(L, "x"); /* push the string 'x' */
  1815. lua_pushobject(L, lua_gettable(L)); /* push result of t.x (2nd arg) */
  1816. lua_pushnumber(L, 4); /* 3rd argument */
  1817. lua_callfunction(L, lua_getglobal(L, "f")); /* call `f' */
  1818. lua_pushobject(L, lua_getresult(L, 1)); /* push first result of the call */
  1819. lua_setglobal(L, "a"); /* set global variable 'a' */
  1820. lua_pushobject(L, lua_getresult(L, 2)); /* push second result of the call */
  1821. lua_setglobal(L, "b"); /* set global variable 'b' */
  1822. \end{verbatim}
  1823. Some special Lua functions have exclusive interfaces.
  1824. The host program can generate a Lua error calling the function
  1825. \Deffunc{lua_error}
  1826. \begin{verbatim}
  1827. void lua_error (lua_State *L, const char *message);
  1828. \end{verbatim}
  1829. This function never returns.
  1830. If \verb|lua_error| is called from a C~function that has been called from Lua,
  1831. then the corresponding Lua execution terminates,
  1832. as if an error had occurred inside Lua code.
  1833. Otherwise, the whole host program terminates with a call to \verb|exit(1)|.
  1834. Before terminating execution,
  1835. the \verb|message| is passed to the error handler function,
  1836. \verb|_ERRORMESSAGE| \see{error}.
  1837. If \verb|message| is \verb|NULL|,
  1838. then \verb|_ERRORMESSAGE| is not called.
  1839. Tag methods can be changed with: \Deffunc{lua_settagmethod}
  1840. \begin{verbatim}
  1841. lua_Object lua_settagmethod (lua_State *L, int tag, const char *event);
  1842. \end{verbatim}
  1843. The first parameter is the tag,
  1844. and the second is the event name \see{tag-method};
  1845. the new method is pushed from C2lua.
  1846. This function returns a \verb|lua_Object|,
  1847. which is the old tag method value.
  1848. To get just the current value of a tag method,
  1849. use the function \Deffunc{lua_gettagmethod}
  1850. \begin{verbatim}
  1851. lua_Object lua_gettagmethod (lua_State *L, int tag, const char *event);
  1852. \end{verbatim}
  1853. It is also possible to copy all tag methods from one tag
  1854. to another: \Deffunc{lua_copytagmethods}
  1855. \begin{verbatim}
  1856. int lua_copytagmethods (lua_State *L, int tagto, int tagfrom);
  1857. \end{verbatim}
  1858. This function returns \verb|tagto|.
  1859. You can traverse a table with the function \Deffunc{lua_next}
  1860. \begin{verbatim}
  1861. int lua_next (lua_State *L, lua_Object t, int i);
  1862. \end{verbatim}
  1863. Its first argument is the table to be traversed,
  1864. and the second is a \emph{cursor};
  1865. this cursor starts in 0,
  1866. and for each call the function returns a value to
  1867. be used in the next call,
  1868. or 0 to signal the end of the traversal.
  1869. The function also returns, in the Lua2C array,
  1870. a key-value pair from the table.
  1871. A typical traversal looks like the following code:
  1872. \begin{verbatim}
  1873. int i;
  1874. lua_Object t;
  1875. ... /* gets the table at `t' */
  1876. i = 0;
  1877. lua_beginblock(L);
  1878. while ((i = lua_next(L, t, i)) != 0) {
  1879. lua_Object key = lua_getresult(L, 1);
  1880. lua_Object value = lua_getresult(L, 2);
  1881. ... /* uses `key' and `value' */
  1882. lua_endblock(L);
  1883. lua_beginblock(L); /* reopens a block */
  1884. }
  1885. lua_endblock(L);
  1886. \end{verbatim}
  1887. The pairs of \verb|lua_beginblock|/\verb|lua_endblock| remove the
  1888. results of each iteration from the stack.
  1889. Without them, a traversal of a large table may overflow the stack.
  1890. \subsection{Defining C Functions} \label{LuacallC}
  1891. To register a C~function to Lua,
  1892. there is the following convenience macro:
  1893. \Deffunc{lua_register}
  1894. \begin{verbatim}
  1895. #define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n))
  1896. /* const char *n; */
  1897. /* lua_CFunction f; */
  1898. \end{verbatim}
  1899. which receives the name the function will have in Lua,
  1900. and a pointer to the function.
  1901. This pointer must have type \verb|lua_CFunction|,
  1902. which is defined as
  1903. \Deffunc{lua_CFunction}
  1904. \begin{verbatim}
  1905. typedef void (*lua_CFunction) (lua_State *L);
  1906. \end{verbatim}
  1907. that is, a pointer to a function with no results and a single argument,
  1908. a Lua environment.
  1909. In order to communicate properly with Lua,
  1910. a C~function must follow a protocol,
  1911. which defines the way parameters and results are passed.
  1912. A C~function receives its arguments in structure lua2C;
  1913. to access them, it uses the macro \verb|lua_getparam|, \Deffunc{lua_getparam}
  1914. again just another name for \verb|lua_lua2C|.
  1915. To return values, a C~function just pushes them onto the stack C2lua,
  1916. in direct order \see{valuesCLua}.
  1917. Like a Lua function, a C~function called by Lua can also return
  1918. many results.
  1919. When a C~function is created,
  1920. it is possible to associate some \emph{upvalues} to it
  1921. \see{upvalue},
  1922. thus creating a C closure;
  1923. these values are passed to the function whenever it is called,
  1924. as common arguments.
  1925. To associate upvalues to a C~function,
  1926. first these values must be pushed on C2lua.
  1927. Then the function \Deffunc{lua_pushcclosure}
  1928. \begin{verbatim}
  1929. void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
  1930. \end{verbatim}
  1931. is used to put the C~function on C2lua,
  1932. with the argument \verb|n| telling how many upvalues must be
  1933. associated with the function;
  1934. in fact, the macro \verb|lua_pushcfunction| is defined as
  1935. \verb|lua_pushcclosure| with \verb|n| set to 0.
  1936. Then, whenever the C~function is called,
  1937. these upvalues are inserted as the first arguments \M{n} to the function,
  1938. before the actual arguments provided in the call.
  1939. For some examples of C~functions, see files \verb|lstrlib.c|,
  1940. \verb|liolib.c| and \verb|lmathlib.c| in the official Lua distribution.
  1941. \subsection{References to Lua Objects}
  1942. As noted in \See{GC}, \verb|lua_Object|s are volatile.
  1943. If the C code needs to keep a \verb|lua_Object|
  1944. outside block boundaries,
  1945. then it must create a \Def{reference} to the object.
  1946. The routines to manipulate references are the following:
  1947. \Deffunc{lua_ref}\Deffunc{lua_getref}
  1948. \Deffunc{lua_unref}
  1949. \begin{verbatim}
  1950. int lua_ref (lua_State *L, int lock);
  1951. lua_Object lua_getref (lua_State *L, int ref);
  1952. void lua_unref (lua_State *L, int ref);
  1953. \end{verbatim}
  1954. The function \verb|lua_ref| creates a reference
  1955. to the object that is on the top of the stack,
  1956. and returns this reference.
  1957. For a \nil\ object,
  1958. the reference is always \verb|LUA_REFNIL|;\Deffunc{LUA_REFNIL}
  1959. otherwise, it is a non-negative integer.
  1960. The constant \verb|LUA_NOREF| \Deffunc{LUA_NOREF}
  1961. is different from any valid reference.
  1962. If \verb|lock| is true, then the object is \emph{locked}:
  1963. this means the object will not be garbage collected.
  1964. \emph{Unlocked references may be garbage collected}.
  1965. Whenever the referenced object is needed in~C,
  1966. a call to \verb|lua_getref|
  1967. returns a handle to it;
  1968. if the object has been collected,
  1969. \verb|lua_getref| returns \verb|LUA_NOOBJECT|.
  1970. When a reference is no longer needed,
  1971. it can be released with a call to \verb|lua_unref|.
  1972. \section{Predefined Functions and Libraries}
  1973. The set of \Index{predefined functions} in Lua is small but powerful.
  1974. Most of them provide features that allow some degree of
  1975. \Index{reflexivity} in the language.
  1976. Some of these features cannot be simulated with the rest of the
  1977. language nor with the standard Lua API.
  1978. Others are just convenient interfaces to common API functions.
  1979. The libraries, on the other hand, provide useful routines
  1980. that are implemented directly through the standard API.
  1981. Therefore, they are not necessary to the language,
  1982. and are provided as separate C modules.
  1983. Currently, there are three standard libraries:
  1984. \begin{itemize}
  1985. \item string manipulation;
  1986. \item mathematical functions (sin, log, etc);
  1987. \item input and output (plus some system facilities).
  1988. \end{itemize}
  1989. To have access to these libraries,
  1990. the C host program must call the functions
  1991. \verb|lua_strlibopen|, \verb|lua_mathlibopen|,
  1992. and \verb|lua_iolibopen|, declared in \verb|lualib.h|.
  1993. \Deffunc{lua_strlibopen}\Deffunc{lua_mathlibopen}\Deffunc{lua_iolibopen}
  1994. \subsection{Predefined Functions} \label{predefined}
  1995. \subsubsection*{\ff \T{_ALERT (message)}}\Deffunc{alert}\label{alert}
  1996. Prints its only string argument to \IndexVerb{stderr}.
  1997. All error messages in Lua are printed through the function stored
  1998. in the \verb|_ALERT| global variable
  1999. \see{error}.
  2000. Therefore, a program may assign another function to this variable
  2001. to change the way such messages are shown
  2002. (for instance, for systems without \verb|stderr|).
  2003. \subsubsection*{\ff \T{assert (v [, message])}}\Deffunc{assert}
  2004. Issues an \emph{``assertion failed!''} error
  2005. when its argument \verb|v| is \nil.
  2006. This function is equivalent to the following Lua function:
  2007. \begin{verbatim}
  2008. function assert (v, m)
  2009. if not v then
  2010. m = m or ""
  2011. error("assertion failed! " .. m)
  2012. end
  2013. end
  2014. \end{verbatim}
  2015. \subsubsection*{\ff \T{call (func, arg [, mode [, errhandler]])}}\Deffunc{call}
  2016. \label{pdf-call}
  2017. Calls function \verb|func| with
  2018. the arguments given by the table \verb|arg|.
  2019. The call is equivalent to
  2020. \begin{verbatim}
  2021. func(arg[1], arg[2], ..., arg[n])
  2022. \end{verbatim}
  2023. where \verb|n| is the result of \verb|getn(arg)| \see{getn}.
  2024. By default,
  2025. all results from \verb|func| are simply returned by \verb|call|.
  2026. If the string \verb|mode| contains \verb|"p"|,
  2027. then the results are \emph{packed} in a single table.\index{packed results}
  2028. That is, \verb|call| returns just one table;
  2029. at index \verb|n|, the table has the total number of results
  2030. from the call;
  2031. the first result is at index 1, etc.
  2032. For instance, the following calls produce the following results:
  2033. \begin{verbatim}
  2034. a = call(sin, {5}) --> a = 0.0871557 = sin(5)
  2035. a = call(max, {1,4,5; n=2}) --> a = 4 (only 1 and 4 are arguments)
  2036. a = call(max, {1,4,5; n=2}, "p") --> a = {4; n=1}
  2037. t = {x=1}
  2038. a = call(next, {t,nil;n=2}, "p") --> a={"x", 1; n=2}
  2039. \end{verbatim}
  2040. By default,
  2041. if an error occurs during the call to \verb|func|,
  2042. the error is propagated.
  2043. If the string \verb|mode| contains \verb|"x"|,
  2044. then the call is \emph{protected}.\index{protected calls}
  2045. In this mode, function \verb|call| does not propagate an error,
  2046. regardless of what happens during the call.
  2047. Instead, it returns \nil\ to signal the error
  2048. (besides calling the appropriated error handler).
  2049. If \verb|errhandler| is provided,
  2050. the error function \verb|_ERRORMESSAGE| is temporarily set to \verb|errhandler|,
  2051. while \verb|func| runs.
  2052. In particular, if \verb|errhandler| is \nil,
  2053. no error messages will be issued during the execution of the called function.
  2054. \subsubsection*{\ff \T{collectgarbage ([limit])}}\Deffunc{collectgarbage}
  2055. Forces a garbage collection cycle.
  2056. Returns the number of objects collected.
  2057. The optional argument \verb|limit| is a number that
  2058. makes the next cycle occur only after that number of new
  2059. objects have been created.
  2060. If \verb|limit| is absent or equal to 0,
  2061. then Lua uses an adaptive algorithm to set this limit.
  2062. \verb|collectgarbage| is equivalent to
  2063. the API function \verb|lua_collectgarbage|.
  2064. \subsubsection*{\ff \T{copytagmethods (tagto, tagfrom)}}
  2065. \Deffunc{copytagmethods}
  2066. Copies all tag methods from one tag to another;
  2067. it returns \verb|tagto|.
  2068. \subsubsection*{\ff \T{dofile (filename)}}\Deffunc{dofile}
  2069. Receives a file name,
  2070. opens the named file, and executes its contents as a Lua chunk,
  2071. or as pre-compiled chunks.
  2072. When called without arguments,
  2073. \verb|dofile| executes the contents of the standard input (\verb|stdin|).
  2074. If there is any error executing the file,
  2075. then \verb|dofile| returns \nil.
  2076. Otherwise, it returns the values returned by the chunk,
  2077. or a non-\nil\ value if the chunk returns no values.
  2078. It issues an error when called with a non-string argument.
  2079. \verb|dofile| is equivalent to the API function \verb|lua_dofile|.
  2080. \subsubsection*{\ff \T{dostring (string [, chunkname])}}\Deffunc{dostring}
  2081. Executes a given string as a Lua chunk.
  2082. If there is any error executing the string,
  2083. then \verb|dostring| returns \nil.
  2084. Otherwise, it returns the values returned by the chunk,
  2085. or a non-\nil\ value if the chunk returns no values.
  2086. The optional parameter \verb|chunkname|
  2087. is the ``name of the chunk'',
  2088. used in error messages and debug information.
  2089. \verb|dostring| is equivalent to the API function \verb|lua_dostring|.
  2090. \subsubsection*{\ff \T{error (message)}}\Deffunc{error}\label{pdf-error}
  2091. Calls the error handler \see{error} and then terminates
  2092. the last protected function called
  2093. (in~C: \verb|lua_dofile|, \verb|lua_dostring|,
  2094. \verb|lua_dobuffer|, or \verb|lua_callfunction|;
  2095. in Lua: \verb|dofile|, \verb|dostring|, or \verb|call| in protected mode).
  2096. If \verb|message| is \nil, then the error handler is not called.
  2097. Function \verb|error| never returns.
  2098. \verb|error| is equivalent to the API function \verb|lua_error|.
  2099. \subsubsection*{\ff \T{foreach (table, function)}}\Deffunc{foreach}
  2100. Executes the given \verb|function| over all elements of \verb|table|.
  2101. For each element, the function is called with the index and
  2102. respective value as arguments.
  2103. If the function returns any non-\nil\ value,
  2104. then the loop is broken, and this value is returned
  2105. as the final value of \verb|foreach|.
  2106. This function could be defined in Lua:
  2107. \begin{verbatim}
  2108. function foreach (t, f)
  2109. for i, v in t do
  2110. local res = f(i, v)
  2111. if res then return res end
  2112. end
  2113. end
  2114. \end{verbatim}
  2115. You may change the \emph{values} of existing
  2116. fields in the table during the traversal,
  2117. but if you create new indices,
  2118. the semantics of \verb|foreach| is undefined.
  2119. \subsubsection*{\ff \T{foreachi (table, function)}}\Deffunc{foreachi}
  2120. Executes the given \verb|function| over the
  2121. numerical indices of \verb|table|.
  2122. For each index, the function is called with the index and
  2123. respective value as arguments.
  2124. Indices are visited in sequential order,
  2125. from 1 to \verb|n|,
  2126. where \verb|n| is the result of \verb|getn(table)| \see{getn}.
  2127. If the function returns any non-\nil\ value,
  2128. then the loop is broken, and this value is returned
  2129. as the final value of \verb|foreachi|.
  2130. This function could be defined in Lua:
  2131. \begin{verbatim}
  2132. function foreachi (t, f)
  2133. for i=1,getn(t) do
  2134. local res = f(i, t[i])
  2135. if res then return res end
  2136. end
  2137. end
  2138. \end{verbatim}
  2139. You may change the \emph{values} of existing fields in the
  2140. table during the traversal,
  2141. but if you create new indices (even non-numeric),
  2142. the semantics of \verb|foreachi| is undefined.
  2143. \subsubsection*{\ff \T{foreachvar (function)}}\Deffunc{foreachvar}
  2144. This function is obsolete.
  2145. Use \verb|foreach(globals(), function)| instead.
  2146. \subsubsection*{\ff \T{getglobal (name)}}\Deffunc{getglobal}
  2147. Gets the value of a global variable,
  2148. or calls a tag method for ``getglobal''.
  2149. Its full semantics is explained in \See{tag-method}.
  2150. The string \verb|name| does not need to be a
  2151. syntactically valid variable name.
  2152. \subsubsection*{\ff \T{getn (table)}}\Deffunc{getn}\label{getn}
  2153. Returns the ``size'' of a table, when seen as a list.
  2154. If the table has an \verb|n| field with a numeric value,
  2155. this value is its ``size''.
  2156. Otherwise, the size is the largest numerical index with a non-nil
  2157. value in the table.
  2158. This function could be defined in Lua:
  2159. \begin{verbatim}
  2160. function getn (t)
  2161. if type(t.n) == 'number' then return t.n end
  2162. local max = 0
  2163. for i, _ in t do
  2164. if type(i) == 'number' and i>max then max=i end
  2165. end
  2166. return max
  2167. end
  2168. \end{verbatim}
  2169. \subsubsection*{\ff \T{gettagmethod (tag, event)}}
  2170. \Deffunc{gettagmethod}
  2171. Returns the current tag method
  2172. for a given pair \M{(tag, event)}.
  2173. \subsubsection*{\ff \T{globals ([newtable])}}\Deffunc{globals}
  2174. Returns the current table of globals.
  2175. If the argument \verb|newtable| is given,
  2176. set this table as the new table of globals.
  2177. \subsubsection*{\ff \T{newtag ()}}\Deffunc{newtag}\label{pdf-newtag}
  2178. Returns a new tag.
  2179. \verb|newtag| is equivalent to the API function \verb|lua_newtag|.
  2180. \subsubsection*{\ff \T{next (table, [index])}}\Deffunc{next}
  2181. Allows a program to traverse all fields of a table.
  2182. Its first argument is a table and its second argument
  2183. is an index in this table.
  2184. It returns the next index of the table and the
  2185. value associated with the index.
  2186. When called with \nil\ as its second argument,
  2187. \verb|next| returns the first index
  2188. of the table and its associated value.
  2189. When called with the last index,
  2190. or with \nil\ in an empty table,
  2191. it returns \nil.
  2192. If the second argument is absent, then it is interpreted as \nil.
  2193. Lua has no declaration of fields;
  2194. semantically, there is no difference between a
  2195. field not present in a table or a field with value \nil.
  2196. Therefore, \verb|next| only considers fields with non-\nil\ values.
  2197. The order in which the indices are enumerated is not specified,
  2198. \emph{even for numeric indices}
  2199. (to traverse a table in numeric order,
  2200. use a counter or the function \verb|foreachi|).
  2201. You may change the \emph{values} of existing fields in the
  2202. table during the traversal,
  2203. but if you create new indices,
  2204. the semantics of \verb|next| is undefined.
  2205. \subsubsection*{\ff \T{nextvar (name)}}\Deffunc{nextvar}
  2206. This function is obsolete.
  2207. Use \verb|next(globals(), name)| instead.
  2208. \subsubsection*{\ff \T{print (e1, e2, ...)}}\Deffunc{print}
  2209. Receives any number of arguments,
  2210. and prints their values using the strings returned by \verb|tostring|.
  2211. This function is not intended for formatted output,
  2212. but only as a quick way to show a value,
  2213. for instance for debugging.
  2214. See \See{libio} for functions for formatted output.
  2215. \subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal}
  2216. This function is obsolete.
  2217. Use \verb|rawget(globals(), name)| instead.
  2218. \subsubsection*{\ff \T{rawgettable (table, index)}}\Deffunc{rawgettable}
  2219. This function was renamed to \verb|rawget|.
  2220. \subsubsection*{\ff \T{rawget (table, index)}}\Deffunc{rawget}
  2221. Gets the real value of \verb|table[index]|,
  2222. without invoking any tag method.
  2223. \verb|table| must be a table,
  2224. and \verb|index| is any value different from \nil.
  2225. \subsubsection*{\ff \T{rawsetglobal (name, value)}}\Deffunc{rawsetglobal}
  2226. This function is obsolete.
  2227. Use \verb|rawset(globals(), name, value)| instead.
  2228. \subsubsection*{\ff \T{rawsettable (table, index, value)}}\Deffunc{rawsettable}
  2229. This function was renamed to \verb|rawset|.
  2230. \subsubsection*{\ff \T{rawset (table, index, value)}}\Deffunc{rawset}
  2231. Sets the real value of \verb|table[index]| to \verb|value|,
  2232. without invoking any tag method.
  2233. \verb|table| must be a table,
  2234. \verb|index| is any value different from \nil,
  2235. and \verb|value| is any Lua value.
  2236. \subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal}
  2237. Sets the named global variable to the given value,
  2238. or calls a tag method for ``setglobal''.
  2239. Its full semantics is explained in \See{tag-method}.
  2240. The string \verb|name| does not need to be a
  2241. syntactically valid variable name.
  2242. \subsubsection*{\ff \T{settag (t, tag)}}\Deffunc{settag}
  2243. Sets the tag of a given table \see{TypesSec}.
  2244. \verb|tag| must be a value created with \verb|newtag|
  2245. \see{pdf-newtag}.
  2246. It returns the value of its first argument (the table).
  2247. For the safety of host programs,
  2248. it is impossible to change the tag of a userdata from Lua.
  2249. \subsubsection*{\ff \T{settagmethod (tag, event, newmethod)}}
  2250. \Deffunc{settagmethod}
  2251. Sets a new tag method to the given pair \M{(tag, event)}.
  2252. It returns the old method.
  2253. If \verb|newmethod| is \nil,
  2254. then \verb|settagmethod| restores the default behavior for the given event.
  2255. \subsubsection*{\ff \T{sort (table [, comp])}}\Deffunc{sort}
  2256. Sorts table elements in a given order, \emph{in-place},
  2257. from \verb|table[1]| to \verb|table[n]|,
  2258. where \verb|n| is the result of \verb|getn(table)| \see{getn}.
  2259. If \verb|comp| is given,
  2260. it must be a function that receives two table elements,
  2261. and returns true when the first is less than the second
  2262. (so that \verb|not comp(a[i+1], a[i])| will be true after the sort).
  2263. If \verb|comp| is not given,
  2264. the standard Lua operator \verb|<| is used instead.
  2265. The sort algorithm is not stable
  2266. (that is, elements considered equal by the given order
  2267. may have their relative positions changed by the sort).
  2268. \subsubsection*{\ff \T{tag (v)}}\Deffunc{tag}\label{pdf-tag}
  2269. Allows Lua programs to test the tag of a value \see{TypesSec}.
  2270. It receives one argument, and returns its tag (a number).
  2271. \verb|tag| is equivalent to the API function \verb|lua_tag|.
  2272. \subsubsection*{\ff \T{tonumber (e [, base])}}\Deffunc{tonumber}
  2273. Receives one argument,
  2274. and tries to convert it to a number.
  2275. If the argument is already a number or a string convertible
  2276. to a number, then \verb|tonumber| returns that number;
  2277. otherwise, it returns \nil.
  2278. An optional argument specifies the base to interpret the numeral.
  2279. The base may be any integer between 2 and 36, inclusive.
  2280. In bases above~10, the letter `A' (either upper or lower case)
  2281. represents~10, `B' represents~11, and so forth, with `Z' representing 35.
  2282. In base 10 (the default), the number may have a decimal part,
  2283. as well as an optional exponent part \see{coercion}.
  2284. In other bases, only unsigned integers are accepted.
  2285. \subsubsection*{\ff \T{tostring (e)}}\Deffunc{tostring}
  2286. Receives an argument of any type and
  2287. converts it to a string in a reasonable format.
  2288. For complete control of how numbers are converted,
  2289. use function \verb|format|.
  2290. \subsubsection*{\ff \T{tinsert (table [, pos] , value)}}\Deffunc{tinsert}
  2291. Inserts element \verb|value| at table position \verb|pos|,
  2292. shifting other elements to open space, if necessary.
  2293. The default value for \verb|pos| is \verb|n+1|,
  2294. where \verb|n| is the result of \verb|getn(table)| \see{getn},
  2295. so that a call \verb|tinsert(t,x)| inserts \verb|x| at the end
  2296. of table \verb|t|.
  2297. This function also sets or increments the field \verb|n| of the table
  2298. to \verb|n+1|.
  2299. This function is equivalent to the following Lua function,
  2300. except that the table accesses are all \emph{raw} (that is, without tag methods):
  2301. \begin{verbatim}
  2302. function tinsert (t, ...)
  2303. local pos, value
  2304. local n = getn(t)
  2305. if arg.n == 1 then
  2306. pos, value = n+1, arg[1]
  2307. else
  2308. pos, value = arg[1], arg[2]
  2309. end
  2310. t.n = n+1;
  2311. for i=n,pos,-1 do
  2312. t[i+1] = t[i]
  2313. end
  2314. t[pos] = value
  2315. end
  2316. \end{verbatim}
  2317. \subsubsection*{\ff \T{tremove (table [, pos])}}\Deffunc{tremove}
  2318. Removes from \verb|table| the element at position \verb|pos|,
  2319. shifting other elements to close the space, if necessary.
  2320. Returns the value of the removed element.
  2321. The default value for \verb|pos| is \verb|n|,
  2322. where \verb|n| is the result of \verb|getn(table)| \see{getn},
  2323. so that a call \verb|tremove(t)| removes the last element
  2324. of table \verb|t|.
  2325. This function also sets or decrements the field \verb|n| of the table
  2326. to \verb|n-1|.
  2327. This function is equivalent to the following Lua function,
  2328. except that the table accesses are all \emph{raw} (that is, without tag methods):
  2329. \begin{verbatim}
  2330. function tremove (t, pos)
  2331. local n = getn(t)
  2332. if n<=0 then return end
  2333. pos = pos or n
  2334. local value = t[pos]
  2335. for i=pos,n-1 do
  2336. t[i] = t[i+1]
  2337. end
  2338. t[n] = nil
  2339. t.n = n-1
  2340. return value
  2341. end
  2342. \end{verbatim}
  2343. \subsubsection*{\ff \T{type (v)}}\Deffunc{type}\label{pdf-type}
  2344. Allows Lua programs to test the type of a value.
  2345. It receives one argument, and returns its type, coded as a string.
  2346. The possible results of this function are
  2347. \verb|"nil"| (a string, not the value \nil),
  2348. \verb|"number"|,
  2349. \verb|"string"|,
  2350. \verb|"table"|,
  2351. \verb|"function"|,
  2352. and \verb|"userdata"|.
  2353. \verb|type| is equivalent to the API function \verb|lua_type|.
  2354. \subsection{String Manipulation}
  2355. This library provides generic functions for string manipulation,
  2356. such as finding and extracting substrings and pattern matching.
  2357. When indexing a string, the first character is at position~1
  2358. (not at~0, as in C).
  2359. \subsubsection*{\ff \T{strbyte (s [, i])}}\Deffunc{strbyte}
  2360. Returns the internal numerical code of the character \verb|s[i]|.
  2361. If \verb|i| is absent, then it is assumed to be 1.
  2362. If \verb|i| is negative,
  2363. it is replaced by the length of the string minus its
  2364. absolute value plus 1.
  2365. Therefore, \Math{-1} points to the last character of \verb|s|.
  2366. \NOTE
  2367. \emph{numerical codes are not necessarily portable across platforms}.
  2368. \subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\Deffunc{strchar}
  2369. Receives 0 or more integers.
  2370. Returns a string with length equal to the number of arguments,
  2371. wherein each character has the internal numerical code equal
  2372. to its correspondent argument.
  2373. \NOTE
  2374. \emph{numerical codes are not necessarily portable across platforms}.
  2375. \subsubsection*{\ff \T{strfind (str, pattern [, init [, plain]])}}
  2376. \Deffunc{strfind}
  2377. Looks for the first \emph{match} of
  2378. \verb|pattern| in \verb|str|.
  2379. If it finds one, then it returns the indices of \verb|str|
  2380. where this occurrence starts and ends;
  2381. otherwise, it returns \nil.
  2382. If the pattern specifies captures (see \verb|gsub| below),
  2383. the captured strings are returned as extra results.
  2384. A third optional numerical argument specifies where to start the search;
  2385. its default value is 1.
  2386. If \verb|init| is negative,
  2387. it is replaced by the length of the string minus its
  2388. absolute value plus 1.
  2389. Therefore, \Math{-1} points to the last character of \verb|str|.
  2390. A value of 1 as a fourth optional argument
  2391. turns off the pattern matching facilities,
  2392. so the function does a plain ``find substring'' operation,
  2393. with no characters in \verb|pattern| being considered ``magic''.
  2394. \subsubsection*{\ff \T{strlen (s)}}\Deffunc{strlen}
  2395. Receives a string and returns its length.
  2396. The empty string \verb|""| has length 0.
  2397. Embedded zeros are counted.
  2398. \subsubsection*{\ff \T{strlower (s)}}\Deffunc{strlower}
  2399. Receives a string and returns a copy of that string with all
  2400. upper case letters changed to lower case.
  2401. All other characters are left unchanged.
  2402. The definition of what is an upper-case
  2403. letter depends on the current locale.
  2404. \subsubsection*{\ff \T{strrep (s, n)}}\Deffunc{strrep}
  2405. Returns a string that is the concatenation of \verb|n| copies of
  2406. the string \verb|s|.
  2407. \subsubsection*{\ff \T{strsub (s, i [, j])}}\Deffunc{strsub}
  2408. Returns another string, which is a substring of \verb|s|,
  2409. starting at \verb|i| and running until \verb|j|.
  2410. If \verb|i| or \verb|j| are negative,
  2411. they are replaced by the length of the string minus their
  2412. absolute value plus 1.
  2413. Therefore, \Math{-1} points to the last character of \verb|s|
  2414. and \Math{-2} to the previous one.
  2415. If \verb|j| is absent, it is assumed to be equal to \Math{-1}
  2416. (which is the same as the string length).
  2417. In particular,
  2418. the call \verb|strsub(s,1,j)| returns a prefix of \verb|s|
  2419. with length \verb|j|,
  2420. and the call \verb|strsub(s, -i)| returns a suffix of \verb|s|
  2421. with length \verb|i|.
  2422. \subsubsection*{\ff \T{strupper (s)}}\Deffunc{strupper}
  2423. Receives a string and returns a copy of that string with all
  2424. lower case letters changed to upper case.
  2425. All other characters are left unchanged.
  2426. The definition of what is a lower case
  2427. letter depends on the current locale.
  2428. \subsubsection*{\ff \T{format (formatstring, e1, e2, \ldots)}}\Deffunc{format}
  2429. \label{format}
  2430. Returns a formatted version of its variable number of arguments
  2431. following the description given in its first argument (which must be a string).
  2432. The format string follows the same rules as the \verb|printf| family of
  2433. standard C~functions.
  2434. The only differences are that the options/modifiers
  2435. \verb|*|, \verb|l|, \verb|L|, \verb|n|, \verb|p|,
  2436. and \verb|h| are not supported,
  2437. and there is an extra option, \verb|q|.
  2438. The \verb|q| option formats a string in a form suitable to be safely read
  2439. back by the Lua interpreter:
  2440. The string is written between double quotes,
  2441. and all double quotes, returns, and backslashes in the string
  2442. are correctly escaped when written.
  2443. For instance, the call
  2444. \begin{verbatim}
  2445. format('%q', 'a string with "quotes" and \n new line')
  2446. \end{verbatim}
  2447. will produce the string:
  2448. \begin{verbatim}
  2449. "a string with \"quotes\" and \
  2450. new line"
  2451. \end{verbatim}
  2452. Conversions can be applied to the \M{n}-th argument in the argument list,
  2453. rather than the next unused argument.
  2454. In this case, the conversion character \verb|%| is replaced
  2455. by the sequence \verb|%d$|, where \verb|d| is a
  2456. decimal digit in the range [1,9],
  2457. giving the position of the argument in the argument list.
  2458. For instance, the call \verb|format("%2$d -> %1$03d", 1, 34)| will
  2459. result in \verb|"34 -> 001"|.
  2460. The same argument can be used in more than one conversion.
  2461. The options \verb|c|, \verb|d|, \verb|E|, \verb|e|, \verb|f|,
  2462. \verb|g|, \verb|G|, \verb|i|, \verb|o|, \verb|u|, \verb|X|, and \verb|x| all
  2463. expect a number as argument,
  2464. whereas \verb|q| and \verb|s| expect a string.
  2465. The \verb|*| modifier can be simulated by building
  2466. the appropriate format string.
  2467. For example, \verb|"%*g"| can be simulated with
  2468. \verb|"%"..width.."g"|.
  2469. \NOTE
  2470. \emph{Neither the format string nor the string values to be formatted with
  2471. \T{format} can contain embedded zeros.}
  2472. \subsubsection*{\ff \T{gsub (s, pat, repl [, n])}}
  2473. \Deffunc{gsub}
  2474. Returns a copy of \verb|s|,
  2475. in which all occurrences of the pattern \verb|pat| have been
  2476. replaced by a replacement string specified by \verb|repl|.
  2477. This function also returns, as a second value,
  2478. the total number of substitutions made.
  2479. If \verb|repl| is a string, then its value is used for replacement.
  2480. Any sequence in \verb|repl| of the form \verb|%n|
  2481. with \verb|n| between 1 and 9
  2482. stands for the value of the \M{n}-th captured substring.
  2483. If \verb|repl| is a function, then this function is called every time a
  2484. match occurs, with all captured substrings passed as arguments,
  2485. in order (see below).
  2486. If the value returned by this function is a string,
  2487. then it is used as the replacement string;
  2488. otherwise, the replacement string is the empty string.
  2489. The last, optional parameter \verb|n| limits
  2490. the maximum number of substitutions to occur.
  2491. For instance, when \verb|n| is 1 only the first occurrence of
  2492. \verb|pat| is replaced.
  2493. Here are some examples:
  2494. \begin{verbatim}
  2495. x = gsub("hello world", "(%w+)", "%1 %1")
  2496. --> x="hello hello world world"
  2497. x = gsub("hello world", "(%w+)", "%1 %1", 1)
  2498. --> x="hello hello world"
  2499. x = gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
  2500. --> x="world hello Lua from"
  2501. x = gsub("home = $HOME, user = $USER", "%$(%w+)", getenv)
  2502. --> x="home = /home/roberto, user = roberto" (for instance)
  2503. x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring)
  2504. --> x="4+5 = 9"
  2505. local t = {name="lua", version="4.0"}
  2506. x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end)
  2507. --> x="lua - 4.0"
  2508. t = {n=0}
  2509. gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end)
  2510. --> t={"first", "second", "word"; n=3}
  2511. \end{verbatim}
  2512. \subsubsection*{Patterns} \label{pm}
  2513. \paragraph{Character Class:}
  2514. a \Def{character class} is used to represent a set of characters.
  2515. The following combinations are allowed in describing a character class:
  2516. \begin{description}
  2517. \item[\emph{x}] (where \emph{x} is any character not in the list
  2518. \verb|^$()%.[]*+-?|)
  2519. --- represents the character \emph{x} itself.
  2520. \item[\T{.}] --- (a dot) represents all characters.
  2521. \item[\T{\%a}] --- represents all letters.
  2522. \item[\T{\%c}] --- represents all control characters.
  2523. \item[\T{\%d}] --- represents all digits.
  2524. \item[\T{\%l}] --- represents all lower case letters.
  2525. \item[\T{\%p}] --- represents all punctuation characters.
  2526. \item[\T{\%s}] --- represents all space characters.
  2527. \item[\T{\%u}] --- represents all upper case letters.
  2528. \item[\T{\%w}] --- represents all alphanumeric characters.
  2529. \item[\T{\%x}] --- represents all hexadecimal digits.
  2530. \item[\T{\%z}] --- represents the character with representation 0.
  2531. \item[\T{\%\M{x}}] (where \M{x} is any non-alphanumeric character) ---
  2532. represents the character \M{x}.
  2533. This is the standard way to escape the magic characters \verb|()%.[]*+-?|.
  2534. We recommend that any ``punct'' character (even the non magic)
  2535. should be preceded by a \verb|%|
  2536. when used to represent itself in a pattern.
  2537. \item[\T{[char-set]}] ---
  2538. represents the class which is the union of all
  2539. characters in char-set.
  2540. A range of characters may be specified by
  2541. separating the end characters of the range with a \verb|-|.
  2542. All classes \verb|%|\emph{x} described above may also be used as
  2543. components in a char-set.
  2544. All other characters in char-set represent themselves.
  2545. For example, \verb|[%w_]| (or \verb|[_%w]|)
  2546. represents all alphanumeric characters plus the underscore,
  2547. \verb|[0-7]| represents the octal digits,
  2548. and \verb|[0-7%l%-]| represents the octal digits plus
  2549. the lower case letters plus the \verb|-| character.
  2550. The interaction between ranges and classes is not defined.
  2551. Therefore, patterns like \verb|[%a-z]| or \verb|[a-%%]|
  2552. have no meaning.
  2553. \item[\T{[\^{ }char-set]}] ---
  2554. represents the complement of char-set,
  2555. where char-set is interpreted as above.
  2556. \end{description}
  2557. For all classes represented by single letters (\verb|%a|, \verb|%c|, \ldots),
  2558. the corresponding upper-case letter represents the complement of the class.
  2559. For instance, \verb|%S| represents all non-space characters.
  2560. The definitions of letter, space, etc. depend on the current locale.
  2561. In particular, the class \verb|[a-z]| may not be equivalent to \verb|%l|.
  2562. The second form should be preferred for portability.
  2563. \paragraph{Pattern Item:}
  2564. a \Def{pattern item} may be
  2565. \begin{itemize}
  2566. \item
  2567. a single character class,
  2568. which matches any single character in the class;
  2569. \item
  2570. a single character class followed by \verb|*|,
  2571. which matches 0 or more repetitions of characters in the class.
  2572. These repetition items will always match the longest possible sequence;
  2573. \item
  2574. a single character class followed by \verb|+|,
  2575. which matches 1 or more repetitions of characters in the class.
  2576. These repetition items will always match the longest possible sequence;
  2577. \item
  2578. a single character class followed by \verb|-|,
  2579. which also matches 0 or more repetitions of characters in the class.
  2580. Unlike \verb|*|,
  2581. these repetition items will always match the shortest possible sequence;
  2582. \item
  2583. a single character class followed by \verb|?|,
  2584. which matches 0 or 1 occurrence of a character in the class;
  2585. \item
  2586. \T{\%\M{n}}, for \M{n} between 1 and 9;
  2587. such item matches a sub-string equal to the \M{n}-th captured string
  2588. (see below);
  2589. \item
  2590. \T{\%b\M{xy}}, where \M{x} and \M{y} are two distinct characters;
  2591. such item matches strings that start with~\M{x}, end with~\M{y},
  2592. and where the \M{x} and \M{y} are \emph{balanced}.
  2593. This means that, if one reads the string from left to right,
  2594. counting \Math{+1} for an \M{x} and \Math{-1} for a \M{y},
  2595. the ending \M{y} is the first where the count reaches 0.
  2596. For instance, the item \verb|%b()| matches expressions with
  2597. balanced parentheses.
  2598. \end{itemize}
  2599. \paragraph{Pattern:}
  2600. a \Def{pattern} is a sequence of pattern items.
  2601. A \verb|^| at the beginning of a pattern anchors the match at the
  2602. beginning of the subject string.
  2603. A \verb|$| at the end of a pattern anchors the match at the
  2604. end of the subject string.
  2605. At other positions,
  2606. \verb|^| and \verb|$| have no special meaning and represent themselves.
  2607. \paragraph{Captures:}
  2608. A pattern may contain sub-patterns enclosed in parentheses,
  2609. that describe \Def{captures}.
  2610. When a match succeeds, the sub-strings of the subject string
  2611. that match captures are stored (\emph{captured}) for future use.
  2612. Captures are numbered according to their left parentheses.
  2613. For instance, in the pattern \verb|"(a*(.)%w(%s*))"|,
  2614. the part of the string matching \verb|"a*(.)%w(%s*)"| is
  2615. stored as the first capture (and therefore has number~1);
  2616. the character matching \verb|.| is captured with number~2,
  2617. and the part matching \verb|%s*| has number~3.
  2618. \NOTE
  2619. {\em A pattern cannot contain embedded zeros.
  2620. Use \verb|%z| instead.}
  2621. \subsection{Mathematical Functions} \label{mathlib}
  2622. This library is an interface to some functions of the standard C math library.
  2623. In addition, it registers a tag method for the binary operator \verb|^| that
  2624. returns \Math{x^y} when applied to numbers \verb|x^y|.
  2625. The library provides the following functions:
  2626. \Deffunc{abs}\Deffunc{acos}\Deffunc{asin}\Deffunc{atan}
  2627. \Deffunc{atan2}\Deffunc{ceil}\Deffunc{cos}\Deffunc{floor}
  2628. \Deffunc{log}\Deffunc{log10}\Deffunc{max}\Deffunc{min}
  2629. \Deffunc{mod}\Deffunc{sin}\Deffunc{sqrt}\Deffunc{tan}
  2630. \Deffunc{frexp}\Deffunc{ldexp}
  2631. \Deffunc{random}\Deffunc{randomseed}
  2632. \begin{verbatim}
  2633. abs acos asin atan atan2 ceil cos deg floor log log10
  2634. max min mod rad sin sqrt tan frexp ldexp
  2635. random randomseed
  2636. \end{verbatim}
  2637. plus a global variable \IndexVerb{PI}.
  2638. Most of them
  2639. are only interfaces to the homonymous functions in the C~library,
  2640. except that, for the trigonometric functions,
  2641. all angles are expressed in \emph{degrees}, not radians.
  2642. Functions \IndexVerb{deg} and \IndexVerb{rad} can be used to convert
  2643. between radians and degrees.
  2644. The function \verb|max| returns the maximum
  2645. value of its numeric arguments.
  2646. Similarly, \verb|min| computes the minimum.
  2647. Both can be used with 1, 2, or more arguments.
  2648. The functions \verb|random| and \verb|randomseed| are interfaces to
  2649. the simple random generator functions \verb|rand| and \verb|srand|,
  2650. provided by ANSI C.
  2651. (No guarantees can be given for their statistical properties.)
  2652. The function \verb|random|, when called without arguments,
  2653. returns a pseudo-random real number in the range \Math{[0,1)}.
  2654. When called with a number \Math{n},
  2655. \verb|random| returns a pseudo-random integer in the range \Math{[1,n]}.
  2656. When called with two arguments, \Math{l} and \Math{u},
  2657. \verb|random| returns a pseudo-random integer in the range \Math{[l,u]}.
  2658. \subsection{I/O Facilities} \label{libio}
  2659. All input and output operations in Lua are done, by default,
  2660. over two \Def{file handles}, one for reading and one for writing.
  2661. These handles are stored in two Lua global variables,
  2662. called \verb|_INPUT| and \verb|_OUTPUT|.
  2663. The global variables
  2664. \verb|_STDIN|, \verb|_STDOUT|, and \verb|_STDERR|
  2665. are initialized with file descriptors for
  2666. \verb|stdin|, \verb|stdout| and \verb|stderr|.
  2667. Initially, \verb|_INPUT=_STDIN| and \verb|_OUTPUT=_STDOUT|.
  2668. \Deffunc{_INPUT}\Deffunc{_OUTPUT}
  2669. \Deffunc{_STDIN}\Deffunc{_STDOUT}\Deffunc{_STDERR}
  2670. A file handle is a userdata containing the file stream \verb|FILE*|,
  2671. and with a distinctive tag created by the I/O library.
  2672. Unless otherwise stated,
  2673. all I/O functions return \nil\ on failure and
  2674. some value different from \nil\ on success.
  2675. \subsubsection*{\ff \T{openfile (filename, mode)}}\Deffunc{openfile}
  2676. This function opens a file,
  2677. in the mode specified in the string \verb|mode|.
  2678. It returns a new file handle,
  2679. or, in case of errors, \nil\ plus a string describing the error.
  2680. This function does not modify either \verb|_INPUT| or \verb|_OUTPUT|.
  2681. The \verb|mode| string can be any of the following:
  2682. \begin{description}
  2683. \item[``r''] read mode;
  2684. \item[``w''] write mode;
  2685. \item[``a''] append mode;
  2686. \item[``r+''] update mode, all previous data is preserved;
  2687. \item[``w+''] update mode, all previous data is erased;
  2688. \item[``a+''] append update mode, previous data is preserved,
  2689. writing is only allowed at the end of file.
  2690. \end{description}
  2691. The \verb|mode| string may also have a \verb|b| at the end,
  2692. which is needed in some systems to open the file in binary mode.
  2693. This string is exactlty what is used in the standard~C function \verb|fopen|.
  2694. \subsubsection*{\ff \T{closefile (handle)}}\Deffunc{closefile}
  2695. This function closes the given file.
  2696. It does not modify either \verb|_INPUT| or \verb|_OUTPUT|.
  2697. \subsubsection*{\ff \T{readfrom (filename)}}\Deffunc{readfrom}
  2698. This function may be called in two ways.
  2699. When called with a file name, it opens the named file,
  2700. sets its handle as the value of \verb|_INPUT|,
  2701. and returns this value.
  2702. It does not close the current input file.
  2703. When called without parameters,
  2704. it closes the \verb|_INPUT| file,
  2705. and restores \verb|stdin| as the value of \verb|_INPUT|.
  2706. If this function fails, it returns \nil,
  2707. plus a string describing the error.
  2708. \begin{quotation}
  2709. \noindent
  2710. \emph{System dependent}: if \verb|filename| starts with a \verb-|-,
  2711. then a \Index{piped input} is opened, via function \IndexVerb{popen}.
  2712. Not all systems implement pipes.
  2713. Moreover,
  2714. the number of files that can be open at the same time is
  2715. usually limited and depends on the system.
  2716. \end{quotation}
  2717. \subsubsection*{\ff \T{writeto (filename)}}\Deffunc{writeto}
  2718. This function may be called in two ways.
  2719. When called with a file name,
  2720. it opens the named file,
  2721. sets its handle as the value of \verb|_OUTPUT|,
  2722. and returns this value.
  2723. It does not close the current output file.
  2724. Note that, if the file already exists,
  2725. then it will be \emph{completely erased} with this operation.
  2726. When called without parameters,
  2727. this function closes the \verb|_OUTPUT| file,
  2728. and restores \verb|stdout| as the value of \verb|_OUTPUT|.
  2729. \index{closing a file}
  2730. If this function fails, it returns \nil,
  2731. plus a string describing the error.
  2732. \begin{quotation}
  2733. \noindent
  2734. \emph{System dependent}: if \verb|filename| starts with a \verb-|-,
  2735. then a \Index{piped output} is opened, via function \IndexVerb{popen}.
  2736. Not all systems implement pipes.
  2737. Moreover,
  2738. the number of files that can be open at the same time is
  2739. usually limited and depends on the system.
  2740. \end{quotation}
  2741. \subsubsection*{\ff \T{appendto (filename)}}\Deffunc{appendto}
  2742. Opens a file named \verb|filename| and sets it as the
  2743. value of \verb|_OUTPUT|.
  2744. Unlike the \verb|writeto| operation,
  2745. this function does not erase any previous contents of the file;
  2746. instead, anything written to the file is appended to its end.
  2747. If this function fails, it returns \nil,
  2748. plus a string describing the error.
  2749. \subsubsection*{\ff \T{remove (filename)}}\Deffunc{remove}
  2750. Deletes the file with the given name.
  2751. If this function fails, it returns \nil,
  2752. plus a string describing the error.
  2753. \subsubsection*{\ff \T{rename (name1, name2)}}\Deffunc{rename}
  2754. Renames file named \verb|name1| to \verb|name2|.
  2755. If this function fails, it returns \nil,
  2756. plus a string describing the error.
  2757. \subsubsection*{\ff \T{flush ([filehandle])}}\Deffunc{flush}
  2758. Saves any written data to the given file.
  2759. If \verb|filehandle| is not specified,
  2760. then \verb|flush| flushes all open files.
  2761. If this function fails, it returns \nil,
  2762. plus a string describing the error.
  2763. \subsubsection*{\ff \T{seek (filehandle [, whence] [, offset])}}\Deffunc{seek}
  2764. Sets and gets the file position,
  2765. measured in bytes from the beginning of the file,
  2766. to the position given by \verb|offset| plus a base
  2767. specified by the string \verb|whence|, as follows:
  2768. \begin{description}
  2769. \item[``set''] base is position 0 (beginning of the file);
  2770. \item[``cur''] base is current position;
  2771. \item[``end''] base is end of file;
  2772. \end{description}
  2773. In case of success, function \verb|seek| returns the final file position,
  2774. measured in bytes from the beginning of the file.
  2775. If the call fails, it returns \nil,
  2776. plus a string describing the error.
  2777. The default value for \verb|whence| is \verb|"cur"|,
  2778. and for \verb|offset| is 0.
  2779. Therefore, the call \verb|seek(file)| returns the current
  2780. file position, without changing it;
  2781. the call \verb|seek(file, "set")| sets the position to the
  2782. beginning of the file (and returns 0);
  2783. and the call \verb|seek(file, "end")| sets the position to the
  2784. end of the file, and returns its size.
  2785. \subsubsection*{\ff \T{tmpname ()}}\Deffunc{tmpname}
  2786. Returns a string with a file name that can safely
  2787. be used for a temporary file.
  2788. The file must be explicitly opened before its use
  2789. and removed when no longer needed.
  2790. \subsubsection*{\ff \T{read ([filehandle,] format1, ...)}}\Deffunc{read}
  2791. Reads file \verb|_INPUT|,
  2792. or \verb|filehandle| if this argument is given,
  2793. according to the given formats, which specify what to read.
  2794. For each format,
  2795. the function returns a string (or a number) with the characters read,
  2796. or \nil\ if it cannot read data with the specified format.
  2797. When called without formats,
  2798. it uses a default format that reads the next line
  2799. (see below).
  2800. The available formats are
  2801. \begin{description}
  2802. \item[``*n''] reads a number;
  2803. this is the only format that returns a number instead of a string.
  2804. \item[``*l''] reads the next line
  2805. (skipping the end of line), or \nil\ on end of file.
  2806. This is the default format.
  2807. \item[``*a''] reads the whole file, starting at the current position.
  2808. On end of file, it returns the empty string.
  2809. \item[``*w''] reads the next word
  2810. (maximal sequence of non--white-space characters),
  2811. skipping spaces if necessary, or \nil\ on end of file.
  2812. \item[\emph{number}] reads a string with up to that number of characters,
  2813. or \nil\ on end of file.
  2814. \end{description}
  2815. \subsubsection*{\ff \T{write ([filehandle, ] value1, ...)}}\Deffunc{write}
  2816. Writes the value of each of its arguments to
  2817. file \verb|_OUTPUT|,
  2818. or to \verb|filehandle| if this argument is given.
  2819. The arguments must be strings or numbers.
  2820. To write other values,
  2821. use \verb|tostring| or \verb|format| before \verb|write|.
  2822. If this function fails, it returns \nil,
  2823. plus a string describing the error.
  2824. \subsubsection*{\ff \T{date ([format])}}\Deffunc{date}
  2825. Returns a string containing date and time
  2826. formatted according to the given string \verb|format|,
  2827. following the same rules of the ANSI~C function \verb|strftime|.
  2828. When called without arguments,
  2829. it returns a reasonable date and time representation that depends on
  2830. the host system and on the current locale.
  2831. \subsubsection*{\ff \T{clock ()}}\Deffunc{clock}
  2832. Returns an approximation of the amount of CPU time
  2833. used by the program, in seconds.
  2834. \subsubsection*{\ff \T{exit ([code])}}\Deffunc{exit}
  2835. Calls the C~function \verb|exit|,
  2836. with an optional \verb|code|,
  2837. to terminate the program.
  2838. The default value for \verb|code| is the success code.
  2839. \subsubsection*{\ff \T{getenv (varname)}}\Deffunc{getenv}
  2840. Returns the value of the process environment variable \verb|varname|,
  2841. or \nil\ if the variable is not defined.
  2842. \subsubsection*{\ff \T{execute (command)}}\Deffunc{execute}
  2843. This function is equivalent to the C~function \verb|system|.
  2844. It passes \verb|command| to be executed by an operating system shell.
  2845. It returns a status code, which is system-dependent.
  2846. \subsubsection*{\ff \T{setlocale (locale [, category])}}\Deffunc{setlocale}
  2847. This function is an interface to the ANSI~C function \verb|setlocale|.
  2848. \verb|locale| is a string specifying a locale;
  2849. \verb|category| is an optional string describing which category to change:
  2850. \verb|"all"|, \verb|"collate"|, \verb|"ctype"|,
  2851. \verb|"monetary"|, \verb|"numeric"|, or \verb|"time"|;
  2852. the default category is \verb|"all"|.
  2853. The function returns the name of the new locale,
  2854. or \nil\ if the request cannot be honored.
  2855. \section{The Debug Interface} \label{debugI}
  2856. Lua has no built-in debugging facilities.
  2857. Instead, it offers a special interface,
  2858. by means of functions and \emph{hooks},
  2859. which allows the construction of different
  2860. kinds of debuggers, profilers, and other tools
  2861. that need ``inside information'' from the interpreter.
  2862. This interface is declared in the header file \verb|luadebug.h|,
  2863. and has \emph{no} single-state variant.
  2864. \subsection{Stack and Function Information}
  2865. \Deffunc{lua_getstack}
  2866. The main function to get information about the interpreter stack is
  2867. \begin{verbatim}
  2868. int lua_getstack (lua_State *L, int level, lua_Debug *ar);
  2869. \end{verbatim}
  2870. It fills parts of a \verb|lua_Debug| structure with
  2871. an identification of the \emph{activation record}
  2872. of the function executing at a given level.
  2873. Level~0 is the current running function,
  2874. whereas level \Math{n+1} is the function that has called level \Math{n}.
  2875. Usually, \verb|lua_getstack| returns 1;
  2876. when called with a level greater than the stack depth,
  2877. it returns 0.
  2878. \Deffunc{lua_Debug}
  2879. The structure \verb|lua_Debug| is used to carry different pieces of information
  2880. about an active function:
  2881. \begin{verbatim}
  2882. struct lua_Debug {
  2883. const char *event; /* "call", "return" */
  2884. const char *source; /* (S) */
  2885. int linedefined; /* (S) */
  2886. const char *what; /* (S) "Lua" function, "C" function, Lua "main" */
  2887. int currentline; /* (l) */
  2888. const char *name; /* (n) */
  2889. const char *namewhat; /* (n) global, tag method, local, field */
  2890. int nups; /* (u) number of upvalues */
  2891. lua_Object func; /* (f) function being executed */
  2892. /* private part */
  2893. ...
  2894. };
  2895. \end{verbatim}
  2896. The \verb|lua_getstack| function fills only the private part
  2897. of this structure, for future use.
  2898. To fill in the other fields of \verb|lua_Debug| with useful information,
  2899. call \Deffunc{lua_getinfo}
  2900. \begin{verbatim}
  2901. int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
  2902. \end{verbatim}
  2903. This function returns 0 on error
  2904. (e.g., an invalid option in \verb|what|).
  2905. Each character in the string \verb|what|
  2906. selects some fields of \verb|ar| to be filled,
  2907. as indicated by the letter in parentheses in the definition of \verb|lua_Debug|;
  2908. that is, an \verb|S| fills the fields \verb|source| and \verb|linedefined|,
  2909. and \verb|l| fills the field \verb|currentline|, etc.
  2910. To get information about a function that is not active (that is,
  2911. it is not in the stack),
  2912. you set the \verb|func| field of the \verb|lua_Debug| structure
  2913. with the function,
  2914. and start the \verb|what| string with the character \verb|>|.
  2915. For instance, to know in which line a function \verb|f| was defined,
  2916. you can write
  2917. \begin{verbatim}
  2918. lua_Debug ar;
  2919. ar.func = lua_getglobal(L, "f");
  2920. lua_getinfo(L, ">S", &ar);
  2921. printf("%d\n", ar.linedefined);
  2922. \end{verbatim}
  2923. The fields of \verb|lua_Debug| have the following meaning:
  2924. \begin{description}
  2925. \item[source]
  2926. If the function was defined in a string,
  2927. \verb|source| is that string;
  2928. if the function was defined in a file,
  2929. \verb|source| starts with a \verb|@| followed by the file name.
  2930. \item[linedefined]
  2931. the line number where starts the definition of the function.
  2932. \item[what] the string \verb|"Lua"| if this is a Lua function,
  2933. \verb|"C"| if this is a C~function,
  2934. or \verb|"main"| if this is the main part of a chunk.
  2935. \item[currentline]
  2936. the current line where the given function is executing.
  2937. When no line information is available,
  2938. \verb|currentline| is set to \Math{-1}.
  2939. \item[name]
  2940. a reasonable name for the given function.
  2941. Because functions in Lua are first class values,
  2942. they do not have a fixed name:
  2943. Some functions may be the value of many global variables,
  2944. while others may be stored only in a table field.
  2945. The \verb|lua_getinfo| function checks whether the given
  2946. function is a tag method or the value of a global variable.
  2947. If the given function is a tag method,
  2948. then \verb|name| points to the event name.
  2949. If the given function is the value of a global variable,
  2950. then \verb|name| points to the variable name.
  2951. If the given function is neither a tag method nor a global variable,
  2952. then \verb|name| is set to \verb|NULL|.
  2953. \item[namewhat]
  2954. Explains the previous field.
  2955. If the function is a global variable,
  2956. \verb|namewhat| is \verb|"global"|;
  2957. if the function is a tag method,
  2958. \verb|namewhat| is \verb|"tag-method"|;
  2959. otherwise \verb|namewhat| is \verb|""| (the empty string).
  2960. \item[nups]
  2961. Number of upvalues of a C~function.
  2962. If the function is not a C~function,
  2963. \verb|nups| is set to 0.
  2964. \item[func]
  2965. The function being executed, as a \verb|lua_Object|.
  2966. \end{description}
  2967. \subsection{Manipulating Local Variables}
  2968. For the manipulation of local variables,
  2969. \verb|luadebug.h| defines the following record:
  2970. \begin{verbatim}
  2971. struct lua_Localvar {
  2972. int index;
  2973. const char *name;
  2974. lua_Object value;
  2975. };
  2976. \end{verbatim}
  2977. where \verb|index| is an index for local variables
  2978. (the first parameter has index 1, and so on,
  2979. until the last active local variable).
  2980. \Deffunc{lua_getlocal}\Deffunc{lua_setlocal}
  2981. The following functions allow the manipulation of the
  2982. local variables of a given activation record.
  2983. \begin{verbatim}
  2984. int lua_getlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v);
  2985. int lua_setlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v);
  2986. \end{verbatim}
  2987. The parameter \verb|ar| must be a valid activation record,
  2988. filled by a previous call to \verb|lua_getstack| or
  2989. given as argument to a hook \see{sub-hooks}.
  2990. To use \verb|lua_getlocal|,
  2991. you fill the \verb|index| field of \verb|v| with the index
  2992. of a local variable; then the function fills the fields
  2993. \verb|name| and \verb|value| with the name and the current
  2994. value of that variable.
  2995. For \verb|lua_setlocal|,
  2996. you fill the \verb|index| and the \verb|value| fields of \verb|v|,
  2997. and the function assigns that value to the variable.
  2998. Both functions return 0 on failure, that happens
  2999. if the index is greater than the number of active local variables.
  3000. As an example, the following function lists the names of all
  3001. local variables for a function in a given level of the stack:
  3002. \begin{verbatim}
  3003. int listvars (lua_State *L, int level) {
  3004. lua_Debug ar;
  3005. int i;
  3006. if (lua_getstack(L, level, &ar) == 0)
  3007. return 0; /* failure: no such level on the stack */
  3008. for (i=1; ; i++) {
  3009. lua_Localvar v;
  3010. v.index = i;
  3011. if (lua_getlocal(L, &ar, &v) == 0)
  3012. return 1; /* no more locals */
  3013. printf("%s\n", v.name);
  3014. }
  3015. }
  3016. \end{verbatim}
  3017. \subsection{Hooks}\label{sub-hooks}
  3018. The Lua interpreter offers two hooks for debugging purposes:
  3019. a \emph{call} hook and a \emph{line} hook.
  3020. Both have the same type,
  3021. \begin{verbatim}
  3022. typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
  3023. \end{verbatim}
  3024. and you can set them with the following functions:
  3025. \Deffunc{lua_Hook}\Deffunc{lua_setcallhook}\Deffunc{lua_setlinehook}
  3026. \begin{verbatim}
  3027. lua_Hook lua_setcallhook (lua_State *L, lua_Hook func);
  3028. lua_Hook lua_setlinehook (lua_State *L, lua_Hook func);
  3029. \end{verbatim}
  3030. A hook is disabled when its value is \verb|NULL|,
  3031. which is the initial value of both hooks.
  3032. The functions \verb|lua_setcallhook| and \verb|lua_setlinehook|
  3033. set their corresponding hooks and return their previous values.
  3034. The call hook is called whenever the
  3035. interpreter enters or leaves a function.
  3036. The \verb|event| field of \verb|ar| has the strings \verb|"call"|
  3037. or \verb|"return"|.
  3038. This \verb|ar| can then be used in calls to \verb|lua_getinfo|,
  3039. \verb|lua_getlocal|, and \verb|lua_setlocal|,
  3040. to get more information about the function and to manipulate its
  3041. local variables.
  3042. The line hook is called every time the interpreter changes
  3043. the line of code it is executing.
  3044. The \verb|event| field of \verb|ar| has the string \verb|"line"|,
  3045. and the \verb|currentline| field has the line number.
  3046. Again, you can use this \verb|ar| in other calls to the debug API.
  3047. While Lua is running a hook, it disables other calls to hooks.
  3048. Therefore, if a hook calls Lua to execute a function or a chunk,
  3049. this execution ocurrs without any calls to hooks.
  3050. A hook cannot call \T{lua_error}.
  3051. It must return to Lua through a regular return.
  3052. (There is no problem if the error is inside a chunk or a Lua function
  3053. called by the hook, because those errors are protected;
  3054. the control returns to the hook anyway.)
  3055. \subsection{The Reflexive Debug Interface}
  3056. The library \verb|ldblib| provides
  3057. the functionality of the debug interface to Lua programs.
  3058. If you want to use this library,
  3059. your host application must open it,
  3060. by calling \verb|lua_dblibopen|.
  3061. You should exert great care when using this library.
  3062. The functions provided here should be used exclusively for debugging
  3063. and similar tasks (e.g., profiling).
  3064. Please resist the temptation to use them as a
  3065. usual programming tool.
  3066. They are slow and violate some (otherwise) secure aspects of the
  3067. language (e.g., privacy of local variables).
  3068. As a general rule, if your program does not need this library,
  3069. do not open it.
  3070. \subsubsection*{\ff \T{getinfo (function, [what])}}\Deffunc{getinfo}
  3071. This function returns a table with information about a function.
  3072. You can give the function directly,
  3073. or you can give a number as the value of \verb|function|,
  3074. which means the function running at level \verb|function| of the stack:
  3075. Level 0 is the current function (\verb|getinfo| itself);
  3076. level 1 is the function that called \verb|getinfo|;
  3077. and so on.
  3078. If \verb|function| is a number larger than the number of active functions,
  3079. \verb|getinfo| returns \nil.
  3080. The returned table contains all the fields returned by \verb|lua_getinfo|,
  3081. with the string \verb|what| describing what to get.
  3082. The default for \verb|what| is to get all information available.
  3083. For instance, the expression \verb|getinfo(1,"n").name| returns
  3084. the name of the current function, if a reasonable name can be found,
  3085. and \verb|getinfo(print)| returns a table with all available information
  3086. about the \verb|print| function.
  3087. \subsubsection*{\ff \T{getlocal (level, local)}}\Deffunc{getlocal}
  3088. This function returns the name and the value of the local variable
  3089. with index \verb|local| of the function at level \verb|level| of the stack.
  3090. (The first parameter has index 1, and so on,
  3091. until the last active local variable.)
  3092. The function returns \nil\ if there is no local
  3093. variable with the given index,
  3094. and raises an error when called with a \verb|level| out of range.
  3095. (You can call \verb|getstack| to check wheter the level is valid.)
  3096. \subsubsection*{\ff \T{setlocal (level, local, value)}}\Deffunc{setlocal}
  3097. This function assigns the value \verb|value| to the local variable
  3098. with index \verb|local| of the function at level \verb|level| of the stack.
  3099. The function returns \nil\ if there is no local
  3100. variable with the given index,
  3101. and raises an error when called with a \verb|level| out of range.
  3102. \subsubsection*{\ff \T{setcallhook (hook)}}\Deffunc{setcallhook}
  3103. Sets the function \verb|hook| as the call hook;
  3104. this hook will be called every time the interpreter starts and
  3105. exits the execution of a function.
  3106. The only argument to this hook is the event name (\verb|"call"| or
  3107. \verb|"return"|).
  3108. You can call \verb|getstack| with level 2 to get more information about
  3109. the function being called or returning
  3110. (level 0 is the \verb|getstack| function,
  3111. and level 1 is the hook function).
  3112. When called without arguments,
  3113. this function turns off call hooks.
  3114. \subsubsection*{\ff \T{setlinehook (hook)}}\Deffunc{setlinehook}
  3115. Sets the function \verb|hook| as the line hook;
  3116. this hook will be called every time the interpreter changes
  3117. the line of code it is executing.
  3118. The only argument to the hook is the line number the interpreter
  3119. is about to execute.
  3120. When called without arguments,
  3121. this function turns off line hooks.
  3122. \section{\Index{Lua Stand-alone}} \label{lua-sa}
  3123. Although Lua has been designed as an extension language,
  3124. the language is frequently used as a stand-alone interpreter.
  3125. An implementation of such an interpreter,
  3126. called simply \verb|lua|,
  3127. is provided with the standard distribution.
  3128. This program can be called with any sequence of the following arguments:
  3129. \begin{description}
  3130. \item[\T{-}] executes \verb|stdin| as a file;
  3131. \item[\T{-c}] calls \verb|lua_close| after running all arguments;
  3132. \item[\T{-e} \rm\emph{stat}] executes string \verb|stat|;
  3133. \item[\T{-f filename}] executes file \verb|filename| with the
  3134. remaining arguments in table \verb|arg|;
  3135. \item[\T{-i}] enters interactive mode with prompt;
  3136. \item[\T{-q}] enters interactive mode without prompt;
  3137. \item[\T{-v}] prints version information;
  3138. \item[\T{var=value}] sets global \verb|var| to string \verb|"value"|;
  3139. \item[\T{filename}] executes file \verb|filename|.
  3140. \end{description}
  3141. When called without arguments,
  3142. Lua behaves as \verb|lua -v -i| when \verb|stdin| is a terminal,
  3143. and as \verb|lua -| otherwise.
  3144. All arguments are handled in order.
  3145. For instance, an invocation like
  3146. \begin{verbatim}
  3147. $ lua -i a=test prog.lua
  3148. \end{verbatim}
  3149. will first interact with the user until an \verb|EOF| in \verb|stdin|,
  3150. then will set \verb|a| to \verb|"test"|,
  3151. and finally will run the file \verb|prog.lua|.
  3152. When the option \T{-f filename} is used,
  3153. all following arguments from the command line
  3154. are passed to the Lua program in a table called \verb|arg|.
  3155. The field \verb|n| gets the index of the last argument,
  3156. and the field 0 gets the \T{filename}.
  3157. For instance, in the call
  3158. \begin{verbatim}
  3159. $ lua a.lua -f b.lua t1 t3
  3160. \end{verbatim}
  3161. the interpreter first runs the file \T{a.lua},
  3162. then creates a table \T{arg},
  3163. \begin{verbatim}
  3164. arg = {"t1", "t3"; n = 2, [0] = "b.lua"}
  3165. \end{verbatim}
  3166. and then runs the file \T{b.lua}.
  3167. The stand-alone interpreter also provides a \verb|getargs| function that
  3168. can be used to access \emph{all} command line arguments.
  3169. For instance, if you call Lua with the line
  3170. \begin{verbatim}
  3171. > lua -d a b
  3172. \end{verbatim}
  3173. and the file \verb|a| (or \verb|b|) calls \verb|getargs|,
  3174. the call will return the table
  3175. \verb|{[0] = "lua", [1] = "-d", [2] = "a", [3] = "b", n = 3}|.
  3176. \Deffunc{getargs}
  3177. In interactive mode,
  3178. a multi-line statement can be written finishing intermediate
  3179. lines with a backslash (\verb|\|).
  3180. If the global variable \verb|_PROMPT| is defined as a string,
  3181. its value is used as the prompt. \index{_PROMPT}
  3182. Therefore, the prompt can be changed like below:
  3183. \begin{verbatim}
  3184. $ lua _PROMPT='myprompt> ' -i
  3185. \end{verbatim}
  3186. In Unix systems, Lua scripts can be made into executable programs
  3187. by using \verb|chmod +x| and the~\verb|#!| form,
  3188. as in \verb|#!/usr/local/bin/lua|,
  3189. or \verb|#!/usr/local/bin/lua -f| to get other arguments.
  3190. \section*{Acknowledgments}
  3191. The authors would like to thank CENPES/PETROBRAS which,
  3192. jointly with \tecgraf, used early versions of
  3193. this system extensively and gave valuable comments.
  3194. The authors would also like to thank Carlos Henrique Levy,
  3195. who found the name of the game.
  3196. Lua means ``moon'' in Portuguese.
  3197. \appendix
  3198. \section*{Incompatibilities with Previous Versions}
  3199. Although great care has been taken to avoid incompatibilities with
  3200. the previous public versions of Lua,
  3201. some differences had to be introduced.
  3202. Here is a list of all these incompatibilities.
  3203. \subsection*{Incompatibilities with \Index{version 3.2}}
  3204. \begin{itemize}
  3205. \item
  3206. General read patterns are now deprecated.
  3207. \item
  3208. Garbage-collection tag methods for tables is now deprecated.
  3209. \item
  3210. \verb|setglobal|, \verb|rawsetglobal|, and \verb|sort| no longer return a value;
  3211. \verb|type| no longer return a second value.
  3212. \item
  3213. In nested function calls like \verb|f(g(x))|
  3214. \emph{all} return values from \verb|g| are passed as arguments to \verb|f|.
  3215. (This only happens when \verb|g| is the last
  3216. [or the only] argument to \verb|f|.)
  3217. \item
  3218. There is now only one tag method for order operators.
  3219. \item
  3220. The debug API has been completely rewritten.
  3221. \item
  3222. The pre-compiler may use the fact that some operators are associative,
  3223. for optimizations.
  3224. This may cause problems if these operators
  3225. have non-associative tag methods.
  3226. \item
  3227. All functions from the old API are now macros.
  3228. \item
  3229. A \verb|const| qualifier has been added to \verb|char *|
  3230. in all API functions that handle C~strings.
  3231. \item
  3232. \verb|luaL_openlib| no longer automatically calls \verb|lua_open|.
  3233. So,
  3234. you must now explicitly call \verb|lua_open| before opening
  3235. the standard libraries.
  3236. \item
  3237. \verb|lua_type| now returns a string describing the type,
  3238. and is no longer a synonym for \verb|lua_tag|.
  3239. \item Old pre-compiled code is obsolete, and must be re-compiled.
  3240. \end{itemize}
  3241. %{===============================================================
  3242. \section*{The complete syntax of Lua}
  3243. \renewenvironment{Produc}{\vspace{0.8ex}\par\noindent\hspace{3ex}\it\begin{tabular}{rrl}}{\end{tabular}\vspace{0.8ex}\par\noindent}
  3244. \renewcommand{\OrNL}{\\ & \Or & }
  3245. \begin{Produc}
  3246. \produc{chunk}{\rep{stat} \opt{\ter{;}}}
  3247. \produc{block}{chunk}
  3248. \produc{stat}{%
  3249. varlist1 \ter{=} explist1
  3250. \OrNL functioncall
  3251. \OrNL \rwd{do} block \rwd{end}
  3252. \OrNL \rwd{while} exp1 \rwd{do} block \rwd{end}
  3253. \OrNL \rwd{repeat} block \rwd{until} exp1
  3254. \OrNL \rwd{if} exp1 \rwd{then} block
  3255. \rep{\rwd{elseif} exp1 \rwd{then} block}
  3256. \opt{\rwd{else} block} \rwd{end}
  3257. \OrNL \rwd{return} \opt{explist1}
  3258. \OrNL \rwd{break}
  3259. \OrNL \rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1}
  3260. \rwd{do} block \rwd{end}
  3261. \OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end}
  3262. \OrNL \rwd{local} declist \opt{init}
  3263. }
  3264. \produc{var}{%
  3265. name
  3266. \OrNL varorfunc \ter{[} exp1 \ter{]}
  3267. \OrNL varorfunc \ter{.} name
  3268. }
  3269. \produc{varorfunc}{var \Or functioncall}
  3270. \produc{varlist1}{var \rep{\ter{,} var}}
  3271. \produc{declist}{name \rep{\ter{,} name}}
  3272. \produc{init}{\ter{=} explist1}
  3273. \produc{exp}{%
  3274. \rwd{nil}
  3275. \Or number
  3276. \Or literal
  3277. \Or function
  3278. \Or upvalue
  3279. \Or functioncall
  3280. \Or tableconstructor
  3281. \Or \ter{(} exp \ter{)}
  3282. \Or exp binop exp
  3283. \Or unop exp
  3284. }
  3285. \produc{exp1}{exp}
  3286. \produc{explist1}{\rep{exp1 \ter{,}} exp}
  3287. \produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}}
  3288. \produc{fieldlist}{%
  3289. lfieldlist
  3290. \Or ffieldlist
  3291. \Or lfieldlist \ter{;} ffieldlist
  3292. \Or ffieldlist \ter{;} lfieldlist
  3293. }
  3294. \produc{lfieldlist}{\opt{lfieldlist1}}
  3295. \produc{ffieldlist}{\opt{ffieldlist1}}
  3296. \produc{lfieldlist1}{exp \rep{\ter{,} exp} \opt{\ter{,}}}
  3297. \produc{ffieldlist1}{ffield \rep{\ter{,} ffield} \opt{\ter{,}}}
  3298. \produc{ffield}{%
  3299. \ter{[} exp \ter{]} \ter{=} exp
  3300. \Or name \ter{=} exp
  3301. }
  3302. \produc{functioncall}{%
  3303. varorfunc args
  3304. \Or varorfunc \ter{:} name args
  3305. }
  3306. \produc{args}{%
  3307. \ter{(} \opt{explist1} \ter{)}
  3308. \Or tableconstructor
  3309. \Or \ter{literal}
  3310. }
  3311. \produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)} block \rwd{end}}
  3312. \produc{funcname}{%
  3313. name
  3314. \OrNL name \ter{.} name
  3315. \OrNL name \ter{:} name
  3316. }
  3317. \produc{parlist1}{%
  3318. \ter{\ldots}
  3319. \Or name \rep{\ter{,} name} \opt{\ter{,} \ter{\ldots}}
  3320. }
  3321. \produc{upvalue}{\ter{\%} name}
  3322. \end{Produc}
  3323. %}===============================================================
  3324. % restore underscore to usual meaning
  3325. \catcode`\_=8
  3326. \newcommand{\indexentry}[2]{\item {#1} #2}
  3327. \begin{theindex}
  3328. \input{manual.id}
  3329. \end{theindex}
  3330. \end{document}