manual.tex 146 KB

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