manual.tex 153 KB

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