luaref.txt 224 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897
  1. *luaref.txt* Nvim
  2. *luaref* *Lua-Reference*
  3. LUA REFERENCE MANUAL
  4. Version 0.3.0
  5. August 7th, 2022
  6. Vimdoc version (c) 2006 by Luis Carvalho
  7. <lexcarvalho at gmail dot com>
  8. Adapted from "Lua: 5.1 reference manual"
  9. R. Ierusalimschy, L. H. de Figueiredo, W. Celes
  10. Copyright (c) 2006 Lua.org, PUC-Rio.
  11. See |luaref-doc| for information on this manual.
  12. See |luaref-copyright| for copyright and licenses.
  13. Type |gO| to see the table of contents.
  14. ==============================================================================
  15. 1 INTRODUCTION *luaref-intro*
  16. Lua is an extension programming language designed to support general
  17. procedural programming with data description facilities. It also offers good
  18. support for object-oriented programming, functional programming, and
  19. data-driven programming. Lua is intended to be used as a powerful,
  20. light-weight scripting language for any program that needs one. Lua is
  21. implemented as a library, written in clean C (that is, in the common subset of
  22. ANSI C and C++).
  23. Being an extension language, Lua has no notion of a "main" program: it only
  24. works embedded in a host client, called the embedding program or simply the
  25. host. This host program can invoke functions to execute a piece of Lua code,
  26. can write and read Lua variables, and can register C functions to be called by
  27. Lua code. Through the use of C functions, Lua can be augmented to cope with a
  28. wide range of different domains, thus creating customized programming
  29. languages sharing a syntactical framework.
  30. Lua is free software, and is provided as usual with no guarantees, as stated
  31. in its license. The implementation described in this manual is available at
  32. Lua's official web site, www.lua.org.
  33. Like any other reference manual, this document is dry in places. For a
  34. discussion of the decisions behind the design of Lua, see references at
  35. |luaref-bibliography|. For a detailed introduction to programming in Lua, see
  36. Roberto's book, Programming in Lua.
  37. Lua means "moon" in Portuguese and is pronounced LOO-ah.
  38. ==============================================================================
  39. 2 THE LANGUAGE *luaref-language*
  40. This section describes the lexis, the syntax, and the semantics of Lua. In
  41. other words, this section describes which tokens are valid, how they can be
  42. combined, and what their combinations mean.
  43. The language constructs will be explained using the usual extended BNF
  44. notation, in which `{ a }` means 0 or more `a`'s, and `[ a ]` means an optional `a`.
  45. ==============================================================================
  46. 2.1 Lexical Conventions *luaref-langLexConv*
  47. *luaref-names* *luaref-identifiers*
  48. Names (also called identifiers) in Lua can be any string of letters, digits,
  49. and underscores, not beginning with a digit. This coincides with the
  50. definition of identifiers in most languages. (The definition of letter depends
  51. on the current locale: any character considered alphabetic by the current
  52. locale can be used in an identifier.) Identifiers are used to name variables
  53. and table fields.
  54. The following keywords are reserved and cannot be used as names:
  55. >
  56. and break do else elseif
  57. end false for function if
  58. in local nil not or
  59. repeat return then true until while
  60. <
  61. Lua is a case-sensitive language: `and` is a reserved word, but `And` and `AND` are
  62. two different, valid names. As a convention, names starting with an underscore
  63. followed by uppercase letters (such as `_VERSION`) are reserved for internal
  64. global variables used by Lua.
  65. The following strings denote other tokens:
  66. >
  67. + - * / % ^ #
  68. == ~= <= >= < > =
  69. ( ) { } [ ]
  70. ; : , . .. ...
  71. <
  72. *luaref-literal*
  73. Literal strings can be delimited by matching single or double quotes, and can
  74. contain the following C-like escape sequences:
  75. - `\a` bell
  76. - `\b` backspace
  77. - `\f` form feed
  78. - `\n` newline
  79. - `\r` carriage return
  80. - `\t` horizontal tab
  81. - `\v` vertical tab
  82. - `\\` backslash
  83. - `\"` quotation mark (double quote)
  84. - `\'` apostrophe (single quote)
  85. Moreover, a backslash followed by a real newline results in a newline in the
  86. string. A character in a string may also be specified by its numerical value
  87. using the escape sequence `\ddd`, where `ddd` is a sequence of up to three
  88. decimal digits. (Note that if a numerical escape is to be followed by a digit,
  89. it must be expressed using exactly three digits.) Strings in Lua may contain
  90. any 8-bit value, including embedded zeros, which can be specified as `\0`.
  91. To put a double (single) quote, a newline, a backslash, or an embedded zero
  92. inside a literal string enclosed by double (single) quotes you must use an
  93. escape sequence. Any other character may be directly inserted into the
  94. literal. (Some control characters may cause problems for the file system, but
  95. Lua has no problem with them.)
  96. Literal strings can also be defined using a long format enclosed by long
  97. brackets. We define an opening long bracket of level n as an opening square
  98. bracket followed by n equal signs followed by another opening square bracket.
  99. So, an opening long bracket of level 0 is written as `[[`, an opening long
  100. bracket of level 1 is written as `[=[`, and so on.
  101. A closing long bracket is defined similarly; for instance, a closing long
  102. bracket of level 4 is written as `]====]`. A long string starts with an
  103. opening long bracket of any level and ends at the first closing long bracket
  104. of the same level. Literals in this bracketed form may run for several lines,
  105. do not interpret any escape sequences, and ignore long brackets of any other
  106. level. They may contain anything except a closing bracket of the proper level.
  107. For convenience, when the opening long bracket is immediately followed by a
  108. newline, the newline is not included in the string. As an example, in a system
  109. using ASCII (in which `a` is coded as 97, newline is coded as 10, and `1` is
  110. coded as 49), the five literals below denote the same string:
  111. >
  112. a = 'alo\n123"'
  113. a = "alo\n123\""
  114. a = '\97lo\10\04923"'
  115. a = [[alo
  116. 123"]]
  117. a = [==[
  118. alo
  119. 123"]==]
  120. <
  121. *luaref-numconstant*
  122. A numerical constant may be written with an optional decimal part and an
  123. optional decimal exponent. Lua also accepts integer hexadecimal constants, by
  124. prefixing them with `0x`. Examples of valid numerical constants are
  125. >
  126. 3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56
  127. <
  128. *luaref-comment*
  129. A comment starts with a double hyphen (`--`) anywhere outside a string. If the
  130. text immediately after `--` is not an opening long bracket, the comment is a
  131. short comment, which runs until the end of the line. Otherwise, it is a long
  132. comment, which runs until the corresponding closing long bracket. Long
  133. comments are frequently used to disable code temporarily.
  134. ==============================================================================
  135. 2.2 Values and Types *luaref-langValTypes*
  136. Lua is a dynamically typed language. This means that variables do not have
  137. types; only values do. There are no type definitions in the language. All
  138. values carry their own type.
  139. All values in Lua are first-class values. This means that all values can be
  140. stored in variables, passed as arguments to other functions, and returned as
  141. results.
  142. *luaref-types* *luaref-nil*
  143. *luaref-true* *luaref-false*
  144. *luaref-number* *luaref-string*
  145. There are eight basic types in Lua: `nil`, `boolean`, `number`, `string`,
  146. `function`, `userdata`, `thread`, and `table`. Nil is the type of the value
  147. `nil`, whose main property is to be different from any other value; it usually
  148. represents the absence of a useful value. Boolean is the type of the values
  149. `false` and `true`. Both `nil` and `false` make a condition false; any other
  150. value makes it true. Number represents real (double-precision floating-point)
  151. numbers. (It is easy to build Lua interpreters that use other internal
  152. representations for numbers, such as single-precision float or long integers;
  153. see file `luaconf.h`.) String represents arrays of characters. Lua is 8-bit
  154. clean: strings may contain any 8-bit character, including embedded zeros
  155. (`\0`) (see |luaref-literal|).
  156. Lua can call (and manipulate) functions written in Lua and functions written
  157. in C (see |luaref-langFuncCalls|).
  158. *luaref-userdatatype*
  159. The type userdata is provided to allow arbitrary C data to be stored in Lua
  160. variables. This type corresponds to a block of raw memory and has no
  161. pre-defined operations in Lua, except assignment and identity test. However,
  162. by using metatables, the programmer can define operations for userdata values
  163. (see |luaref-langMetatables|). Userdata values cannot be created or modified
  164. in Lua, only through the C API. This guarantees the integrity of data owned by
  165. the host program.
  166. *luaref-thread*
  167. The type `thread` represents independent threads of execution and it is used to
  168. implement coroutines (see |luaref-langCoro|). Do not confuse Lua threads with
  169. operating-system threads. Lua supports coroutines on all systems, even those
  170. that do not support threads.
  171. *luaref-table*
  172. The type `table` implements associative arrays, that is, arrays that can be
  173. indexed not only with numbers, but with any value (except `nil`). Tables can
  174. be heterogeneous; that is, they can contain values of all types (except
  175. `nil`). Tables are the sole data structuring mechanism in Lua; they may be
  176. used to represent ordinary arrays, symbol tables, sets, records, graphs,
  177. trees, etc. To represent records, Lua uses the field name as an index. The
  178. language supports this representation by providing `a.name` as syntactic sugar
  179. for `a["name"]`. There are several convenient ways to create tables in Lua
  180. (see |luaref-langTableConst|).
  181. Like indices, the value of a table field can be of any type (except `nil`). In
  182. particular, because functions are first-class values, table fields may contain
  183. functions. Thus tables may also carry methods (see |luaref-langFuncDefs|).
  184. Tables, functions, threads and (full) userdata values are objects: variables
  185. do not actually contain these values, only references to them. Assignment,
  186. parameter passing, and function returns always manipulate references to such
  187. values; these operations do not imply any kind of copy.
  188. The library function `type` returns a string describing the type of a given
  189. value (see |luaref-type()|).
  190. ------------------------------------------------------------------------------
  191. 2.2.1 Coercion *luaref-langCoercion*
  192. Lua provides automatic conversion between string and number values at run
  193. time. Any arithmetic operation applied to a string tries to convert that
  194. string to a number, following the usual conversion rules. Conversely, whenever
  195. a number is used where a string is expected, the number is converted to a
  196. string, in a reasonable format. For complete control of how numbers are
  197. converted to strings, use the `format` function from the string library (see
  198. |string.format()|).
  199. ==============================================================================
  200. 2.3 Variables *luaref-langVariables*
  201. Variables are places that store values. There are three kinds of variables in
  202. Lua: global variables, local variables, and table fields.
  203. A single name can denote a global variable or a local variable (or a
  204. function's formal parameter, which is a particular form of local variable):
  205. >
  206. var ::= Name
  207. <
  208. Name denotes identifiers, as defined in |luaref-langLexConv|.
  209. Any variable is assumed to be global unless explicitly declared as a local
  210. (see |luaref-langLocalDec|). Local variables are lexically scoped: local
  211. variables can be freely accessed by functions defined inside their scope (see
  212. |luaref-langVisibRules|).
  213. Before the first assignment to a variable, its value is `nil`.
  214. Square brackets are used to index a table:
  215. >
  216. var ::= prefixexp [ exp ]
  217. <
  218. The first expression (`prefixexp`) should result in a table value; the second
  219. expression (`exp`) identifies a specific entry inside that table. The
  220. expression denoting the table to be indexed has a restricted syntax; see
  221. |luaref-langExpressions| for details.
  222. The syntax `var.NAME` is just syntactic sugar for `var["NAME"]` :
  223. >
  224. var ::= prefixexp . Name
  225. <
  226. All global variables live as fields in ordinary Lua tables, called environment
  227. tables or simply environments (see |luaref-langEnvironments|). Each function
  228. has its own reference to an environment, so that all global variables in this
  229. function will refer to this environment table. When a function is created, it
  230. inherits the environment from the function that created it. To get the
  231. environment table of a Lua function, you call `getfenv` (see
  232. |lua_getfenv()|). To replace it, you call `setfenv` (see |luaref-setfenv()|).
  233. (You can only manipulate the environment of C functions through the debug
  234. library; see |luaref-libDebug|.)
  235. An access to a global variable `x` is equivalent to `_env.x`, which in turn is
  236. equivalent to
  237. >
  238. gettable_event(_env, "x")
  239. <
  240. where `_env` is the environment of the running function. (The `_env` variable is
  241. not defined in Lua. We use it here only for explanatory purposes.)
  242. The meaning of accesses to global variables and table fields can be changed
  243. via metatables. An access to an indexed variable `t[i]` is equivalent to a
  244. call `gettable_event(t,i)`. (See |luaref-langMetatables| for a complete
  245. description of the `gettable_event` function. This function is not defined or
  246. callable in Lua. We use it here only for explanatory purposes.)
  247. ==============================================================================
  248. 2.4 Statements *luaref-langStats*
  249. Lua supports an almost conventional set of statements, similar to those in
  250. Pascal or C. This set includes assignment, control structures, function
  251. calls, and variable declarations.
  252. ------------------------------------------------------------------------------
  253. 2.4.1 Chunks *luaref-chunk* *luaref-langChunks*
  254. The unit of execution of Lua is called a chunk. A chunk is simply a sequence
  255. of statements, which are executed sequentially. Each statement can be
  256. optionally followed by a semicolon:
  257. >
  258. chunk ::= {stat [ ; ]}
  259. <
  260. There are no empty statements and thus `;;` is not legal.
  261. Lua handles a chunk as the body of an anonymous function with a variable
  262. number of arguments (see |luaref-langFuncDefs|). As such, chunks can define
  263. local variables, receive arguments, and return values.
  264. A chunk may be stored in a file or in a string inside the host program. When a
  265. chunk is executed, first it is pre-compiled into instructions for a virtual
  266. machine, and then the compiled code is executed by an interpreter for the
  267. virtual machine.
  268. Chunks may also be pre-compiled into binary form; see program `luac` for
  269. details. Programs in source and compiled forms are interchangeable; Lua
  270. automatically detects the file type and acts accordingly.
  271. ------------------------------------------------------------------------------
  272. 2.4.2 Blocks *luaref-block* *luaref-langBlocks*
  273. A block is a list of statements; syntactically, a block is the same as a
  274. chunk:
  275. >
  276. block ::= chunk
  277. <
  278. *luaref-do* *luaref-end*
  279. A block may be explicitly delimited to produce a single statement:
  280. >
  281. stat ::= do block end
  282. <
  283. Explicit blocks are useful to control the scope of variable declarations.
  284. Explicit blocks are also sometimes used to add a `return` or `break` statement
  285. in the middle of another block (see |luaref-langContStructs|).
  286. ------------------------------------------------------------------------------
  287. 2.4.3 Assignment *luaref-langAssign*
  288. Lua allows multiple assignment. Therefore, the syntax for assignment defines a
  289. list of variables on the left side and a list of expressions on the right
  290. side. The elements in both lists are separated by commas:
  291. >
  292. stat ::= varlist1 = explist1
  293. varlist1 ::= var { , var }
  294. explist1 ::= exp { , exp }
  295. <
  296. Expressions are discussed in |luaref-langExpressions|.
  297. Before the assignment, the list of values is adjusted to the length of the
  298. list of variables. If there are more values than needed, the excess values are
  299. thrown away. If there are fewer values than needed, the list is extended with
  300. as many `nil`s as needed. If the list of expressions ends with a function
  301. call, then all values returned by this call enter in the list of values,
  302. before the adjustment (except when the call is enclosed in parentheses; see
  303. |luaref-langExpressions|).
  304. The assignment statement first evaluates all its expressions and only then are
  305. the assignments performed. Thus the code
  306. >
  307. i = 3
  308. i, a[i] = i+1, 20
  309. <
  310. sets `a[3]` to 20, without affecting `a[4]` because the `i` in `a[i]` is evaluated (to
  311. 3) before it is assigned 4. Similarly, the line
  312. >
  313. x, y = y, x
  314. <
  315. exchanges the values of `x` and `y`.
  316. The meaning of assignments to global variables and table fields can be changed
  317. via metatables. An assignment to an indexed variable `t[i] = val` is
  318. equivalent to `settable_event(t,i,val)`. (See |luaref-langMetatables| for a
  319. complete description of the `settable_event` function. This function is not
  320. defined or callable in Lua. We use it here only for explanatory purposes.)
  321. An assignment to a global variable `x = val` is equivalent to the
  322. assignment `_env.x = val`, which in turn is equivalent to
  323. >
  324. settable_event(_env, "x", val)
  325. <
  326. where `_env` is the environment of the running function. (The `_env` variable is
  327. not defined in Lua. We use it here only for explanatory purposes.)
  328. ------------------------------------------------------------------------------
  329. 2.4.4 Control Structures *luaref-langContStructs*
  330. *luaref-if* *luaref-then* *luaref-else* *luaref-elseif*
  331. *luaref-while* *luaref-repeat* *luaref-until*
  332. The control structures `if`, `while`, and `repeat` have the usual meaning and
  333. familiar syntax:
  334. >
  335. stat ::= while exp do block end
  336. stat ::= repeat block until exp
  337. stat ::= if exp then block { elseif exp then block }
  338. [ else block ] end
  339. <
  340. Lua also has a `for` statement, in two flavors (see |luaref-langForStat|).
  341. The condition expression of a control structure may return any value.
  342. Both `false` and `nil` are considered false. All values different
  343. from `nil` and `false` are considered true (in particular, the number 0 and the
  344. empty string are also true).
  345. In the `repeat-until` loop, the inner block does not end at the `until` keyword,
  346. but only after the condition. So, the condition can refer to local variables
  347. declared inside the loop block.
  348. *luaref-return*
  349. The `return` statement is used to return values from a function or a chunk
  350. (which is just a function). Functions and chunks may return more than one
  351. value, so the syntax for the `return` statement is
  352. `stat ::=` `return` `[explist1]`
  353. *luaref-break*
  354. The `break` statement is used to terminate the execution of a `while`, `repeat`,
  355. or `for` loop, skipping to the next statement after the loop:
  356. `stat ::=` `break`
  357. A `break` ends the innermost enclosing loop.
  358. The `return` and `break` statements can only be written as the `last`
  359. statement of a block. If it is really necessary to `return` or `break` in the
  360. middle of a block, then an explicit inner block can be used, as in the idioms
  361. `do return end` and `do break end`, because now `return` and `break` are
  362. the last statements in their (inner) blocks.
  363. ------------------------------------------------------------------------------
  364. 2.4.5 For Statement *luaref-for* *luaref-langForStat*
  365. The `for` statement has two forms: one numeric and one generic.
  366. The numeric `for` loop repeats a block of code while a control variable runs
  367. through an arithmetic progression. It has the following syntax:
  368. >
  369. stat ::= for Name = exp , exp [ , exp ] do block end
  370. <
  371. The `block` is repeated for `name` starting at the value of the first `exp`, until
  372. it passes the second `exp` by steps of the third `exp`. More precisely,
  373. a `for` statement like >
  374. for var = e1, e2, e3 do block end
  375. < is equivalent to the code: >
  376. do
  377. local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3)
  378. if not ( var and limit and step ) then error() end
  379. while ( step >0 and var <= limit )
  380. or ( step <=0 and var >= limit ) do
  381. block
  382. var = var + step
  383. end
  384. end
  385. <
  386. Note the following:
  387. - All three control expressions are evaluated only once, before the loop
  388. starts. They must all result in numbers.
  389. - `var`, `limit` and `step` are invisible variables. The names are here for
  390. explanatory purposes only.
  391. - If the third expression (the step) is absent, then a step of 1 is used.
  392. - You can use `break` to exit a `for` loop.
  393. - The loop variable `var` is local to the loop; you cannot use its value
  394. after the `for` ends or is broken. If you need this value, assign it to
  395. another variable before breaking or exiting the loop.
  396. *luaref-in*
  397. The generic `for` statement works over functions, called iterators. On each
  398. iteration, the iterator function is called to produce a new value, stopping
  399. when this new value is `nil`. The generic `for` loop has the following syntax:
  400. >
  401. stat ::= for namelist in explist1 do block end
  402. namelist ::= Name { , Name }
  403. <
  404. A `for` statement like
  405. `for` `var1, ..., varn` `in` `explist` `do` `block` `end`
  406. is equivalent to the code: >
  407. do
  408. local f, s, var = explist
  409. while true do
  410. local var1, ..., varn = f(s, var)
  411. var = var1
  412. if var == nil then break end
  413. block
  414. end
  415. end
  416. <
  417. Note the following:
  418. - `explist` is evaluated only once. Its results are an iterator function,
  419. a `state`, and an initial value for the first iterator variable.
  420. - `f`, `s`, and `var` are invisible variables. The names are here for
  421. explanatory purposes only.
  422. - You can use `break` to exit a `for` loop.
  423. - The loop variables `var1, ..., varn` are local to the loop; you cannot use
  424. their values after the `for` ends. If you need these values, then assign
  425. them to other variables before breaking or exiting the loop.
  426. ------------------------------------------------------------------------------
  427. 2.4.6 Function Calls as Statements *luaref-langFuncStat*
  428. To allow possible side-effects, function calls can be executed as statements:
  429. >
  430. stat ::= functioncall
  431. <
  432. In this case, all returned values are thrown away. Function calls are
  433. explained in |luaref-langFuncCalls|.
  434. ------------------------------------------------------------------------------
  435. 2.4.7 Local Declarations *luaref-local* *luaref-langLocalDec*
  436. Local variables may be declared anywhere inside a block. The declaration may
  437. include an initial assignment:
  438. >
  439. stat ::= local namelist [ = explist1 ]
  440. namelist ::= Name { , Name }
  441. <
  442. If present, an initial assignment has the same semantics of a multiple
  443. assignment (see |luaref-langAssign|). Otherwise, all variables are initialized
  444. with `nil`.
  445. A chunk is also a block (see |luaref-langChunks|), and so local variables can be
  446. declared in a chunk outside any explicit block. The scope of such local
  447. variables extends until the end of the chunk.
  448. The visibility rules for local variables are explained in
  449. |luaref-langVisibRules|.
  450. ==============================================================================
  451. 2.5 Expressions *luaref-langExpressions*
  452. The basic expressions in Lua are the following:
  453. >
  454. exp ::= prefixexp
  455. exp ::= nil | false | true
  456. exp ::= Number
  457. exp ::= String
  458. exp ::= function
  459. exp ::= tableconstructor
  460. exp ::= ...
  461. exp ::= exp binop exp
  462. exp ::= unop exp
  463. prefixexp ::= var | functioncall | ( exp )
  464. <
  465. Numbers and literal strings are explained in |luaref-langLexConv|; variables are
  466. explained in |luaref-langVariables|; function definitions are explained in
  467. |luaref-langFuncDefs|; function calls are explained in |luaref-langFuncCalls|;
  468. table constructors are explained in |luaref-langTableConst|. Vararg expressions,
  469. denoted by three dots (`...`), can only be used inside vararg functions;
  470. they are explained in |luaref-langFuncDefs|.
  471. Binary operators comprise arithmetic operators (see |luaref-langArithOp|),
  472. relational operators (see |luaref-langRelOp|), logical operators (see
  473. |luaref-langLogOp|), and the concatenation operator (see |luaref-langConcat|).
  474. Unary operators comprise the unary minus (see |luaref-langArithOp|), the unary
  475. `not` (see |luaref-langLogOp|), and the unary length operator (see
  476. |luaref-langLength|).
  477. Both function calls and vararg expressions may result in multiple values. If
  478. the expression is used as a statement (see |luaref-langFuncStat|)
  479. (only possible for function calls), then its return list is adjusted to zero
  480. elements, thus discarding all returned values. If the expression is used as
  481. the last (or the only) element of a list of expressions, then no adjustment is
  482. made (unless the call is enclosed in parentheses). In all other contexts, Lua
  483. adjusts the result list to one element, discarding all values except the first
  484. one.
  485. Here are some examples:
  486. >
  487. f() -- adjusted to 0 results
  488. g(f(), x) -- f() is adjusted to 1 result
  489. g(x, f()) -- g gets x plus all results from f()
  490. a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
  491. a,b = ... -- a gets the first vararg parameter, b gets
  492. -- the second (both a and b may get nil if there
  493. -- is no corresponding vararg parameter)
  494. a,b,c = x, f() -- f() is adjusted to 2 results
  495. a,b,c = f() -- f() is adjusted to 3 results
  496. return f() -- returns all results from f()
  497. return ... -- returns all received vararg parameters
  498. return x,y,f() -- returns x, y, and all results from f()
  499. {f()} -- creates a list with all results from f()
  500. {...} -- creates a list with all vararg parameters
  501. {f(), nil} -- f() is adjusted to 1 result
  502. <
  503. An expression enclosed in parentheses always results in only one value. Thus,
  504. `(f(x,y,z))` is always a single value, even if `f` returns several values.
  505. (The value of `(f(x,y,z))` is the first value returned by `f` or `nil` if `f` does not
  506. return any values.)
  507. ------------------------------------------------------------------------------
  508. 2.5.1 Arithmetic Operators *luaref-langArithOp*
  509. Lua supports the usual arithmetic operators: the binary `+` (addition),
  510. `-` (subtraction), `*` (multiplication), `/` (division), `%` (modulo)
  511. and `^` (exponentiation); and unary `-` (negation). If the operands are numbers,
  512. or strings that can be converted to numbers (see |luaref-langCoercion|), then all
  513. operations have the usual meaning. Exponentiation works for any exponent. For
  514. instance, `x^(-0.5)` computes the inverse of the square root of `x`. Modulo is
  515. defined as
  516. >
  517. a % b == a - math.floor(a/b)*b
  518. <
  519. That is, it is the remainder of a division that rounds the quotient towards
  520. minus infinity.
  521. ------------------------------------------------------------------------------
  522. 2.5.2 Relational Operators *luaref-langRelOp*
  523. The relational operators in Lua are
  524. >
  525. == ~= < > <= >=
  526. <
  527. These operators always result in `false` or `true`.
  528. Equality (`==`) first compares the type of its operands. If the types are
  529. different, then the result is `false`. Otherwise, the values of the operands
  530. are compared. Numbers and strings are compared in the usual way. Objects
  531. (tables, userdata, threads, and functions) are compared by reference: two
  532. objects are considered equal only if they are the same object. Every time you
  533. create a new object (a table, userdata, or function), this new object is
  534. different from any previously existing object.
  535. You can change the way that Lua compares tables and userdata using the "eq"
  536. metamethod (see |luaref-langMetatables|).
  537. The conversion rules of coercion |luaref-langCoercion| do not apply to
  538. equality comparisons. Thus, `"0"==0` evaluates to `false`, and `t[0]` and
  539. `t["0"]` denote different entries in a table.
  540. The operator `~=` is exactly the negation of equality (`==`).
  541. The order operators work as follows. If both arguments are numbers, then they
  542. are compared as such. Otherwise, if both arguments are strings, then their
  543. values are compared according to the current locale. Otherwise, Lua tries to
  544. call the "lt" or the "le" metamethod (see |luaref-langMetatables|).
  545. ------------------------------------------------------------------------------
  546. 2.5.3 Logical Operators *luaref-langLogOp*
  547. The logical operators in Lua are
  548. >
  549. and or not
  550. <
  551. Like the control structures (see |luaref-langContStructs|), all logical operators
  552. consider both `false` and `nil` as false and anything else as true.
  553. *luaref-not* *luaref-and* *luaref-or*
  554. The negation operator `not` always returns `false` or `true`. The conjunction
  555. operator `and` returns its first argument if this value is `false` or `nil`;
  556. otherwise, `and` returns its second argument. The disjunction
  557. operator `or` returns its first argument if this value is different
  558. from `nil` and `false`; otherwise, `or` returns its second argument.
  559. Both `and` and `or` use short-cut evaluation, that is, the second operand is
  560. evaluated only if necessary. Here are some examples:
  561. >
  562. 10 or 20 --> 10
  563. 10 or error() --> 10
  564. nil or "a" --> "a"
  565. nil and 10 --> nil
  566. false and error() --> false
  567. false and nil --> false
  568. false or nil --> nil
  569. 10 and 20 --> 20
  570. <
  571. (In this manual, `-->` indicates the result of the preceding expression.)
  572. ------------------------------------------------------------------------------
  573. 2.5.4 Concatenation *luaref-langConcat*
  574. The string concatenation operator in Lua is denoted by two dots (`..`).
  575. If both operands are strings or numbers, then they are converted to strings
  576. according to the rules mentioned in |luaref-langCoercion|. Otherwise, the
  577. "concat" metamethod is called (see |luaref-langMetatables|).
  578. ------------------------------------------------------------------------------
  579. 2.5.5 The Length Operator *luaref-langLength*
  580. The length operator is denoted by the unary operator `#`. The length of a
  581. string is its number of bytes (that is, the usual meaning of string length
  582. when each character is one byte).
  583. The length of a table `t` is defined to be any integer index `n` such that `t[n]` is
  584. not `nil` and `t[n+1]` is `nil`; moreover, if `t[1]` is `nil`, `n` may be zero. For a
  585. regular array, with non-nil values from 1 to a given `n`, its length is exactly
  586. that `n`, the index of its last value. If the array has "holes" (that
  587. is, `nil` values between other non-nil values), then `#t` may be any of the
  588. indices that directly precedes a `nil` value (that is, it may consider any
  589. such `nil` value as the end of the array).
  590. ------------------------------------------------------------------------------
  591. 2.5.6 Precedence *luaref-langPrec*
  592. Operator precedence in Lua follows the table below, from lower to higher
  593. priority:
  594. >
  595. or
  596. and
  597. < > <= >= ~= ==
  598. ..
  599. + -
  600. * /
  601. not # - (unary)
  602. ^
  603. <
  604. As usual, you can use parentheses to change the precedences in an expression.
  605. The concatenation (`..`) and exponentiation (`^`) operators are right
  606. associative. All other binary operators are left associative.
  607. ------------------------------------------------------------------------------
  608. 2.5.7 Table Constructors *luaref-langTableConst*
  609. Table constructors are expressions that create tables. Every time a
  610. constructor is evaluated, a new table is created. Constructors can be used to
  611. create empty tables, or to create a table and initialize some of its fields.
  612. The general syntax for constructors is
  613. >
  614. tableconstructor ::= { [ fieldlist ] }
  615. fieldlist ::= field { fieldsep field } [ fieldsep ]
  616. field ::= [ exp ] = exp | Name = exp | exp
  617. fieldsep ::= , | ;
  618. <
  619. Each field of the form `[exp1] = exp2` adds to the new table an entry with
  620. key `exp1` and value `exp2`. A field of the form `name = exp` is equivalent to
  621. `["name"] = exp`. Finally, fields of the form `exp` are equivalent to
  622. `[i] = exp`, where `i` are consecutive numerical integers, starting with 1.
  623. Fields in the other formats do not affect this counting. For example,
  624. >
  625. a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
  626. <
  627. is equivalent to
  628. >
  629. do
  630. local t = {}
  631. t[f(1)] = g
  632. t[1] = "x" -- 1st exp
  633. t[2] = "y" -- 2nd exp
  634. t.x = 1 -- temp["x"] = 1
  635. t[3] = f(x) -- 3rd exp
  636. t[30] = 23
  637. t[4] = 45 -- 4th exp
  638. a = t
  639. end
  640. <
  641. If the last field in the list has the form `exp` and the expression is a
  642. function call, then all values returned by the call enter the list
  643. consecutively (see |luaref-langFuncCalls|). To avoid this, enclose the function
  644. call in parentheses (see |luaref-langExpressions|).
  645. The field list may have an optional trailing separator, as a convenience for
  646. machine-generated code.
  647. ------------------------------------------------------------------------------
  648. 2.5.8 Function Calls *luaref-function* *luaref-langFuncCalls*
  649. A function call in Lua has the following syntax:
  650. >
  651. functioncall ::= prefixexp args
  652. <
  653. In a function call, first `prefixexp` and `args` are evaluated. If the value
  654. of `prefixexp` has type `function`, then this function is called with the given
  655. arguments. Otherwise, the `prefixexp` "call" metamethod is called, having as
  656. first parameter the value of `prefixexp`, followed by the original call
  657. arguments (see |luaref-langMetatables|).
  658. The form
  659. >
  660. functioncall ::= prefixexp : Name args
  661. <
  662. can be used to call "methods". A call `v:name(` `args` `)` is syntactic sugar
  663. for `v.name(v,` `args` `)`, except that `v` is evaluated only once.
  664. Arguments have the following syntax:
  665. >
  666. args ::= ( [ explist1 ] )
  667. args ::= tableconstructor
  668. args ::= String
  669. <
  670. All argument expressions are evaluated before the call. A call of the
  671. form `f{` `fields` `}` is syntactic sugar for `f({` `fields` `})`, that is, the
  672. argument list is a single new table. A call of the form `f'` `string` `'`
  673. (or `f"` `string` `"` or `f[[` `string` `]]`) is syntactic sugar for
  674. `f('` `string` `')`, that is, the argument list is a single literal string.
  675. As an exception to the free-format syntax of Lua, you cannot put a line break
  676. before the `(` in a function call. This restriction avoids some ambiguities
  677. in the language. If you write
  678. >
  679. a = f
  680. (g).x(a)
  681. <
  682. Lua would see that as a single statement, `a = f(g).x(a)`. So, if you want two
  683. statements, you must add a semi-colon between them. If you actually want to
  684. call `f`, you must remove the line break before `(g)`.
  685. *luaref-tailcall*
  686. A call of the form `return` `functioncall` is called a tail call. Lua
  687. implements proper tail calls (or proper tail recursion): in a tail call, the
  688. called function reuses the stack entry of the calling function. Therefore,
  689. there is no limit on the number of nested tail calls that a program can
  690. execute. However, a tail call erases any debug information about the calling
  691. function. Note that a tail call only happens with a particular syntax, where
  692. the `return` has one single function call as argument; this syntax makes the
  693. calling function return exactly the returns of the called function. So, none
  694. of the following examples are tail calls:
  695. >
  696. return (f(x)) -- results adjusted to 1
  697. return 2 * f(x)
  698. return x, f(x) -- additional results
  699. f(x); return -- results discarded
  700. return x or f(x) -- results adjusted to 1
  701. <
  702. ------------------------------------------------------------------------------
  703. 2.5.9 Function Definitions *luaref-langFuncDefs*
  704. The syntax for function definition is
  705. >
  706. function ::= function funcbody
  707. funcbody ::= ( [ parlist1 ] ) block end
  708. <
  709. The following syntactic sugar simplifies function definitions:
  710. >
  711. stat ::= function funcname funcbody
  712. stat ::= local function Name funcbody
  713. funcname ::= Name { . Name } [ : Name ]
  714. <
  715. The statement
  716. `function f ()` `body` `end`
  717. translates to
  718. `f = function ()` `body` `end`
  719. The statement
  720. `function t.a.b.c.f ()` `body` `end`
  721. translates to
  722. `t.a.b.c.f = function ()` `body` `end`
  723. The statement
  724. `local function f ()` `body` `end`
  725. translates to
  726. `local f; f = function f ()` `body` `end`
  727. not to
  728. `local f = function f ()` `body` `end`
  729. (This only makes a difference when the body of the function contains
  730. references to `f`.)
  731. *luaref-closure*
  732. A function definition is an executable expression, whose value has type
  733. `function`. When Lua pre-compiles a chunk, all its function bodies are
  734. pre-compiled too. Then, whenever Lua executes the function definition, the
  735. function is instantiated (or closed). This function instance (or closure) is
  736. the final value of the expression. Different instances of the same function
  737. may refer to different external local variables and may have different
  738. environment tables.
  739. Parameters act as local variables that are initialized with the argument
  740. values:
  741. >
  742. parlist1 ::= namelist [ , ... ] | ...
  743. <
  744. *luaref-vararg*
  745. When a function is called, the list of arguments is adjusted to the length of
  746. the list of parameters, unless the function is a variadic or vararg function,
  747. which is indicated by three dots (`...`) at the end of its parameter list. A
  748. vararg function does not adjust its argument list; instead, it collects all
  749. extra arguments and supplies them to the function through a vararg expression,
  750. which is also written as three dots. The value of this expression is a list of
  751. all actual extra arguments, similar to a function with multiple results. If a
  752. vararg expression is used inside another expression or in the middle of a list
  753. of expressions, then its return list is adjusted to one element. If the
  754. expression is used as the last element of a list of expressions, then no
  755. adjustment is made (unless the call is enclosed in parentheses).
  756. As an example, consider the following definitions:
  757. >
  758. function f(a, b) end
  759. function g(a, b, ...) end
  760. function r() return 1,2,3 end
  761. <
  762. Then, we have the following mapping from arguments to parameters and to the
  763. vararg expression:
  764. >
  765. CALL PARAMETERS
  766. f(3) a=3, b=nil
  767. f(3, 4) a=3, b=4
  768. f(3, 4, 5) a=3, b=4
  769. f(r(), 10) a=1, b=10
  770. f(r()) a=1, b=2
  771. g(3) a=3, b=nil, ... --> (nothing)
  772. g(3, 4) a=3, b=4, ... --> (nothing)
  773. g(3, 4, 5, 8) a=3, b=4, ... --> 5 8
  774. g(5, r()) a=5, b=1, ... --> 2 3
  775. <
  776. Results are returned using the `return` statement (see |luaref-langContStructs|).
  777. If control reaches the end of a function without encountering
  778. a `return` statement, then the function returns with no results.
  779. *luaref-colonsyntax*
  780. The colon syntax is used for defining methods, that is, functions that have an
  781. implicit extra parameter `self`. Thus, the statement
  782. `function t.a.b.c:f (` `params` `)` `body` `end`
  783. is syntactic sugar for
  784. `t.a.b.c:f = function (self, (` `params` `)` `body` `end`
  785. ==============================================================================
  786. 2.6 Visibility Rules *luaref-langVisibRules*
  787. Lua is a lexically scoped language. The scope of variables begins at the first
  788. statement after their declaration and lasts until the end of the innermost
  789. block that includes the declaration. Consider the following example:
  790. >
  791. x = 10 -- global variable
  792. do -- new block
  793. local x = x -- new `x`, with value 10
  794. print(x) --> 10
  795. x = x+1
  796. do -- another block
  797. local x = x+1 -- another `x`
  798. print(x) --> 12
  799. end
  800. print(x) --> 11
  801. end
  802. print(x) --> 10 (the global one)
  803. <
  804. Notice that, in a declaration like `local x = x`, the new `x` being declared is
  805. not in scope yet, and so the second `x` refers to the outside variable.
  806. *luaref-upvalue*
  807. Because of the lexical scoping rules, local variables can be freely accessed
  808. by functions defined inside their scope. A local variable used by an inner
  809. function is called an upvalue, or external local variable, inside the inner
  810. function.
  811. Notice that each execution of a local statement defines new local variables.
  812. Consider the following example:
  813. >
  814. a = {}
  815. local x = 20
  816. for i=1,10 do
  817. local y = 0
  818. a[i] = function () y=y+1; return x+y end
  819. end
  820. <
  821. The loop creates ten closures (that is, ten instances of the anonymous
  822. function). Each of these closures uses a different `y` variable, while all of
  823. them share the same `x`.
  824. ==============================================================================
  825. 2.7 Error Handling *luaref-langError*
  826. Because Lua is an embedded extension language, all Lua actions start from
  827. C code in the host program calling a function from the Lua library (see
  828. |lua_pcall()|). Whenever an error occurs during Lua compilation or
  829. execution, control returns to C, which can take appropriate measures (such as
  830. print an error message).
  831. Lua code can explicitly generate an error by calling the `error` function (see
  832. |luaref-error()|). If you need to catch errors in Lua, you can use
  833. the `pcall` function (see |luaref-pcall()|).
  834. ==============================================================================
  835. 2.8 Metatables *luaref-metatable* *luaref-langMetatables*
  836. Every value in Lua may have a metatable. This metatable is an ordinary Lua
  837. table that defines the behavior of the original table and userdata under
  838. certain special operations. You can change several aspects of the behavior of
  839. an object by setting specific fields in its metatable. For instance, when a
  840. non-numeric value is the operand of an addition, Lua checks for a function in
  841. the field `"__add"` in its metatable. If it finds one, Lua calls that function
  842. to perform the addition.
  843. We call the keys in a metatable events and the values metamethods. In the
  844. previous example, the event is "add" and the metamethod is the function that
  845. performs the addition.
  846. You can query the metatable of any value through the `getmetatable` function
  847. (see |luaref-getmetatable()|).
  848. You can replace the metatable of tables through the `setmetatable` function (see
  849. |luaref-setmetatable()|). You cannot change the metatable of other types from Lua
  850. (except using the debug library); you must use the C API for that.
  851. Tables and userdata have individual metatables (although multiple tables and
  852. userdata can share a same table as their metatable); values of all other types
  853. share one single metatable per type. So, there is one single metatable for all
  854. numbers, and for all strings, etc.
  855. A metatable may control how an object behaves in arithmetic operations, order
  856. comparisons, concatenation, length operation, and indexing. A metatable can
  857. also define a function to be called when a userdata is garbage collected. For
  858. each of those operations Lua associates a specific key called an event. When
  859. Lua performs one of those operations over a value, it checks whether this
  860. value has a metatable with the corresponding event. If so, the value
  861. associated with that key (the metamethod) controls how Lua will perform the
  862. operation.
  863. Metatables control the operations listed next. Each operation is identified by
  864. its corresponding name. The key for each operation is a string with its name
  865. prefixed by two underscores, `__`; for instance, the key for operation "add"
  866. is the string "__add". The semantics of these operations is better explained
  867. by a Lua function describing how the interpreter executes that operation.
  868. The code shown here in Lua is only illustrative; the real behavior is hard
  869. coded in the interpreter and it is much more efficient than this simulation.
  870. All functions used in these descriptions (`rawget`, `tonumber`, etc.) are
  871. described in |luaref-libBasic|. In particular, to retrieve the metamethod of a
  872. given object, we use the expression
  873. >
  874. metatable(obj)[event]
  875. <
  876. This should be read as
  877. >
  878. rawget(metatable(obj) or {}, event)
  879. <
  880. That is, the access to a metamethod does not invoke other metamethods, and the
  881. access to objects with no metatables does not fail (it simply results
  882. in `nil`).
  883. "add": *__add()*
  884. ------
  885. the `+` operation.
  886. The function `getbinhandler` below defines how Lua chooses a handler for a
  887. binary operation. First, Lua tries the first operand. If its type does not
  888. define a handler for the operation, then Lua tries the second operand.
  889. >
  890. function getbinhandler (op1, op2, event)
  891. return metatable(op1)[event] or metatable(op2)[event]
  892. end
  893. <
  894. By using this function, the behavior of the `op1 + op2` is
  895. >
  896. function add_event (op1, op2)
  897. local o1, o2 = tonumber(op1), tonumber(op2)
  898. if o1 and o2 then -- both operands are numeric?
  899. return o1 + o2 -- `+` here is the primitive `add`
  900. else -- at least one of the operands is not numeric
  901. local h = getbinhandler(op1, op2, "__add")
  902. if h then
  903. -- call the handler with both operands
  904. return h(op1, op2)
  905. else -- no handler available: default behavior
  906. error(...)
  907. end
  908. end
  909. end
  910. <
  911. "sub": *__sub()*
  912. ------
  913. the `-` operation. Behavior similar to the "add" operation.
  914. "mul": *__mul()*
  915. ------
  916. the `*` operation. Behavior similar to the "add" operation.
  917. "div": *__div()*
  918. ------
  919. the `/` operation. Behavior similar to the "add" operation.
  920. "mod": *__mod()*
  921. ------
  922. the `%` operation. Behavior similar to the "add" operation, with the
  923. operation `o1 - floor(o1/o2)*o2` as the primitive operation.
  924. "pow": *__pow()*
  925. ------
  926. the `^` (exponentiation) operation. Behavior similar to the "add" operation,
  927. with the function `pow` (from the C math library) as the primitive operation.
  928. "unm": *__unm()*
  929. ------
  930. the unary `-` operation.
  931. >
  932. function unm_event (op)
  933. local o = tonumber(op)
  934. if o then -- operand is numeric?
  935. return -o -- `-` here is the primitive `unm`
  936. else -- the operand is not numeric.
  937. -- Try to get a handler from the operand
  938. local h = metatable(op).__unm
  939. if h then
  940. -- call the handler with the operand
  941. return h(op)
  942. else -- no handler available: default behavior
  943. error(...)
  944. end
  945. end
  946. end
  947. <
  948. "concat": *__concat()*
  949. ---------
  950. the `..` (concatenation) operation.
  951. >
  952. function concat_event (op1, op2)
  953. if (type(op1) == "string" or type(op1) == "number") and
  954. (type(op2) == "string" or type(op2) == "number") then
  955. return op1 .. op2 -- primitive string concatenation
  956. else
  957. local h = getbinhandler(op1, op2, "__concat")
  958. if h then
  959. return h(op1, op2)
  960. else
  961. error(...)
  962. end
  963. end
  964. end
  965. <
  966. "len": *__len()*
  967. ------
  968. the `#` operation.
  969. >
  970. function len_event (op)
  971. if type(op) == "string" then
  972. return strlen(op) -- primitive string length
  973. elseif type(op) == "table" then
  974. return #op -- primitive table length
  975. else
  976. local h = metatable(op).__len
  977. if h then
  978. -- call the handler with the operand
  979. return h(op)
  980. else -- no handler available: default behavior
  981. error(...)
  982. end
  983. end
  984. end
  985. <
  986. "eq": *__eq()*
  987. -----
  988. the `==` operation.
  989. The function `getcomphandler` defines how Lua chooses a metamethod for
  990. comparison operators. A metamethod only is selected when both objects being
  991. compared have the same type and the same metamethod for the selected
  992. operation.
  993. >
  994. function getcomphandler (op1, op2, event)
  995. if type(op1) ~= type(op2) then return nil end
  996. local mm1 = metatable(op1)[event]
  997. local mm2 = metatable(op2)[event]
  998. if mm1 == mm2 then return mm1 else return nil end
  999. end
  1000. <
  1001. The "eq" event is defined as follows:
  1002. >
  1003. function eq_event (op1, op2)
  1004. if type(op1) ~= type(op2) then -- different types?
  1005. return false -- different objects
  1006. end
  1007. if op1 == op2 then -- primitive equal?
  1008. return true -- objects are equal
  1009. end
  1010. -- try metamethod
  1011. local h = getcomphandler(op1, op2, "__eq")
  1012. if h then
  1013. return h(op1, op2)
  1014. else
  1015. return false
  1016. end
  1017. end
  1018. <
  1019. `a ~= b` is equivalent to `not (a == b)`.
  1020. "lt": *__lt()*
  1021. -----
  1022. the `<` operation.
  1023. >
  1024. function lt_event (op1, op2)
  1025. if type(op1) == "number" and type(op2) == "number" then
  1026. return op1 < op2 -- numeric comparison
  1027. elseif type(op1) == "string" and type(op2) == "string" then
  1028. return op1 < op2 -- lexicographic comparison
  1029. else
  1030. local h = getcomphandler(op1, op2, "__lt")
  1031. if h then
  1032. return h(op1, op2)
  1033. else
  1034. error(...);
  1035. end
  1036. end
  1037. end
  1038. <
  1039. `a > b` is equivalent to `b < a`.
  1040. "le": *__le()*
  1041. -----
  1042. the `<=` operation.
  1043. >
  1044. function le_event (op1, op2)
  1045. if type(op1) == "number" and type(op2) == "number" then
  1046. return op1 <= op2 -- numeric comparison
  1047. elseif type(op1) == "string" and type(op2) == "string" then
  1048. return op1 <= op2 -- lexicographic comparison
  1049. else
  1050. local h = getcomphandler(op1, op2, "__le")
  1051. if h then
  1052. return h(op1, op2)
  1053. else
  1054. h = getcomphandler(op1, op2, "__lt")
  1055. if h then
  1056. return not h(op2, op1)
  1057. else
  1058. error(...);
  1059. end
  1060. end
  1061. end
  1062. end
  1063. <
  1064. `a >= b` is equivalent to `b <= a`. Note that, in the absence of a "le"
  1065. metamethod, Lua tries the "lt", assuming that `a <= b` is equivalent
  1066. to `not (b < a)`.
  1067. "index": *__index()*
  1068. --------
  1069. The indexing access `table[key]`.
  1070. >
  1071. function gettable_event (table, key)
  1072. local h
  1073. if type(table) == "table" then
  1074. local v = rawget(table, key)
  1075. if v ~= nil then return v end
  1076. h = metatable(table).__index
  1077. if h == nil then return nil end
  1078. else
  1079. h = metatable(table).__index
  1080. if h == nil then
  1081. error(...);
  1082. end
  1083. end
  1084. if type(h) == "function" then
  1085. return h(table, key) -- call the handler
  1086. else return h[key] -- or repeat operation on it
  1087. end
  1088. <
  1089. "newindex": *__newindex()*
  1090. -----------
  1091. The indexing assignment `table[key] = value`.
  1092. >
  1093. function settable_event (table, key, value)
  1094. local h
  1095. if type(table) == "table" then
  1096. local v = rawget(table, key)
  1097. if v ~= nil then rawset(table, key, value); return end
  1098. h = metatable(table).__newindex
  1099. if h == nil then rawset(table, key, value); return end
  1100. else
  1101. h = metatable(table).__newindex
  1102. if h == nil then
  1103. error(...);
  1104. end
  1105. end
  1106. if type(h) == "function" then
  1107. return h(table, key,value) -- call the handler
  1108. else h[key] = value -- or repeat operation on it
  1109. end
  1110. <
  1111. "call": *__call()*
  1112. -------
  1113. called when Lua calls a value.
  1114. >
  1115. function function_event (func, ...)
  1116. if type(func) == "function" then
  1117. return func(...) -- primitive call
  1118. else
  1119. local h = metatable(func).__call
  1120. if h then
  1121. return h(func, ...)
  1122. else
  1123. error(...)
  1124. end
  1125. end
  1126. end
  1127. <
  1128. ==============================================================================
  1129. 2.9 Environments *luaref-environment* *luaref-langEnvironments*
  1130. Besides metatables, objects of types thread, function, and userdata have
  1131. another table associated with them, called their environment. Like metatables,
  1132. environments are regular tables and multiple objects can share the same
  1133. environment.
  1134. Environments associated with userdata have no meaning for Lua. It is only a
  1135. convenience feature for programmers to associate a table to a userdata.
  1136. Environments associated with threads are called global environments. They are
  1137. used as the default environment for their threads and non-nested functions
  1138. created by the thread (through `loadfile` |luaref-loadfile()|, `loadstring`
  1139. |luaref-loadstring()| or `load` |luaref-load()|) and can be directly accessed by C
  1140. code (see |luaref-apiPseudoIndices|).
  1141. Environments associated with C functions can be directly accessed by C code
  1142. (see |luaref-apiPseudoIndices|). They are used as the default environment for
  1143. other C functions created by the function.
  1144. Environments associated with Lua functions are used to resolve all accesses to
  1145. global variables within the function (see |luaref-langVariables|). They are
  1146. used as the default environment for other Lua functions created by the
  1147. function.
  1148. You can change the environment of a Lua function or the running thread by
  1149. calling `setfenv`. You can get the environment of a Lua function or the
  1150. running thread by calling `getfenv` (see |lua_getfenv()|). To manipulate the
  1151. environment of other objects (userdata, C functions, other threads) you must
  1152. use the C API.
  1153. ==============================================================================
  1154. 2.10 Garbage Collection *luaref-langGC*
  1155. Lua performs automatic memory management. This means that you do not have to
  1156. worry neither about allocating memory for new objects nor about freeing it
  1157. when the objects are no longer needed. Lua manages memory automatically by
  1158. running a garbage collector from time to time to collect all dead objects
  1159. (that is, these objects that are no longer accessible from Lua). All objects
  1160. in Lua are subject to automatic management: tables, userdata, functions,
  1161. threads, and strings.
  1162. Lua implements an incremental mark-and-sweep collector. It uses two numbers to
  1163. control its garbage-collection cycles: the garbage-collector pause and the
  1164. garbage-collector step multiplier.
  1165. The garbage-collector pause controls how long the collector waits before
  1166. starting a new cycle. Larger values make the collector less aggressive. Values
  1167. smaller than 1 mean the collector will not wait to start a new cycle. A value
  1168. of 2 means that the collector waits for the total memory in use to double
  1169. before starting a new cycle.
  1170. The step multiplier controls the relative speed of the collector relative to
  1171. memory allocation. Larger values make the collector more aggressive but also
  1172. increase the size of each incremental step. Values smaller than 1 make the
  1173. collector too slow and may result in the collector never finishing a cycle.
  1174. The default, 2, means that the collector runs at "twice" the speed of memory
  1175. allocation.
  1176. You can change these numbers by calling `lua_gc` (see |lua_gc()|) in C or
  1177. `collectgarbage` (see |luaref-collectgarbage()|) in Lua. Both get percentage
  1178. points as arguments (so an argument of 100 means a real value of 1). With
  1179. these functions you can also control the collector directly (e.g., stop and
  1180. restart it).
  1181. ------------------------------------------------------------------------------
  1182. 2.10.1 Garbage-Collection Metamethods *luaref-langGCMeta*
  1183. Using the C API, you can set garbage-collector metamethods for userdata (see
  1184. |luaref-langMetatables|). These metamethods are also called finalizers.
  1185. Finalizers allow you to coordinate Lua's garbage collection with external
  1186. resource management (such as closing files, network or database connections,
  1187. or freeing your own memory).
  1188. *__gc*
  1189. Garbage userdata with a field `__gc` in their metatables are not collected
  1190. immediately by the garbage collector. Instead, Lua puts them in a list. After
  1191. the collection, Lua does the equivalent of the following function for each
  1192. userdata in that list:
  1193. >
  1194. function gc_event (udata)
  1195. local h = metatable(udata).__gc
  1196. if h then
  1197. h(udata)
  1198. end
  1199. end
  1200. <
  1201. At the end of each garbage-collection cycle, the finalizers for userdata are
  1202. called in reverse order of their creation, among these collected in that
  1203. cycle. That is, the first finalizer to be called is the one associated with
  1204. the userdata created last in the program.
  1205. ------------------------------------------------------------------------------
  1206. 2.10.2 - Weak Tables *luaref-weaktable* *luaref-langWeaktables*
  1207. A weak table is a table whose elements are weak references. A weak reference
  1208. is ignored by the garbage collector. In other words, if the only references to
  1209. an object are weak references, then the garbage collector will collect this
  1210. object.
  1211. *__mode*
  1212. A weak table can have weak keys, weak values, or both. A table with weak keys
  1213. allows the collection of its keys, but prevents the collection of its values.
  1214. A table with both weak keys and weak values allows the collection of both keys
  1215. and values. In any case, if either the key or the value is collected, the
  1216. whole pair is removed from the table. The weakness of a table is controlled by
  1217. the value of the `__mode` field of its metatable. If the `__mode` field is a
  1218. string containing the character `k`, the keys in the table are weak.
  1219. If `__mode` contains `v`, the values in the table are weak.
  1220. After you use a table as a metatable, you should not change the value of its
  1221. field `__mode`. Otherwise, the weak behavior of the tables controlled by this
  1222. metatable is undefined.
  1223. ==============================================================================
  1224. 2.11 Coroutines *luaref-coroutine* *luaref-langCoro*
  1225. Lua supports coroutines, also called collaborative multithreading. A coroutine
  1226. in Lua represents an independent thread of execution. Unlike threads in
  1227. multithread systems, however, a coroutine only suspends its execution by
  1228. explicitly calling a yield function.
  1229. You create a coroutine with a call to `coroutine.create` (see
  1230. |coroutine.create()|). Its sole argument is a function that is the main
  1231. function of the coroutine. The `create` function only creates a new coroutine
  1232. and returns a handle to it (an object of type `thread`); it does not start the
  1233. coroutine execution.
  1234. When you first call `coroutine.resume` (see |coroutine.resume()|),
  1235. passing as its first argument the thread returned by `coroutine.create`, the
  1236. coroutine starts its execution, at the first line of its main function. Extra
  1237. arguments passed to `coroutine.resume` are passed on to the coroutine main
  1238. function. After the coroutine starts running, it runs until it terminates or
  1239. `yields`.
  1240. A coroutine can terminate its execution in two ways: normally, when its main
  1241. function returns (explicitly or implicitly, after the last instruction); and
  1242. abnormally, if there is an unprotected error. In the first case,
  1243. `coroutine.resume` returns `true`, plus any values returned by the coroutine
  1244. main function. In case of errors, `coroutine.resume` returns `false` plus an
  1245. error message.
  1246. A coroutine yields by calling `coroutine.yield` (see
  1247. |coroutine.yield()|). When a coroutine yields, the corresponding
  1248. `coroutine.resume` returns immediately, even if the yield happens inside
  1249. nested function calls (that is, not in the main function, but in a function
  1250. directly or indirectly called by the main function). In the case of a yield,
  1251. `coroutine.resume` also returns `true`, plus any values passed to
  1252. `coroutine.yield`. The next time you resume the same coroutine, it continues
  1253. its execution from the point where it yielded, with the call to
  1254. `coroutine.yield` returning any extra arguments passed to `coroutine.resume`.
  1255. Like `coroutine.create`, the `coroutine.wrap` function (see
  1256. |coroutine.wrap()|) also creates a coroutine, but instead of returning
  1257. the coroutine itself, it returns a function that, when called, resumes the
  1258. coroutine. Any arguments passed to this function go as extra arguments to
  1259. `coroutine.resume`. `coroutine.wrap` returns all the values returned by
  1260. `coroutine.resume`, except the first one (the boolean error code). Unlike
  1261. `coroutine.resume`, `coroutine.wrap` does not catch errors; any error is
  1262. propagated to the caller.
  1263. As an example, consider the next code:
  1264. >
  1265. function foo1 (a)
  1266. print("foo", a)
  1267. return coroutine.yield(2*a)
  1268. end
  1269. co = coroutine.create(function (a,b)
  1270. print("co-body", a, b)
  1271. local r = foo1(a+1)
  1272. print("co-body", r)
  1273. local r, s = coroutine.yield(a+b, a-b)
  1274. print("co-body", r, s)
  1275. return b, "end"
  1276. end)
  1277. print("main", coroutine.resume(co, 1, 10))
  1278. print("main", coroutine.resume(co, "r"))
  1279. print("main", coroutine.resume(co, "x", "y"))
  1280. print("main", coroutine.resume(co, "x", "y"))
  1281. <
  1282. When you run it, it produces the following output:
  1283. >
  1284. co-body 1 10
  1285. foo 2
  1286. main true 4
  1287. co-body r
  1288. main true 11 -9
  1289. co-body x y
  1290. main true 10 end
  1291. main false cannot resume dead coroutine
  1292. <
  1293. ==============================================================================
  1294. 3 THE APPLICATION PROGRAM INTERFACE *luaref-API*
  1295. This section describes the C API for Lua, that is, the set of C functions
  1296. available to the host program to communicate with Lua. All API functions and
  1297. related types and constants are declared in the header file `lua.h`.
  1298. Even when we use the term "function", any facility in the API may be provided
  1299. as a `macro` instead. All such macros use each of its arguments exactly once
  1300. (except for the first argument, which is always a Lua state), and so do not
  1301. generate hidden side-effects.
  1302. As in most C libraries, the Lua API functions do not check their arguments for
  1303. validity or consistency. However, you can change this behavior by compiling
  1304. Lua with a proper definition for the macro `luai_apicheck`,in file
  1305. `luaconf.h`.
  1306. ==============================================================================
  1307. 3.1 The Stack *luaref-stack* *luaref-apiStack*
  1308. Lua uses a virtual stack to pass values to and from C. Each element in this
  1309. stack represents a Lua value (`nil`, number, string, etc.).
  1310. Whenever Lua calls C, the called function gets a new stack, which is
  1311. independent of previous stacks and of stacks of C functions that are still
  1312. active. This stack initially contains any arguments to the C function and it
  1313. is where the C function pushes its results to be returned to the caller (see
  1314. |lua_CFunction()|).
  1315. *luaref-stackindex*
  1316. For convenience, most query operations in the API do not follow a strict stack
  1317. discipline. Instead, they can refer to any element in the stack by using an
  1318. index: a positive index represents an absolute stack position (starting at 1);
  1319. a negative index represents an offset from the top of the stack. More
  1320. specifically, if the stack has `n` elements, then index 1 represents the first
  1321. element (that is, the element that was pushed onto the stack first) and index
  1322. `n` represents the last element; index `-1` also represents the last element
  1323. (that is, the element at the top) and index `-n` represents the first element.
  1324. We say that an index is valid if it lies between 1 and the stack top (that is,
  1325. if `1 <= abs(index) <= top`).
  1326. ==============================================================================
  1327. 3.2 Stack Size *luaref-apiStackSize*
  1328. When you interact with Lua API, you are responsible for ensuring consistency.
  1329. In particular, you are responsible for controlling stack overflow. You can
  1330. use the function `lua_checkstack` to grow the stack size (see
  1331. |lua_checkstack()|).
  1332. Whenever Lua calls C, it ensures that at least `LUA_MINSTACK` stack positions
  1333. are available. `LUA_MINSTACK` is defined as 20, so that usually you do not
  1334. have to worry about stack space unless your code has loops pushing elements
  1335. onto the stack.
  1336. Most query functions accept as indices any value inside the available stack
  1337. space, that is, indices up to the maximum stack size you have set through
  1338. `lua_checkstack`. Such indices are called acceptable indices. More formally,
  1339. we define an acceptable index as follows:
  1340. >
  1341. (index < 0 && abs(index) <= top) || (index > 0 && index <= stackspace)
  1342. <
  1343. Note that 0 is never an acceptable index.
  1344. ==============================================================================
  1345. 3.3 Pseudo-Indices *luaref-pseudoindex* *luaref-apiPseudoIndices*
  1346. Unless otherwise noted, any function that accepts valid indices can also be
  1347. called with pseudo-indices, which represent some Lua values that are
  1348. accessible to the C code but which are not in the stack. Pseudo-indices are
  1349. used to access the thread environment, the function environment, the registry,
  1350. and the upvalues of a C function (see |luaref-apiCClosures|).
  1351. The thread environment (where global variables live) is always at pseudo-index
  1352. `LUA_GLOBALSINDEX`. The environment of the running C function is always at
  1353. pseudo-index `LUA_ENVIRONINDEX`.
  1354. To access and change the value of global variables, you can use regular table
  1355. operations over an environment table. For instance, to access the value of a
  1356. global variable, do
  1357. >
  1358. lua_getfield(L, LUA_GLOBALSINDEX, varname);
  1359. <
  1360. ==============================================================================
  1361. 3.4 C Closures *luaref-cclosure* *luaref-apiCClosures*
  1362. When a C function is created, it is possible to associate some values with it,
  1363. thus creating a C closure; these values are called upvalues and are accessible
  1364. to the function whenever it is called (see |lua_pushcclosure()|).
  1365. Whenever a C function is called, its upvalues are located at specific
  1366. pseudo-indices. These pseudo-indices are produced by the macro
  1367. `lua_upvalueindex`. The first value associated with a function is at position
  1368. `lua_upvalueindex(1)`, and so on. Any access to `lua_upvalueindex(` `n` `)`,
  1369. where `n` is greater than the number of upvalues of the current function,
  1370. produces an acceptable (but invalid) index.
  1371. ==============================================================================
  1372. 3.5 Registry *luaref-registry* *luaref-apiRegistry*
  1373. Lua provides a registry, a pre-defined table that can be used by any C code to
  1374. store whatever Lua value it needs to store. This table is always located at
  1375. pseudo-index `LUA_REGISTRYINDEX`. Any C library can store data into this
  1376. table, but it should take care to choose keys different from those used by
  1377. other libraries, to avoid collisions. Typically, you should use as key a
  1378. string containing your library name or a light userdata with the address of a
  1379. C object in your code.
  1380. The integer keys in the registry are used by the reference mechanism,
  1381. implemented by the auxiliary library, and therefore should not be used for
  1382. other purposes.
  1383. ==============================================================================
  1384. 3.6 Error Handling in C *luaref-apiError*
  1385. Internally, Lua uses the C `longjmp` facility to handle errors. (You can also
  1386. choose to use exceptions if you use C++; see file `luaconf.h`.) When Lua faces
  1387. any error (such as memory allocation errors, type errors, syntax errors, and
  1388. runtime errors) it raises an error; that is, it does a long jump. A protected
  1389. environment uses `setjmp` to set a recover point; any error jumps to the most
  1390. recent active recover point.
  1391. Almost any function in the API may raise an error, for instance due to a
  1392. memory allocation error. The following functions run in protected mode (that
  1393. is, they create a protected environment to run), so they never raise an error:
  1394. `lua_newstate`, `lua_close`, `lua_load`, `lua_pcall`, and `lua_cpcall` (see
  1395. |lua_newstate()|, |lua_close()|, |lua_load()|,
  1396. |lua_pcall()|, and |lua_cpcall()|).
  1397. Inside a C function you can raise an error by calling `lua_error` (see
  1398. |lua_error()|).
  1399. ==============================================================================
  1400. 3.7 Functions and Types *luaref-apiFunctions*
  1401. Here we list all functions and types from the C API in alphabetical order.
  1402. lua_Alloc *lua_Alloc()*
  1403. >
  1404. typedef void * (*lua_Alloc) (void *ud,
  1405. void *ptr,
  1406. size_t osize,
  1407. size_t nsize);
  1408. <
  1409. The type of the memory-allocation function used by Lua states. The
  1410. allocator function must provide a functionality similar to `realloc`,
  1411. but not exactly the same. Its arguments are `ud`, an opaque pointer
  1412. passed to `lua_newstate` (see |lua_newstate()|); `ptr`, a pointer
  1413. to the block being allocated/reallocated/freed; `osize`, the original
  1414. size of the block; `nsize`, the new size of the block. `ptr` is `NULL`
  1415. if and only if `osize` is zero. When `nsize` is zero, the allocator
  1416. must return `NULL`; if `osize` is not zero, it should free the block
  1417. pointed to by `ptr`. When `nsize` is not zero, the allocator returns
  1418. `NULL` if and only if it cannot fill the request. When `nsize` is not
  1419. zero and `osize` is zero, the allocator should behave like `malloc`.
  1420. When `nsize` and `osize` are not zero, the allocator behaves like
  1421. `realloc`. Lua assumes that the allocator never fails when `osize >=
  1422. nsize`.
  1423. Here is a simple implementation for the allocator function. It is used
  1424. in the auxiliary library by `luaL_newstate` (see
  1425. |luaL_newstate()|).
  1426. >
  1427. static void *l_alloc (void *ud, void *ptr, size_t osize,
  1428. size_t nsize) {
  1429. (void)ud; (void)osize; /* not used */
  1430. if (nsize == 0) {
  1431. free(ptr);
  1432. return NULL;
  1433. }
  1434. else
  1435. return realloc(ptr, nsize);
  1436. }
  1437. <
  1438. This code assumes that `free(NULL)` has no effect and that
  1439. `realloc(NULL, size)` is equivalent to `malloc(size)`. ANSI C ensures both
  1440. behaviors.
  1441. lua_atpanic *lua_atpanic()*
  1442. >
  1443. lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);
  1444. <
  1445. Sets a new panic function and returns the old one.
  1446. If an error happens outside any protected environment, Lua calls a
  1447. `panic` `function` and then calls `exit(EXIT_FAILURE)`, thus exiting
  1448. the host application. Your panic function may avoid this exit by never
  1449. returning (e.g., doing a long jump).
  1450. The panic function can access the error message at the top of the
  1451. stack.
  1452. lua_call *lua_call()*
  1453. >
  1454. void lua_call (lua_State *L, int nargs, int nresults);
  1455. <
  1456. Calls a function.
  1457. To call a function you must use the following protocol: first, the
  1458. function to be called is pushed onto the stack; then, the arguments to
  1459. the function are pushed in direct order; that is, the first argument
  1460. is pushed first. Finally you call `lua_call`; `nargs` is the number of
  1461. arguments that you pushed onto the stack. All arguments and the
  1462. function value are popped from the stack when the function is called.
  1463. The function results are pushed onto the stack when the function
  1464. returns. The number of results is adjusted to `nresults`, unless
  1465. `nresults` is `LUA_MULTRET`. In this case, `all` results from the
  1466. function are pushed. Lua takes care that the returned values fit into
  1467. the stack space. The function results are pushed onto the stack in
  1468. direct order (the first result is pushed first), so that after the
  1469. call the last result is on the top of the stack.
  1470. Any error inside the called function is propagated upwards (with a
  1471. `longjmp`).
  1472. The following example shows how the host program may do the equivalent
  1473. to this Lua code:
  1474. >
  1475. a = f("how", t.x, 14)
  1476. <
  1477. Here it is in C:
  1478. >
  1479. lua_getfield(L, LUA_GLOBALSINDEX, "f"); // function to be called
  1480. lua_pushstring(L, "how"); // 1st argument
  1481. lua_getfield(L, LUA_GLOBALSINDEX, "t"); // table to be indexed
  1482. lua_getfield(L, -1, "x"); // push result of t.x (2nd arg)
  1483. lua_remove(L, -2); // remove 't' from the stack
  1484. lua_pushinteger(L, 14); // 3rd argument
  1485. lua_call(L, 3, 1); // call 'f' with 3 arguments and 1 result
  1486. lua_setfield(L, LUA_GLOBALSINDEX, "a"); // set global 'a'
  1487. <
  1488. Note that the code above is "balanced": at its end, the stack is back
  1489. to its original configuration. This is considered good programming
  1490. practice.
  1491. lua_CFunction *luaref-cfunction* *lua_CFunction()*
  1492. >
  1493. typedef int (*lua_CFunction) (lua_State *L);
  1494. <
  1495. Type for C functions.
  1496. In order to communicate properly with Lua, a C function must use the
  1497. following protocol, which defines the way parameters and results are
  1498. passed: a C function receives its arguments from Lua in its stack in
  1499. direct order (the first argument is pushed first). So, when the
  1500. function starts, `lua_gettop(L)` (see |lua_gettop()|) returns the
  1501. number of arguments received by the function. The first argument (if
  1502. any) is at index 1 and its last argument is at index `lua_gettop(L)`.
  1503. To return values to Lua, a C function just pushes them onto the stack,
  1504. in direct order (the first result is pushed first), and returns the
  1505. number of results. Any other value in the stack below the results will
  1506. be properly discarded by Lua. Like a Lua function, a C function called
  1507. by Lua can also return many results.
  1508. *luaref-cfunctionexample*
  1509. As an example, the following function receives a variable number of
  1510. numerical arguments and returns their average and sum:
  1511. >
  1512. static int foo (lua_State *L) {
  1513. int n = lua_gettop(L); /* number of arguments */
  1514. lua_Number sum = 0;
  1515. int i;
  1516. for (i = 1; i &lt;= n; i++) {
  1517. if (!lua_isnumber(L, i)) {
  1518. lua_pushstring(L, "incorrect argument");
  1519. lua_error(L);
  1520. }
  1521. sum += lua_tonumber(L, i);
  1522. }
  1523. lua_pushnumber(L, sum/n); /* first result */
  1524. lua_pushnumber(L, sum); /* second result */
  1525. return 2; /* number of results */
  1526. }
  1527. <
  1528. lua_checkstack *lua_checkstack()*
  1529. >
  1530. int lua_checkstack (lua_State *L, int extra);
  1531. <
  1532. Ensures that there are at least `extra` free stack slots in the stack.
  1533. It returns false if it cannot grow the stack to that size. This
  1534. function never shrinks the stack; if the stack is already larger than
  1535. the new size, it is left unchanged.
  1536. lua_close *lua_close()*
  1537. >
  1538. void lua_close (lua_State *L);
  1539. <
  1540. Destroys all objects in the given Lua state (calling the corresponding
  1541. garbage-collection metamethods, if any) and frees all dynamic memory
  1542. used by this state. On several platforms, you may not need to call
  1543. this function, because all resources are naturally released when the
  1544. host program ends. On the other hand, long-running programs, such as a
  1545. daemon or a web server, might need to release states as soon as they
  1546. are not needed, to avoid growing too large.
  1547. lua_concat *lua_concat()*
  1548. >
  1549. void lua_concat (lua_State *L, int n);
  1550. <
  1551. Concatenates the `n` values at the top of the stack, pops them, and
  1552. leaves the result at the top. If `n` is 1, the result is the single
  1553. string on the stack (that is, the function does nothing); if `n` is 0,
  1554. the result is the empty string. Concatenation is done following the
  1555. usual semantics of Lua (see |luaref-langConcat|).
  1556. lua_cpcall *lua_cpcall()*
  1557. >
  1558. int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);
  1559. <
  1560. Calls the C function `func` in protected mode. `func` starts with only
  1561. one element in its stack, a light userdata containing `ud`. In case of
  1562. errors, `lua_cpcall` returns the same error codes as `lua_pcall` (see
  1563. |lua_pcall()|), plus the error object on the top of the stack;
  1564. otherwise, it returns zero, and does not change the stack. All values
  1565. returned by `func` are discarded.
  1566. lua_createtable *lua_createtable()*
  1567. >
  1568. void lua_createtable (lua_State *L, int narr, int nrec);
  1569. <
  1570. Creates a new empty table and pushes it onto the stack. The new table
  1571. has space pre-allocated for `narr` array elements and `nrec` non-array
  1572. elements. This pre-allocation is useful when you know exactly how many
  1573. elements the table will have. Otherwise you can use the function
  1574. `lua_newtable` (see |lua_newtable()|).
  1575. lua_dump *lua_dump()*
  1576. >
  1577. int lua_dump (lua_State *L, lua_Writer writer, void *data);
  1578. <
  1579. Dumps a function as a binary chunk. Receives a Lua function on the top
  1580. of the stack and produces a binary chunk that, if loaded again,
  1581. results in a function equivalent to the one dumped. As it produces
  1582. parts of the chunk, `lua_dump` calls function `writer` (see
  1583. |lua_Writer()|) with the given `data` to write them.
  1584. The value returned is the error code returned by the last call to the
  1585. writer; 0 means no errors.
  1586. This function does not pop the Lua function from the stack.
  1587. lua_equal *lua_equal()*
  1588. >
  1589. int lua_equal (lua_State *L, int index1, int index2);
  1590. <
  1591. Returns 1 if the two values in acceptable indices `index1` and
  1592. `index2` are equal, following the semantics of the Lua `==` operator
  1593. (that is, may call metamethods). Otherwise returns 0. Also returns 0
  1594. if any of the indices is non valid.
  1595. lua_error *lua_error()*
  1596. >
  1597. int lua_error (lua_State *L);
  1598. <
  1599. Generates a Lua error. The error message (which can actually be a Lua
  1600. value of any type) must be on the stack top. This function does a long
  1601. jump, and therefore never returns (see |luaL_error()|).
  1602. lua_gc *lua_gc()*
  1603. >
  1604. int lua_gc (lua_State *L, int what, int data);
  1605. <
  1606. Controls the garbage collector.
  1607. This function performs several tasks, according to the value of the
  1608. parameter `what`:
  1609. - `LUA_GCSTOP` stops the garbage collector.
  1610. - `LUA_GCRESTART` restarts the garbage collector.
  1611. - `LUA_GCCOLLECT` performs a full garbage-collection cycle.
  1612. - `LUA_GCCOUNT` returns the current amount of memory (in Kbytes) in
  1613. use by Lua.
  1614. - `LUA_GCCOUNTB` returns the remainder of dividing the current
  1615. amount of bytes of memory in use by Lua by 1024.
  1616. - `LUA_GCSTEP` performs an incremental step of garbage collection.
  1617. The step "size" is controlled by `data` (larger
  1618. values mean more steps) in a non-specified way. If
  1619. you want to control the step size you must
  1620. experimentally tune the value of `data`. The
  1621. function returns 1 if the step finished a
  1622. garbage-collection cycle.
  1623. - `LUA_GCSETPAUSE` sets `data` /100 as the new value for the
  1624. `pause` of the collector (see |luaref-langGC|).
  1625. The function returns the previous value of the
  1626. pause.
  1627. - `LUA_GCSETSTEPMUL`sets `data` /100 as the new value for the
  1628. `step` `multiplier` of the collector (see
  1629. |luaref-langGC|). The function returns the
  1630. previous value of the step multiplier.
  1631. lua_getallocf *lua_getallocf()*
  1632. >
  1633. lua_Alloc lua_getallocf (lua_State *L, void **ud);
  1634. <
  1635. Returns the memory-allocation function of a given state. If `ud` is
  1636. not `NULL`, Lua stores in `*ud` the opaque pointer passed to
  1637. `lua_newstate` (see |lua_newstate()|).
  1638. lua_getfenv *lua_getfenv()*
  1639. >
  1640. void lua_getfenv (lua_State *L, int index);
  1641. <
  1642. Pushes onto the stack the environment table of the value at the given
  1643. index.
  1644. lua_getfield *lua_getfield()*
  1645. >
  1646. void lua_getfield (lua_State *L, int index, const char *k);
  1647. <
  1648. Pushes onto the stack the value `t[k]`, where `t` is the value at the
  1649. given valid index `index`. As in Lua, this function may trigger a
  1650. metamethod for the "index" event (see |luaref-langMetatables|).
  1651. lua_getglobal *lua_getglobal()*
  1652. >
  1653. void lua_getglobal (lua_State *L, const char *name);
  1654. <
  1655. Pushes onto the stack the value of the global `name`. It is defined as
  1656. a macro:
  1657. >
  1658. #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s)
  1659. <
  1660. lua_getmetatable *lua_getmetatable()*
  1661. >
  1662. int lua_getmetatable (lua_State *L, int index);
  1663. <
  1664. Pushes onto the stack the metatable of the value at the given
  1665. acceptable index. If the index is not valid, or if the value does not
  1666. have a metatable, the function returns 0 and pushes nothing on the
  1667. stack.
  1668. lua_gettable *lua_gettable()*
  1669. >
  1670. void lua_gettable (lua_State *L, int index);
  1671. <
  1672. Pushes onto the stack the value `t[k]`, where `t` is the value at the
  1673. given valid index `index` and `k` is the value at the top of the
  1674. stack.
  1675. This function pops the key from the stack (putting the resulting value
  1676. in its place). As in Lua, this function may trigger a metamethod for
  1677. the "index" event (see |luaref-langMetatables|).
  1678. lua_gettop *lua_gettop()*
  1679. >
  1680. int lua_gettop (lua_State *L);
  1681. <
  1682. Returns the index of the top element in the stack. Because indices
  1683. start at 1, this result is equal to the number of elements in the
  1684. stack (and so
  1685. 0 means an empty stack).
  1686. lua_insert *lua_insert()*
  1687. >
  1688. void lua_insert (lua_State *L, int index);
  1689. <
  1690. Moves the top element into the given valid index, shifting up the
  1691. elements above this index to open space. Cannot be called with a
  1692. pseudo-index, because a pseudo-index is not an actual stack position.
  1693. lua_Integer *lua_Integer()*
  1694. >
  1695. typedef ptrdiff_t lua_Integer;
  1696. <
  1697. The type used by the Lua API to represent integral values.
  1698. By default it is a `ptrdiff_t`, which is usually the largest integral
  1699. type the machine handles "comfortably".
  1700. lua_isboolean *lua_isboolean()*
  1701. >
  1702. int lua_isboolean (lua_State *L, int index);
  1703. <
  1704. Returns 1 if the value at the given acceptable index has type boolean,
  1705. and 0 otherwise.
  1706. lua_iscfunction *lua_iscfunction()*
  1707. >
  1708. int lua_iscfunction (lua_State *L, int index);
  1709. <
  1710. Returns 1 if the value at the given acceptable index is a C function,
  1711. and 0 otherwise.
  1712. lua_isfunction *lua_isfunction()*
  1713. >
  1714. int lua_isfunction (lua_State *L, int index);
  1715. <
  1716. Returns 1 if the value at the given acceptable index is a function
  1717. (either C or Lua), and 0 otherwise.
  1718. lua_islightuserdata *lua_islightuserdata()*
  1719. >
  1720. int lua_islightuserdata (lua_State *L, int index);
  1721. <
  1722. Returns 1 if the value at the given acceptable index is a light
  1723. userdata, and 0 otherwise.
  1724. lua_isnil *lua_isnil()*
  1725. >
  1726. int lua_isnil (lua_State *L, int index);
  1727. <
  1728. Returns 1 if the value at the given acceptable index is `nil`, and 0
  1729. otherwise.
  1730. lua_isnumber *lua_isnumber()*
  1731. >
  1732. int lua_isnumber (lua_State *L, int index);
  1733. <
  1734. Returns 1 if the value at the given acceptable index is a number or a
  1735. string convertible to a number, and 0 otherwise.
  1736. lua_isstring *lua_isstring()*
  1737. >
  1738. int lua_isstring (lua_State *L, int index);
  1739. <
  1740. Returns 1 if the value at the given acceptable index is a string or a
  1741. number (which is always convertible to a string), and 0 otherwise.
  1742. lua_istable *lua_istable()*
  1743. >
  1744. int lua_istable (lua_State *L, int index);
  1745. <
  1746. Returns 1 if the value at the given acceptable index is a table, and
  1747. 0 otherwise.
  1748. lua_isthread *lua_isthread()*
  1749. >
  1750. int lua_isthread (lua_State *L, int index);
  1751. <
  1752. Returns 1 if the value at the given acceptable index is a thread, and
  1753. 0 otherwise.
  1754. lua_isuserdata *lua_isuserdata()*
  1755. >
  1756. int lua_isuserdata (lua_State *L, int index);
  1757. <
  1758. Returns 1 if the value at the given acceptable index is a userdata
  1759. (either full or light), and 0 otherwise.
  1760. lua_lessthan *lua_lessthan()*
  1761. >
  1762. int lua_lessthan (lua_State *L, int index1, int index2);
  1763. <
  1764. Returns 1 if the value at acceptable index `index1` is smaller than
  1765. the value at acceptable index `index2`, following the semantics of the
  1766. Lua `<` operator (that is, may call metamethods). Otherwise returns 0.
  1767. Also returns 0 if any of the indices is non valid.
  1768. lua_load *lua_load()*
  1769. >
  1770. int lua_load (lua_State *L,
  1771. lua_Reader reader,
  1772. void *data,
  1773. const char *chunkname);
  1774. <
  1775. Loads a Lua chunk. If there are no errors, `lua_load` pushes the
  1776. compiled chunk as a Lua function on top of the stack. Otherwise, it
  1777. pushes an error message. The return values of `lua_load` are:
  1778. - `0`: no errors;
  1779. - `LUA_ERRSYNTAX` : syntax error during pre-compilation;
  1780. - `LUA_ERRMEM` : memory allocation error.
  1781. This function only loads a chunk; it does not run it.
  1782. `lua_load` automatically detects whether the chunk is text or binary,
  1783. and loads it accordingly (see program `luac`).
  1784. The `lua_load` function uses a user-supplied `reader` function to read
  1785. the chunk (see |lua_Reader()|). The `data` argument is an opaque
  1786. value passed to the reader function.
  1787. The `chunkname` argument gives a name to the chunk, which is used for
  1788. error messages and in debug information (see |luaref-apiDebug|).
  1789. lua_newstate *lua_newstate()*
  1790. >
  1791. lua_State *lua_newstate (lua_Alloc f, void *ud);
  1792. <
  1793. Creates a new, independent state. Returns `NULL` if cannot create the
  1794. state (due to lack of memory). The argument `f` is the allocator
  1795. function; Lua does all memory allocation for this state through this
  1796. function. The second argument, `ud`, is an opaque pointer that Lua
  1797. simply passes to the allocator in every call.
  1798. lua_newtable *lua_newtable()*
  1799. >
  1800. void lua_newtable (lua_State *L);
  1801. <
  1802. Creates a new empty table and pushes it onto the stack. It is
  1803. equivalent to `lua_createtable(L, 0, 0)` (see
  1804. |lua_createtable()|).
  1805. lua_newthread *lua_newthread()*
  1806. >
  1807. lua_State *lua_newthread (lua_State *L);
  1808. <
  1809. Creates a new thread, pushes it on the stack, and returns a pointer to
  1810. a `lua_State` (see |lua_State()|) that represents this new
  1811. thread. The new state returned by this function shares with the
  1812. original state all global objects (such as tables), but has an
  1813. independent execution stack.
  1814. There is no explicit function to close or to destroy a thread. Threads
  1815. are subject to garbage collection, like any Lua object.
  1816. lua_newuserdata *lua_newuserdata()*
  1817. >
  1818. void *lua_newuserdata (lua_State *L, size_t size);
  1819. <
  1820. This function allocates a new block of memory with the given size,
  1821. pushes onto the stack a new full userdata with the block address, and
  1822. returns this address.
  1823. *luaref-userdata*
  1824. Userdata represents C values in Lua. A full userdata represents a
  1825. block of memory. It is an object (like a table): you must create it,
  1826. it can have its own metatable, and you can detect when it is being
  1827. collected. A full userdata is only equal to itself (under raw
  1828. equality).
  1829. When Lua collects a full userdata with a `gc` metamethod, Lua calls
  1830. the metamethod and marks the userdata as finalized. When this userdata
  1831. is collected again then Lua frees its corresponding memory.
  1832. lua_next *lua_next()*
  1833. >
  1834. int lua_next (lua_State *L, int index);
  1835. <
  1836. Pops a key from the stack, and pushes a key-value pair from the table
  1837. at the given index (the "next" pair after the given key). If there are
  1838. no more elements in the table, then `lua_next` returns 0 (and pushes
  1839. nothing).
  1840. *luaref-tabletraversal*
  1841. A typical traversal looks like this:
  1842. >
  1843. /* table is in the stack at index 't' */
  1844. lua_pushnil(L); /* first key */
  1845. while (lua_next(L, t) != 0) {
  1846. /* uses 'key' (at index -2) and 'value' (at index -1) */
  1847. printf("%s - %s\n",
  1848. lua_typename(L, lua_type(L, -2)),
  1849. lua_typename(L, lua_type(L, -1)));
  1850. /* removes 'value'; keeps 'key' for next iteration */
  1851. lua_pop(L, 1);
  1852. }
  1853. <
  1854. While traversing a table, do not call `lua_tolstring` (see
  1855. |lua_tolstring()|) directly on a key, unless you know that the
  1856. key is actually a string. Recall that `lua_tolstring` `changes` the
  1857. value at the given index; this confuses the next call to `lua_next`.
  1858. lua_Number *lua_Number()*
  1859. >
  1860. typedef double lua_Number;
  1861. <
  1862. The type of numbers in Lua. By default, it is double, but that can be
  1863. changed in `luaconf.h`.
  1864. Through the configuration file you can change Lua to operate with
  1865. another type for numbers (e.g., float or long).
  1866. lua_objlen *lua_objlen()*
  1867. >
  1868. size_t lua_objlen (lua_State *L, int index);
  1869. <
  1870. Returns the "length" of the value at the given acceptable index: for
  1871. strings, this is the string length; for tables, this is the result of
  1872. the length operator (`#`); for userdata, this is the size of the
  1873. block of memory allocated for the userdata; for other values, it is 0.
  1874. lua_pcall *lua_pcall()*
  1875. >
  1876. lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);
  1877. <
  1878. Calls a function in protected mode.
  1879. Both `nargs` and `nresults` have the same meaning as in `lua_call`
  1880. (see |lua_call()|). If there are no errors during the call,
  1881. `lua_pcall` behaves exactly like `lua_call`. However, if there is any
  1882. error, `lua_pcall` catches it, pushes a single value on the stack (the
  1883. error message), and returns an error code. Like `lua_call`,
  1884. `lua_pcall` always removes the function and its arguments from the
  1885. stack.
  1886. If `errfunc` is 0, then the error message returned on the stack is
  1887. exactly the original error message. Otherwise, `errfunc` is the stack
  1888. index of an `error` `handler function`. (In the current
  1889. implementation, this index cannot be a pseudo-index.) In case of
  1890. runtime errors, this function will be called with the error message
  1891. and its return value will be the message returned on the stack by
  1892. `lua_pcall`.
  1893. Typically, the error handler function is used to add more debug
  1894. information to the error message, such as a stack traceback. Such
  1895. information cannot be gathered after the return of `lua_pcall`, since
  1896. by then the stack has unwound.
  1897. The `lua_pcall` function returns 0 in case of success or one of the
  1898. following error codes (defined in `lua.h`):
  1899. - `LUA_ERRRUN` a runtime error.
  1900. - `LUA_ERRMEM` memory allocation error. For such errors, Lua does
  1901. not call the error handler function.
  1902. - `LUA_ERRERR` error while running the error handler function.
  1903. lua_pop *lua_pop()*
  1904. >
  1905. void lua_pop (lua_State *L, int n);
  1906. <
  1907. Pops `n` elements from the stack.
  1908. lua_pushboolean *lua_pushboolean()*
  1909. >
  1910. void lua_pushboolean (lua_State *L, int b);
  1911. <
  1912. Pushes a boolean value with value `b` onto the stack.
  1913. lua_pushcclosure *lua_pushcclosure()*
  1914. >
  1915. void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
  1916. <
  1917. Pushes a new C closure onto the stack.
  1918. When a C function is created, it is possible to associate some values
  1919. with it, thus creating a C closure (see |luaref-apiCClosures|); these
  1920. values are then accessible to the function whenever it is called. To
  1921. associate values with a C function, first these values should be
  1922. pushed onto the stack (when there are multiple values, the first value
  1923. is pushed first). Then `lua_pushcclosure` is called to create and push
  1924. the C function onto the stack, with the argument `n` telling how many
  1925. values should be associated with the function. `lua_pushcclosure` also
  1926. pops these values from the stack.
  1927. lua_pushcfunction *lua_pushcfunction()*
  1928. >
  1929. void lua_pushcfunction (lua_State *L, lua_CFunction f);
  1930. <
  1931. Pushes a C function onto the stack. This function receives a pointer
  1932. to a C function and pushes onto the stack a Lua value of type
  1933. `function` that, when called, invokes the corresponding C function.
  1934. Any function to be registered in Lua must follow the correct protocol
  1935. to receive its parameters and return its results (see
  1936. |lua_CFunction()|).
  1937. `lua_pushcfunction` is defined as a macro:
  1938. >
  1939. #define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0)
  1940. <
  1941. lua_pushfstring *lua_pushfstring()*
  1942. >
  1943. const char *lua_pushfstring (lua_State *L, const char *fmt, ...);
  1944. <
  1945. Pushes onto the stack a formatted string and returns a pointer to this
  1946. string. It is similar to the C function `sprintf`, but has some
  1947. important differences:
  1948. - You do not have to allocate space for the result: the result is a
  1949. Lua string and Lua takes care of memory allocation (and
  1950. deallocation, through garbage collection).
  1951. - The conversion specifiers are quite restricted. There are no flags,
  1952. widths, or precisions. The conversion specifiers can only be `%%`
  1953. (inserts a `%` in the string), `%s` (inserts a zero-terminated
  1954. string, with no size restrictions), `%f` (inserts a
  1955. `lua_Number`), `%p` (inserts a pointer as a hexadecimal numeral),
  1956. `%d` (inserts an `int`), and `%c` (inserts an `int` as a
  1957. character).
  1958. lua_pushinteger *lua_pushinteger()*
  1959. >
  1960. void lua_pushinteger (lua_State *L, lua_Integer n);
  1961. <
  1962. Pushes a number with value `n` onto the stack.
  1963. lua_pushlightuserdata *lua_pushlightuserdata()*
  1964. >
  1965. void lua_pushlightuserdata (lua_State *L, void *p);
  1966. <
  1967. Pushes a light userdata onto the stack.
  1968. *luaref-lightuserdata*
  1969. Userdata represents C values in Lua. A light userdata represents a
  1970. pointer. It is a value (like a number): you do not create it, it has
  1971. no individual metatable, and it is not collected (as it was never
  1972. created). A light userdata is equal to "any" light userdata with the
  1973. same C address.
  1974. lua_pushlstring *lua_pushlstring()*
  1975. >
  1976. void lua_pushlstring (lua_State *L, const char *s, size_t len);
  1977. <
  1978. Pushes the string pointed to by `s` with size `len` onto the stack.
  1979. Lua makes (or reuses) an internal copy of the given string, so the
  1980. memory at `s` can be freed or reused immediately after the function
  1981. returns. The string can contain embedded zeros.
  1982. lua_pushnil *lua_pushnil()*
  1983. >
  1984. void lua_pushnil (lua_State *L);
  1985. <
  1986. Pushes a nil value onto the stack.
  1987. lua_pushnumber *lua_pushnumber()*
  1988. >
  1989. void lua_pushnumber (lua_State *L, lua_Number n);
  1990. <
  1991. Pushes a number with value `n` onto the stack.
  1992. lua_pushstring *lua_pushstring()*
  1993. >
  1994. void lua_pushstring (lua_State *L, const char *s);
  1995. <
  1996. Pushes the zero-terminated string pointed to by `s` onto the stack.
  1997. Lua makes (or reuses) an internal copy of the given string, so the
  1998. memory at `s` can be freed or reused immediately after the function
  1999. returns. The string cannot contain embedded zeros; it is assumed to
  2000. end at the first zero.
  2001. lua_pushthread *lua_pushthread()*
  2002. >
  2003. int lua_pushthread (lua_State *L);
  2004. <
  2005. Pushes the thread represented by `L` onto the stack. Returns 1 if this
  2006. thread is the main thread of its state.
  2007. lua_pushvalue *lua_pushvalue()*
  2008. >
  2009. void lua_pushvalue (lua_State *L, int index);
  2010. <
  2011. Pushes a copy of the element at the given valid index onto the stack.
  2012. lua_pushvfstring *lua_pushvfstring()*
  2013. >
  2014. const char *lua_pushvfstring (lua_State *L,
  2015. const char *fmt,
  2016. va_list argp);
  2017. <
  2018. Equivalent to `lua_pushfstring` (see |lua_pushfstring()|), except
  2019. that it receives a `va_list` instead of a variable number of
  2020. arguments.
  2021. lua_rawequal *lua_rawequal()*
  2022. >
  2023. int lua_rawequal (lua_State *L, int index1, int index2);
  2024. <
  2025. Returns 1 if the two values in acceptable indices `index1` and
  2026. `index2` are primitively equal (that is, without calling metamethods).
  2027. Otherwise returns 0. Also returns 0 if any of the indices are non
  2028. valid.
  2029. lua_rawget *lua_rawget()*
  2030. >
  2031. void lua_rawget (lua_State *L, int index);
  2032. <
  2033. Similar to `lua_gettable` (see |lua_gettable()|), but does a raw
  2034. access (i.e., without metamethods).
  2035. lua_rawgeti *lua_rawgeti()*
  2036. >
  2037. void lua_rawgeti (lua_State *L, int index, int n);
  2038. <
  2039. Pushes onto the stack the value `t[n]`, where `t` is the value at the
  2040. given valid index `index`. The access is raw; that is, it does not
  2041. invoke metamethods.
  2042. lua_rawset *lua_rawset()*
  2043. >
  2044. void lua_rawset (lua_State *L, int index);
  2045. <
  2046. Similar to `lua_settable` (see |lua_settable()|), but does a raw
  2047. assignment (i.e., without metamethods).
  2048. lua_rawseti *lua_rawseti()*
  2049. >
  2050. void lua_rawseti (lua_State *L, int index, int n);
  2051. <
  2052. Does the equivalent of `t[n] = v`, where `t` is the value at the given
  2053. valid index `index` and `v` is the value at the top of the stack.
  2054. This function pops the value from the stack. The assignment is raw;
  2055. that is, it does not invoke metamethods.
  2056. lua_Reader *lua_Reader()*
  2057. >
  2058. typedef const char * (*lua_Reader) (lua_State *L,
  2059. void *data,
  2060. size_t *size);
  2061. <
  2062. The reader function used by `lua_load` (see |lua_load()|). Every
  2063. time it needs another piece of the chunk, `lua_load` calls the reader,
  2064. passing along its `data` parameter. The reader must return a pointer
  2065. to a block of memory with a new piece of the chunk and set `size` to
  2066. the block size. The block must exist until the reader function is
  2067. called again. To signal the end of the chunk, the reader must return
  2068. `NULL`. The reader function may return pieces of any size greater than
  2069. zero.
  2070. lua_register *lua_register()*
  2071. >
  2072. void lua_register (lua_State *L,
  2073. const char *name,
  2074. lua_CFunction f);
  2075. <
  2076. Sets the C function `f` as the new value of global `name`. It is
  2077. defined as a macro:
  2078. >
  2079. #define lua_register(L,n,f) \
  2080. (lua_pushcfunction(L, f), lua_setglobal(L, n))
  2081. <
  2082. lua_remove *lua_remove()*
  2083. >
  2084. void lua_remove (lua_State *L, int index);
  2085. <
  2086. Removes the element at the given valid index, shifting down the
  2087. elements above this index to fill the gap. Cannot be called with a
  2088. pseudo-index, because a pseudo-index is not an actual stack position.
  2089. lua_replace *lua_replace()*
  2090. >
  2091. void lua_replace (lua_State *L, int index);
  2092. <
  2093. Moves the top element into the given position (and pops it), without
  2094. shifting any element (therefore replacing the value at the given
  2095. position).
  2096. lua_resume *lua_resume()*
  2097. >
  2098. int lua_resume (lua_State *L, int narg);
  2099. <
  2100. Starts and resumes a coroutine in a given thread.
  2101. To start a coroutine, you first create a new thread (see
  2102. |lua_newthread()|); then you push onto its stack the main
  2103. function plus any arguments; then you call `lua_resume` (see
  2104. |lua_resume()|) with `narg` being the number of arguments. This
  2105. call returns when the coroutine suspends or finishes its execution.
  2106. When it returns, the stack contains all values passed to `lua_yield`
  2107. (see |lua_yield()|), or all values returned by the body function.
  2108. `lua_resume` returns `LUA_YIELD` if the coroutine yields, 0 if the
  2109. coroutine finishes its execution without errors, or an error code in
  2110. case of errors (see |lua_pcall()|). In case of errors, the stack
  2111. is not unwound, so you can use the debug API over it. The error
  2112. message is on the top of the stack. To restart a coroutine, you put on
  2113. its stack only the values to be passed as results from `lua_yield`,
  2114. and then call `lua_resume`.
  2115. lua_setallocf *lua_setallocf()*
  2116. >
  2117. void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);
  2118. <
  2119. Changes the allocator function of a given state to `f` with user data
  2120. `ud`.
  2121. lua_setfenv *lua_setfenv()*
  2122. >
  2123. int lua_setfenv (lua_State *L, int index);
  2124. <
  2125. Pops a table from the stack and sets it as the new environment for the
  2126. value at the given index. If the value at the given index is neither a
  2127. function nor a thread nor a userdata, `lua_setfenv` returns 0.
  2128. Otherwise it returns 1.
  2129. lua_setfield *lua_setfield()*
  2130. >
  2131. void lua_setfield (lua_State *L, int index, const char *k);
  2132. <
  2133. Does the equivalent to `t[k] = v`, where `t` is the value at the given
  2134. valid index `index` and `v` is the value at the top of the stack.
  2135. This function pops the value from the stack. As in Lua, this function
  2136. may trigger a metamethod for the "newindex" event (see
  2137. |luaref-langMetatables|).
  2138. lua_setglobal *lua_setglobal()*
  2139. >
  2140. void lua_setglobal (lua_State *L, const char *name);
  2141. <
  2142. Pops a value from the stack and sets it as the new value of global
  2143. `name`. It is defined as a macro:
  2144. >
  2145. #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s)
  2146. <
  2147. lua_setmetatable *lua_setmetatable()*
  2148. >
  2149. int lua_setmetatable (lua_State *L, int index);
  2150. <
  2151. Pops a table from the stack and sets it as the new metatable for the
  2152. value at the given acceptable index.
  2153. lua_settable *lua_settable()*
  2154. >
  2155. void lua_settable (lua_State *L, int index);
  2156. <
  2157. Does the equivalent to `t[k] = v`, where `t` is the value at the given
  2158. valid index `index`, `v` is the value at the top of the stack, and `k`
  2159. is the value just below the top.
  2160. This function pops both the key and the value from the stack. As in
  2161. Lua, this function may trigger a metamethod for the "newindex" event
  2162. (see |luaref-langMetatables|).
  2163. lua_settop *lua_settop()*
  2164. >
  2165. void lua_settop (lua_State *L, int index);
  2166. <
  2167. Accepts any acceptable index, or 0, and sets the stack top to this
  2168. index. If the new top is larger than the old one, then the new
  2169. elements are filled with `nil`. If `index` is 0, then all stack
  2170. elements are removed.
  2171. lua_State *lua_State()*
  2172. >
  2173. typedef struct lua_State lua_State;
  2174. <
  2175. Opaque structure that keeps the whole state of a Lua interpreter. The
  2176. Lua library is fully reentrant: it has no global variables. All
  2177. information about a state is kept in this structure.
  2178. A pointer to this state must be passed as the first argument to every
  2179. function in the library, except to `lua_newstate` (see
  2180. |lua_newstate()|), which creates a Lua state from scratch.
  2181. lua_status *lua_status()*
  2182. >
  2183. int lua_status (lua_State *L);
  2184. <
  2185. Returns the status of the thread `L`.
  2186. The status can be 0 for a normal thread, an error code if the thread
  2187. finished its execution with an error, or `LUA_YIELD` if the thread is
  2188. suspended.
  2189. lua_toboolean *lua_toboolean()*
  2190. >
  2191. int lua_toboolean (lua_State *L, int index);
  2192. <
  2193. Converts the Lua value at the given acceptable index to a C boolean
  2194. value (0 or 1). Like all tests in Lua, `lua_toboolean` returns 1 for
  2195. any Lua value different from `false` and `nil`; otherwise it returns
  2196. 0. It also returns 0 when called with a non-valid index. (If you want
  2197. to accept only actual boolean values, use `lua_isboolean`
  2198. |lua_isboolean()| to test the value's type.)
  2199. lua_tocfunction *lua_tocfunction()*
  2200. >
  2201. lua_CFunction lua_tocfunction (lua_State *L, int index);
  2202. <
  2203. Converts a value at the given acceptable index to a C function. That
  2204. value must be a C function; otherwise it returns `NULL`.
  2205. lua_tointeger *lua_tointeger()*
  2206. >
  2207. lua_Integer lua_tointeger (lua_State *L, int idx);
  2208. <
  2209. Converts the Lua value at the given acceptable index to the signed
  2210. integral type `lua_Integer` (see |lua_Integer()|). The Lua value
  2211. must be a number or a string convertible to a number (see
  2212. |luaref-langCoercion|); otherwise, `lua_tointeger` returns 0.
  2213. If the number is not an integer, it is truncated in some non-specified
  2214. way.
  2215. lua_tolstring *lua_tolstring()*
  2216. >
  2217. const char *lua_tolstring (lua_State *L, int index, size_t *len);
  2218. <
  2219. Converts the Lua value at the given acceptable index to a C string. If
  2220. `len` is not `NULL`, it also sets `*len` with the string length. The
  2221. Lua value must be a string or a number; otherwise, the function
  2222. returns `NULL`. If the value is a number, then `lua_tolstring` also
  2223. `changes the actual value in the stack to a` `string`. (This change
  2224. confuses `lua_next` |lua_next()| when `lua_tolstring` is applied
  2225. to keys during a table traversal.)
  2226. `lua_tolstring` returns a fully aligned pointer to a string inside the
  2227. Lua state. This string always has a zero (`\0`) after its last
  2228. character (as in C), but may contain other zeros in its body. Because
  2229. Lua has garbage collection, there is no guarantee that the pointer
  2230. returned by `lua_tolstring` will be valid after the corresponding
  2231. value is removed from the stack.
  2232. lua_tonumber *lua_tonumber()*
  2233. >
  2234. lua_Number lua_tonumber (lua_State *L, int index);
  2235. <
  2236. Converts the Lua value at the given acceptable index to the C type
  2237. `lua_Number` (see |lua_Number()|). The Lua value must be a number
  2238. or a string convertible to a number (see |luaref-langCoercion|);
  2239. otherwise, `lua_tonumber` returns 0.
  2240. lua_topointer *lua_topointer()*
  2241. >
  2242. const void *lua_topointer (lua_State *L, int index);
  2243. <
  2244. Converts the value at the given acceptable index to a generic C
  2245. pointer (`void*`). The value may be a userdata, a table, a thread, or
  2246. a function; otherwise, `lua_topointer` returns `NULL`. Different
  2247. objects will give different pointers. There is no way to convert the
  2248. pointer back to its original value.
  2249. Typically this function is used only for debug information.
  2250. lua_tostring *lua_tostring()*
  2251. >
  2252. const char *lua_tostring (lua_State *L, int index);
  2253. <
  2254. Equivalent to `lua_tolstring` (see |lua_tolstring()|) with `len`
  2255. equal to `NULL`.
  2256. lua_tothread *lua_tothread()*
  2257. >
  2258. lua_State *lua_tothread (lua_State *L, int index);
  2259. <
  2260. Converts the value at the given acceptable index to a Lua thread
  2261. (represented as `lua_State*` |lua_State()|). This value must be a
  2262. thread; otherwise, the function returns `NULL`.
  2263. lua_touserdata *lua_touserdata()*
  2264. >
  2265. void *lua_touserdata (lua_State *L, int index);
  2266. <
  2267. If the value at the given acceptable index is a full userdata, returns
  2268. its block address. If the value is a light userdata, returns its
  2269. pointer. Otherwise, it returns `NULL`.
  2270. lua_type *lua_type()*
  2271. >
  2272. int lua_type (lua_State *L, int index);
  2273. <
  2274. Returns the type of the value in the given acceptable index, or
  2275. `LUA_TNONE` for a non-valid index (that is, an index to an "empty"
  2276. stack position). The types returned by `lua_type` are coded by the
  2277. following constants defined in `lua.h` : `LUA_TNIL`, `LUA_TNUMBER`,
  2278. `LUA_TBOOLEAN`, `LUA_TSTRING`, `LUA_TTABLE`, `LUA_TFUNCTION`,
  2279. `LUA_TUSERDATA`, `LUA_TTHREAD`, and `LUA_TLIGHTUSERDATA`.
  2280. lua_typename *lua_typename()*
  2281. >
  2282. const char *lua_typename (lua_State *L, int tp);
  2283. <
  2284. Returns the name of the type encoded by the value `tp`, which must be
  2285. one the values returned by `lua_type`.
  2286. lua_Writer *lua_Writer()*
  2287. >
  2288. typedef int (*lua_Writer) (lua_State *L,
  2289. const void* p,
  2290. size_t sz,
  2291. void* ud);
  2292. <
  2293. The writer function used by `lua_dump` (see |lua_dump()|). Every
  2294. time it produces another piece of chunk, `lua_dump` calls the writer,
  2295. passing along the buffer to be written (`p`), its size (`sz`), and the
  2296. `data` parameter supplied to `lua_dump`.
  2297. The writer returns an error code: 0 means no errors; any other value
  2298. means an error and stops `lua_dump` from calling the writer again.
  2299. lua_xmove *lua_xmove()*
  2300. >
  2301. void lua_xmove (lua_State *from, lua_State *to, int n);
  2302. <
  2303. Exchange values between different threads of the `same` global state.
  2304. This function pops `n` values from the stack `from`, and pushes them
  2305. onto the stack `to`.
  2306. lua_yield *lua_yield()*
  2307. >
  2308. int lua_yield (lua_State *L, int nresults);
  2309. <
  2310. Yields a coroutine.
  2311. This function should only be called as the return expression of a C
  2312. function, as follows:
  2313. >
  2314. return lua_yield (L, nresults);
  2315. <
  2316. When a C function calls `lua_yield` in that way, the running coroutine
  2317. suspends its execution, and the call to `lua_resume` (see
  2318. |lua_resume()|) that started this coroutine returns. The
  2319. parameter `nresults` is the number of values from the stack that are
  2320. passed as results to `lua_resume`.
  2321. *luaref-stackexample*
  2322. As an example of stack manipulation, if the stack starts as
  2323. `10 20 30 40 50*` (from bottom to top; the `*` marks the top), then
  2324. >
  2325. lua_pushvalue(L, 3) --> 10 20 30 40 50 30*
  2326. lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30*
  2327. lua_remove(L, -3) --> 10 20 30 40 30 30*
  2328. lua_remove(L, 6) --> 10 20 30 40 30*
  2329. lua_insert(L, 1) --> 30 10 20 30 40*
  2330. lua_insert(L, -1) --> 30 10 20 30 40* (no effect)
  2331. lua_replace(L, 2) --> 30 40 20 30*
  2332. lua_settop(L, -3) --> 30 40*
  2333. lua_settop(L, 6) --> 30 40 nil nil nil nil*
  2334. <
  2335. ==============================================================================
  2336. 3.8 The Debug Interface *luaref-apiDebug*
  2337. Lua has no built-in debugging facilities. Instead, it offers a special
  2338. interface by means of functions and hooks. This interface allows the
  2339. construction of different kinds of debuggers, profilers, and other tools that
  2340. need "inside information" from the interpreter.
  2341. lua_Debug *lua_Debug()*
  2342. >
  2343. typedef struct lua_Debug {
  2344. int event;
  2345. const char *name; /* (n) */
  2346. const char *namewhat; /* (n) */
  2347. const char *what; /* (S) */
  2348. const char *source; /* (S) */
  2349. int currentline; /* (l) */
  2350. int nups; /* (u) number of upvalues */
  2351. int linedefined; /* (S) */
  2352. int lastlinedefined; /* (S) */
  2353. char short_src[LUA_IDSIZE]; /* (S) */
  2354. /* private part */
  2355. other fields
  2356. } lua_Debug;
  2357. <
  2358. A structure used to carry different pieces of information about an active
  2359. function. `lua_getstack` (see |lua_getstack()|) fills only the private part
  2360. of this structure, for later use. To fill the other fields of `lua_Debug` with
  2361. useful information, call `lua_getinfo` (see |lua_getinfo()|).
  2362. The fields of `lua_Debug` have the following meaning:
  2363. - `source` If the function was defined in a string, then `source` is
  2364. that string. If the function was defined in a file, then
  2365. `source` starts with a `@` followed by the file name.
  2366. - `short_src` a "printable" version of `source`, to be used in error messages.
  2367. - `linedefined` the line number where the definition of the function starts.
  2368. - `lastlinedefined` the line number where the definition of the function ends.
  2369. - `what` the string `"Lua"` if the function is a Lua function,
  2370. `"C"` if it is a C function, `"main"` if it is the main
  2371. part of a chunk, and `"tail"` if it was a function that
  2372. did a tail call. In the latter case, Lua has no other
  2373. information about the function.
  2374. - `currentline` the current line where the given function is executing.
  2375. When no line information is available, `currentline` is
  2376. set to -1.
  2377. - `name` a reasonable name for the given function. Because
  2378. functions in Lua are first-class values, they do not have
  2379. a fixed name: some functions may be the value of multiple
  2380. global variables, while others may be stored only in a
  2381. table field. The `lua_getinfo` function checks how the
  2382. function was called to find a suitable name. If it cannot
  2383. find a name, then `name` is set to `NULL`.
  2384. - `namewhat` explains the `name` field. The value of `namewhat` can be
  2385. `"global"`, `"local"`, `"method"`, `"field"`,
  2386. `"upvalue"`, or `""` (the empty string), according to how
  2387. the function was called. (Lua uses the empty string when
  2388. no other option seems to apply.) `nups` the number of
  2389. upvalues of the function.
  2390. lua_gethook *lua_gethook()*
  2391. >
  2392. lua_Hook lua_gethook (lua_State *L);
  2393. <
  2394. Returns the current hook function.
  2395. lua_gethookcount *lua_gethookcount()*
  2396. >
  2397. int lua_gethookcount (lua_State *L);
  2398. <
  2399. Returns the current hook count.
  2400. lua_gethookmask *lua_gethookmask()*
  2401. >
  2402. int lua_gethookmask (lua_State *L);
  2403. <
  2404. Returns the current hook mask.
  2405. lua_getinfo *lua_getinfo()*
  2406. >
  2407. int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
  2408. <
  2409. Returns information about a specific function or function invocation.
  2410. To get information about a function invocation, the parameter `ar`
  2411. must be a valid activation record that was filled by a previous call
  2412. to `lua_getstack` (see |lua_getstack()|) or given as argument to
  2413. a hook (see |lua_Hook()|).
  2414. To get information about a function you push it onto the stack and
  2415. start the `what` string with the character `>`. (In that case,
  2416. `lua_getinfo` pops the function in the top of the stack.) For
  2417. instance, to know in which line a function `f` was defined, you can
  2418. write the following code:
  2419. >
  2420. lua_Debug ar;
  2421. lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global 'f' */
  2422. lua_getinfo(L, ">S", &ar);
  2423. printf("%d\n", ar.linedefined);
  2424. <
  2425. Each character in the string `what` selects some fields of the
  2426. structure `ar` to be filled or a value to be pushed on the stack:
  2427. `'n'` fills in the field `name` and `namewhat`
  2428. `'S'` fills in the fields `source`, `short_src`, `linedefined`,
  2429. `lastlinedefined`, and `what`
  2430. `'l'` fills in the field `currentline`
  2431. `'u'` fills in the field `nups`
  2432. `'f'` pushes onto the stack the function that is running at the
  2433. given level
  2434. `'L'` pushes onto the stack a table whose indices are the numbers
  2435. of the lines that are valid on the function. (A `valid line` is a
  2436. line with some associated code, that is, a line where you can put
  2437. a break point. Non-valid lines include empty lines and comments.)
  2438. This function returns 0 on error (for instance, an invalid option in
  2439. `what`).
  2440. lua_getlocal *lua_getlocal()*
  2441. >
  2442. const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);
  2443. <
  2444. Gets information about a local variable of a given activation record.
  2445. The parameter `ar` must be a valid activation record that was filled
  2446. by a previous call to `lua_getstack` (see |lua_getstack()|) or
  2447. given as argument to a hook (see |lua_Hook()|). The index `n`
  2448. selects which local variable to inspect (1 is the first parameter or
  2449. active local variable, and so on, until the last active local
  2450. variable). `lua_getlocal` pushes the variable's value onto the stack
  2451. and returns its name.
  2452. Variable names starting with `(` (open parentheses) represent
  2453. internal variables (loop control variables, temporaries, and C
  2454. function locals).
  2455. Returns `NULL` (and pushes nothing) when the index is greater than the
  2456. number of active local variables.
  2457. lua_getstack *lua_getstack()*
  2458. >
  2459. int lua_getstack (lua_State *L, int level, lua_Debug *ar);
  2460. <
  2461. Gets information about the interpreter runtime stack.
  2462. This function fills parts of a `lua_Debug` (see |lua_Debug()|)
  2463. structure with an identification of the `activation record` of the
  2464. function executing at a given level. Level 0 is the current running
  2465. function, whereas level `n+1` is the function that has called level
  2466. `n`. When there are no errors, `lua_getstack` returns 1; when called
  2467. with a level greater than the stack depth, it returns 0.
  2468. lua_getupvalue *lua_getupvalue()*
  2469. >
  2470. const char *lua_getupvalue (lua_State *L, int funcindex, int n);
  2471. <
  2472. Gets information about a closure's upvalue. (For Lua functions,
  2473. upvalues are the external local variables that the function uses, and
  2474. that are consequently included in its closure.) `lua_getupvalue` gets
  2475. the index `n` of an upvalue, pushes the upvalue's value onto the
  2476. stack, and returns its name. `funcindex` points to the closure in the
  2477. stack. (Upvalues have no particular order, as they are active through
  2478. the whole function. So, they are numbered in an arbitrary order.)
  2479. Returns `NULL` (and pushes nothing) when the index is greater than the
  2480. number of upvalues. For C functions, this function uses the empty
  2481. string `""` as a name for all upvalues.
  2482. lua_Hook *lua_Hook()*
  2483. >
  2484. typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
  2485. <
  2486. Type for debugging hook functions.
  2487. Whenever a hook is called, its `ar` argument has its field `event` set
  2488. to the specific event that triggered the hook. Lua identifies these
  2489. events with the following constants: `LUA_HOOKCALL`, `LUA_HOOKRET`,
  2490. `LUA_HOOKTAILRET`, `LUA_HOOKLINE`, and `LUA_HOOKCOUNT`. Moreover, for
  2491. line events, the field `currentline` is also set. To get the value of
  2492. any other field in `ar`, the hook must call `lua_getinfo` (see
  2493. |lua_getinfo()|). For return events, `event` may be
  2494. `LUA_HOOKRET`, the normal value, or `LUA_HOOKTAILRET`. In the latter
  2495. case, Lua is simulating a return from a function that did a tail call;
  2496. in this case, it is useless to call `lua_getinfo`.
  2497. While Lua is running a hook, it disables other calls to hooks.
  2498. Therefore, if a hook calls back Lua to execute a function or a chunk,
  2499. this execution occurs without any calls to hooks.
  2500. lua_sethook *lua_sethook()*
  2501. >
  2502. int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);
  2503. <
  2504. Sets the debugging hook function.
  2505. Argument `f` is the hook function. `mask` specifies on which events
  2506. the hook will be called: it is formed by a bitwise `or` of the
  2507. constants `LUA_MASKCALL`, `LUA_MASKRET`, `LUA_MASKLINE`, and
  2508. `LUA_MASKCOUNT`. The `count` argument is only meaningful when the mask
  2509. includes `LUA_MASKCOUNT`. For each event, the hook is called as
  2510. explained below:
  2511. - `The call hook`: is called when the interpreter calls a function.
  2512. The hook is called just after Lua enters the new function, before
  2513. the function gets its arguments.
  2514. - `The return hook`: is called when the interpreter returns from a
  2515. function. The hook is called just before Lua leaves the function.
  2516. You have no access to the values to be returned by the function.
  2517. - `The line hook`: is called when the interpreter is about to start
  2518. the execution of a new line of code, or when it jumps back in the
  2519. code (even to the same line). (This event only happens while Lua is
  2520. executing a Lua function.)
  2521. - `The count hook`: is called after the interpreter executes every
  2522. `count` instructions. (This event only happens while Lua is
  2523. executing a Lua function.)
  2524. A hook is disabled by setting `mask` to zero.
  2525. lua_setlocal *lua_setlocal()*
  2526. >
  2527. const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);
  2528. <
  2529. Sets the value of a local variable of a given activation record.
  2530. Parameters `ar` and `n` are as in `lua_getlocal` (see
  2531. |lua_getlocal()|). `lua_setlocal` assigns the value at the top of
  2532. the stack to the variable and returns its name. It also pops the value
  2533. from the stack.
  2534. Returns `NULL` (and pops nothing) when the index is greater than the
  2535. number of active local variables.
  2536. lua_setupvalue *lua_setupvalue()*
  2537. >
  2538. const char *lua_setupvalue (lua_State *L, int funcindex, int n);
  2539. <
  2540. Sets the value of a closure's upvalue. It assigns the value at the top
  2541. of the stack to the upvalue and returns its name. It also pops the
  2542. value from the stack. Parameters `funcindex` and `n` are as in the
  2543. `lua_getupvalue` (see |lua_getupvalue()|).
  2544. Returns `NULL` (and pops nothing) when the index is greater than the
  2545. number of upvalues.
  2546. *luaref-debugexample*
  2547. As an example, the following function lists the names of all local
  2548. variables and upvalues for a function at a given level of the stack:
  2549. >
  2550. int listvars (lua_State *L, int level) {
  2551. lua_Debug ar;
  2552. int i;
  2553. const char *name;
  2554. if (lua_getstack(L, level, &ar) == 0)
  2555. return 0; /* failure: no such level in the stack */
  2556. i = 1;
  2557. while ((name = lua_getlocal(L, &ar, i++)) != NULL) {
  2558. printf("local %d %s\n", i-1, name);
  2559. lua_pop(L, 1); /* remove variable value */
  2560. }
  2561. lua_getinfo(L, "f", &ar); /* retrieves function */
  2562. i = 1;
  2563. while ((name = lua_getupvalue(L, -1, i++)) != NULL) {
  2564. printf("upvalue %d %s\n", i-1, name);
  2565. lua_pop(L, 1); /* remove upvalue value */
  2566. }
  2567. return 1;
  2568. }
  2569. <
  2570. ==============================================================================
  2571. 4 THE AUXILIARY LIBRARY *luaref-aux*
  2572. The auxiliary library provides several convenient functions to interface C
  2573. with Lua. While the basic API provides the primitive functions for all
  2574. interactions between C and Lua, the auxiliary library provides higher-level
  2575. functions for some common tasks.
  2576. All functions from the auxiliary library are defined in header file `lauxlib.h`
  2577. and have a prefix `luaL_`.
  2578. All functions in the auxiliary library are built on top of the basic API, and
  2579. so they provide nothing that cannot be done with this API.
  2580. Several functions in the auxiliary library are used to check C function
  2581. arguments. Their names are always `luaL_check*` or `luaL_opt*`. All of these
  2582. functions raise an error if the check is not satisfied. Because the error
  2583. message is formatted for arguments (e.g., "bad argument #1"), you should not
  2584. use these functions for other stack values.
  2585. ==============================================================================
  2586. 4.1 Functions and Types *luaref-auxFunctions*
  2587. Here we list all functions and types from the auxiliary library in
  2588. alphabetical order.
  2589. luaL_addchar *luaL_addchar()*
  2590. >
  2591. void luaL_addchar (luaL_Buffer *B, char c);
  2592. <
  2593. Adds the character `c` to the buffer `B` (see |luaL_Buffer()|).
  2594. luaL_addlstring *luaL_addlstring()*
  2595. >
  2596. void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);
  2597. <
  2598. Adds the string pointed to by `s` with length `l` to the buffer `B`
  2599. (see |luaL_Buffer()|). The string may contain embedded zeros.
  2600. luaL_addsize *luaL_addsize()*
  2601. >
  2602. void luaL_addsize (luaL_Buffer *B, size_t n);
  2603. <
  2604. Adds to the buffer `B` (see |luaL_Buffer()|) a string of length
  2605. `n` previously copied to the buffer area (see
  2606. |luaL_prepbuffer()|).
  2607. luaL_addstring *luaL_addstring()*
  2608. >
  2609. void luaL_addstring (luaL_Buffer *B, const char *s);
  2610. <
  2611. Adds the zero-terminated string pointed to by `s` to the buffer `B`
  2612. (see |luaL_Buffer()|). The string may not contain embedded zeros.
  2613. luaL_addvalue *luaL_addvalue()*
  2614. >
  2615. void luaL_addvalue (luaL_Buffer *B);
  2616. <
  2617. Adds the value at the top of the stack to the buffer `B` (see
  2618. |luaL_Buffer()|). Pops the value.
  2619. This is the only function on string buffers that can (and must) be
  2620. called with an extra element on the stack, which is the value to be
  2621. added to the buffer.
  2622. luaL_argcheck *luaL_argcheck()*
  2623. >
  2624. void luaL_argcheck (lua_State *L,
  2625. int cond,
  2626. int narg,
  2627. const char *extramsg);
  2628. <
  2629. Checks whether `cond` is true. If not, raises an error with the
  2630. following message, where `func` is retrieved from the call stack:
  2631. >
  2632. bad argument #<narg> to <func> (<extramsg>)
  2633. <
  2634. luaL_argerror *luaL_argerror()*
  2635. >
  2636. int luaL_argerror (lua_State *L, int narg, const char *extramsg);
  2637. <
  2638. Raises an error with the following message, where `func` is retrieved
  2639. from the call stack:
  2640. >
  2641. bad argument #<narg> to <func> (<extramsg>)
  2642. <
  2643. This function never returns, but it is an idiom to use it in C
  2644. functions as `return luaL_argerror(` `args` `)`.
  2645. luaL_Buffer *luaL_Buffer()*
  2646. >
  2647. typedef struct luaL_Buffer luaL_Buffer;
  2648. <
  2649. Type for a `string buffer`.
  2650. A string buffer allows C code to build Lua strings piecemeal. Its
  2651. pattern of use is as follows:
  2652. - First you declare a variable `b` of type `luaL_Buffer`.
  2653. - Then you initialize it with a call `luaL_buffinit(L, &b)` (see
  2654. |luaL_buffinit()|).
  2655. - Then you add string pieces to the buffer calling any of the
  2656. `luaL_add*` functions.
  2657. - You finish by calling `luaL_pushresult(&b)` (see
  2658. |luaL_pushresult()|). This call leaves the final string on the
  2659. top of the stack.
  2660. During its normal operation, a string buffer uses a variable number of
  2661. stack slots. So, while using a buffer, you cannot assume that you know
  2662. where the top of the stack is. You can use the stack between
  2663. successive calls to buffer operations as long as that use is balanced;
  2664. that is, when you call a buffer operation, the stack is at the same
  2665. level it was immediately after the previous buffer operation. (The
  2666. only exception to this rule is `luaL_addvalue`
  2667. |luaL_addvalue()|.) After calling `luaL_pushresult` the stack is
  2668. back to its level when the buffer was initialized, plus the final
  2669. string on its top.
  2670. luaL_buffinit *luaL_buffinit()*
  2671. >
  2672. void luaL_buffinit (lua_State *L, luaL_Buffer *B);
  2673. <
  2674. Initializes a buffer `B`. This function does not allocate any space;
  2675. the buffer must be declared as a variable (see |luaL_Buffer()|).
  2676. luaL_callmeta *luaL_callmeta()*
  2677. >
  2678. int luaL_callmeta (lua_State *L, int obj, const char *e);
  2679. <
  2680. Calls a metamethod.
  2681. If the object at index `obj` has a metatable and this metatable has a
  2682. field `e`, this function calls this field and passes the object as its
  2683. only argument. In this case this function returns 1 and pushes onto
  2684. the stack the value returned by the call. If there is no metatable or
  2685. no metamethod, this function returns
  2686. 0 (without pushing any value on the stack).
  2687. luaL_checkany *luaL_checkany()*
  2688. >
  2689. void luaL_checkany (lua_State *L, int narg);
  2690. <
  2691. Checks whether the function has an argument of any type (including
  2692. `nil`) at position `narg`.
  2693. luaL_checkint *luaL_checkint()*
  2694. >
  2695. int luaL_checkint (lua_State *L, int narg);
  2696. <
  2697. Checks whether the function argument `narg` is a number and returns
  2698. this number cast to an `int`.
  2699. luaL_checkinteger *luaL_checkinteger()*
  2700. >
  2701. lua_Integer luaL_checkinteger (lua_State *L, int narg);
  2702. <
  2703. Checks whether the function argument `narg` is a number and returns
  2704. this number cast to a `lua_Integer` (see |lua_Integer()|).
  2705. luaL_checklong *luaL_checklong()*
  2706. >
  2707. long luaL_checklong (lua_State *L, int narg);
  2708. <
  2709. Checks whether the function argument `narg` is a number and returns
  2710. this number cast to a `long`.
  2711. luaL_checklstring *luaL_checklstring()*
  2712. >
  2713. const char *luaL_checklstring (lua_State *L, int narg, size_t *l);
  2714. <
  2715. Checks whether the function argument `narg` is a string and returns
  2716. this string; if `l` is not `NULL` fills `*l` with the string's length.
  2717. luaL_checknumber *luaL_checknumber()*
  2718. >
  2719. lua_Number luaL_checknumber (lua_State *L, int narg);
  2720. <
  2721. Checks whether the function argument `narg` is a number and returns
  2722. this number (see |lua_Number()|).
  2723. luaL_checkoption *luaL_checkoption()*
  2724. >
  2725. int luaL_checkoption (lua_State *L,
  2726. int narg,
  2727. const char *def,
  2728. const char *const lst[]);
  2729. <
  2730. Checks whether the function argument `narg` is a string and searches
  2731. for this string in the array `lst` (which must be NULL-terminated).
  2732. Returns the index in the array where the string was found. Raises an
  2733. error if the argument is not a string or if the string cannot be
  2734. found.
  2735. If `def` is not `NULL`, the function uses `def` as a default value
  2736. when there is no argument `narg` or if this argument is `nil`.
  2737. This is a useful function for mapping strings to C enums. (The usual
  2738. convention in Lua libraries is to use strings instead of numbers to
  2739. select options.)
  2740. luaL_checkstack *luaL_checkstack()*
  2741. >
  2742. void luaL_checkstack (lua_State *L, int sz, const char *msg);
  2743. <
  2744. Grows the stack size to `top + sz` elements, raising an error if the
  2745. stack cannot grow to that size. `msg` is an additional text to go into
  2746. the error message.
  2747. luaL_checkstring *luaL_checkstring()*
  2748. >
  2749. const char *luaL_checkstring (lua_State *L, int narg);
  2750. <
  2751. Checks whether the function argument `narg` is a string and returns
  2752. this string.
  2753. luaL_checktype *luaL_checktype()*
  2754. >
  2755. void luaL_checktype (lua_State *L, int narg, int t);
  2756. <
  2757. Checks whether the function argument `narg` has type `t` (see
  2758. |lua_type()|).
  2759. luaL_checkudata *luaL_checkudata()*
  2760. >
  2761. void *luaL_checkudata (lua_State *L, int narg, const char *tname);
  2762. <
  2763. Checks whether the function argument `narg` is a userdata of the type
  2764. `tname` (see |luaL_newmetatable()|).
  2765. luaL_dofile *luaL_dofile()*
  2766. >
  2767. int luaL_dofile (lua_State *L, const char *filename);
  2768. <
  2769. Loads and runs the given file. It is defined as the following macro:
  2770. >
  2771. (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
  2772. <
  2773. It returns 0 if there are no errors or 1 in case of errors.
  2774. luaL_dostring *luaL_dostring()*
  2775. >
  2776. int luaL_dostring (lua_State *L, const char *str);
  2777. <
  2778. Loads and runs the given string. It is defined as the following macro:
  2779. >
  2780. (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
  2781. <
  2782. It returns 0 if there are no errors or 1 in case of errors.
  2783. luaL_error *luaL_error()*
  2784. >
  2785. int luaL_error (lua_State *L, const char *fmt, ...);
  2786. <
  2787. Raises an error. The error message format is given by `fmt` plus any
  2788. extra arguments, following the same rules of `lua_pushfstring` (see
  2789. |lua_pushfstring()|). It also adds at the beginning of the
  2790. message the file name and the line number where the error occurred, if
  2791. this information is available.
  2792. This function never returns, but it is an idiom to use it in C
  2793. functions as `return luaL_error(` `args` `)`.
  2794. luaL_getmetafield *luaL_getmetafield()*
  2795. >
  2796. int luaL_getmetafield (lua_State *L, int obj, const char *e);
  2797. <
  2798. Pushes onto the stack the field `e` from the metatable of the object
  2799. at index `obj`. If the object does not have a metatable, or if the
  2800. metatable does not have this field, returns 0 and pushes nothing.
  2801. luaL_getmetatable *luaL_getmetatable()*
  2802. >
  2803. void luaL_getmetatable (lua_State *L, const char *tname);
  2804. <
  2805. Pushes onto the stack the metatable associated with name `tname` in
  2806. the registry (see |luaL_newmetatable()|).
  2807. luaL_gsub *luaL_gsub()*
  2808. >
  2809. const char *luaL_gsub (lua_State *L,
  2810. const char *s,
  2811. const char *p,
  2812. const char *r);
  2813. <
  2814. Creates a copy of string `s` by replacing any occurrence of the string
  2815. `p` with the string `r`. Pushes the resulting string on the stack and
  2816. returns it.
  2817. luaL_loadbuffer *luaL_loadbuffer()*
  2818. >
  2819. int luaL_loadbuffer (lua_State *L,
  2820. const char *buff,
  2821. size_t sz,
  2822. const char *name);
  2823. <
  2824. Loads a buffer as a Lua chunk. This function uses `lua_load` (see
  2825. |lua_load()|) to load the chunk in the buffer pointed to by
  2826. `buff` with size `sz`.
  2827. This function returns the same results as `lua_load`. `name` is the
  2828. chunk name, used for debug information and error messages.
  2829. luaL_loadfile *luaL_loadfile()*
  2830. >
  2831. int luaL_loadfile (lua_State *L, const char *filename);
  2832. <
  2833. Loads a file as a Lua chunk. This function uses `lua_load` (see
  2834. |lua_load()|) to load the chunk in the file named `filename`. If
  2835. `filename` is `NULL`, then it loads from the standard input. The first
  2836. line in the file is ignored if it starts with a `#`.
  2837. This function returns the same results as `lua_load`, but it has an
  2838. extra error code `LUA_ERRFILE` if it cannot open/read the file.
  2839. As `lua_load`, this function only loads the chunk; it does not run it.
  2840. luaL_loadstring *luaL_loadstring()*
  2841. >
  2842. int luaL_loadstring (lua_State *L, const char *s);
  2843. <
  2844. Loads a string as a Lua chunk. This function uses `lua_load` (see
  2845. |lua_load()|) to load the chunk in the zero-terminated string
  2846. `s`.
  2847. This function returns the same results as `lua_load`.
  2848. Also as `lua_load`, this function only loads the chunk; it does not
  2849. run it.
  2850. luaL_newmetatable *luaL_newmetatable()*
  2851. >
  2852. int luaL_newmetatable (lua_State *L, const char *tname);
  2853. <
  2854. If the registry already has the key `tname`, returns 0. Otherwise,
  2855. creates a new table to be used as a metatable for userdata, adds it to
  2856. the registry with key `tname`, and returns 1.
  2857. In both cases pushes onto the stack the final value associated with
  2858. `tname` in the registry.
  2859. luaL_newstate *luaL_newstate()*
  2860. >
  2861. lua_State *luaL_newstate (void);
  2862. <
  2863. Creates a new Lua state. It calls `lua_newstate` (see
  2864. |lua_newstate()|) with an allocator based on the standard C
  2865. `realloc` function and then sets a panic function (see
  2866. |lua_atpanic()|) that prints an error message to the standard
  2867. error output in case of fatal errors.
  2868. Returns the new state, or `NULL` if there is a memory allocation
  2869. error.
  2870. luaL_openlibs *luaL_openlibs()*
  2871. >
  2872. void luaL_openlibs (lua_State *L);
  2873. <
  2874. Opens all standard Lua libraries into the given state. See also
  2875. |luaref-openlibs| for details on how to open individual libraries.
  2876. luaL_optint *luaL_optint()*
  2877. >
  2878. int luaL_optint (lua_State *L, int narg, int d);
  2879. <
  2880. If the function argument `narg` is a number, returns this number cast
  2881. to an `int`. If this argument is absent or is `nil`, returns `d`.
  2882. Otherwise, raises an error.
  2883. luaL_optinteger *luaL_optinteger()*
  2884. >
  2885. lua_Integer luaL_optinteger (lua_State *L,
  2886. int narg,
  2887. lua_Integer d);
  2888. <
  2889. If the function argument `narg` is a number, returns this number cast
  2890. to a `lua_Integer` (see |lua_Integer()|). If this argument is
  2891. absent or is `nil`, returns `d`. Otherwise, raises an error.
  2892. luaL_optlong *luaL_optlong()*
  2893. >
  2894. long luaL_optlong (lua_State *L, int narg, long d);
  2895. <
  2896. If the function argument `narg` is a number, returns this number cast
  2897. to a `long`. If this argument is absent or is `nil`, returns `d`.
  2898. Otherwise, raises an error.
  2899. luaL_optlstring *luaL_optlstring()*
  2900. >
  2901. const char *luaL_optlstring (lua_State *L,
  2902. int narg,
  2903. const char *d,
  2904. size_t *l);
  2905. <
  2906. If the function argument `narg` is a string, returns this string. If
  2907. this argument is absent or is `nil`, returns `d`. Otherwise, raises an
  2908. error.
  2909. If `l` is not `NULL`, fills the position `*l` with the results' length.
  2910. luaL_optnumber *luaL_optnumber()*
  2911. >
  2912. lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);
  2913. <
  2914. If the function argument `narg` is a number, returns this number. If
  2915. this argument is absent or is `nil`, returns `d`. Otherwise, raises an
  2916. error.
  2917. luaL_optstring *luaL_optstring()*
  2918. >
  2919. const char *luaL_optstring (lua_State *L,
  2920. int narg,
  2921. const char *d);
  2922. <
  2923. If the function argument `narg` is a string, returns this string. If
  2924. this argument is absent or is `nil`, returns `d`. Otherwise, raises an
  2925. error.
  2926. luaL_prepbuffer *luaL_prepbuffer()*
  2927. >
  2928. char *luaL_prepbuffer (luaL_Buffer *B);
  2929. <
  2930. Returns an address to a space of size `LUAL_BUFFERSIZE` where you can
  2931. copy a string to be added to buffer `B` (see |luaL_Buffer()|).
  2932. After copying the string into this space you must call `luaL_addsize`
  2933. (see |luaL_addsize()|) with the size of the string to actually
  2934. add it to the buffer.
  2935. luaL_pushresult *luaL_pushresult()*
  2936. >
  2937. void luaL_pushresult (luaL_Buffer *B);
  2938. <
  2939. Finishes the use of buffer `B` leaving the final string on the top of
  2940. the stack.
  2941. luaL_ref *luaL_ref()*
  2942. >
  2943. int luaL_ref (lua_State *L, int t);
  2944. <
  2945. Creates and returns a `reference`, in the table at index `t`, for the
  2946. object at the top of the stack (and pops the object).
  2947. A reference is a unique integer key. As long as you do not manually
  2948. add integer keys into table `t`, `luaL_ref` ensures the uniqueness of
  2949. the key it returns. You can retrieve an object referred by reference
  2950. `r` by calling `lua_rawgeti(L, t, r)` (see |lua_rawgeti()|).
  2951. Function `luaL_unref` (see |luaL_unref()|) frees a reference and
  2952. its associated object.
  2953. If the object at the top of the stack is `nil`, `luaL_ref` returns the
  2954. constant `LUA_REFNIL`. The constant `LUA_NOREF` is guaranteed to be
  2955. different from any reference returned by `luaL_ref`.
  2956. luaL_Reg *luaL_Reg()*
  2957. >
  2958. typedef struct luaL_Reg {
  2959. const char *name;
  2960. lua_CFunction func;
  2961. } luaL_Reg;
  2962. <
  2963. Type for arrays of functions to be registered by `luaL_register` (see
  2964. |luaL_register()|). `name` is the function name and `func` is a
  2965. pointer to the function. Any array of `luaL_Reg` must end with a
  2966. sentinel entry in which both `name` and `func` are `NULL`.
  2967. luaL_register *luaL_register()*
  2968. >
  2969. void luaL_register (lua_State *L,
  2970. const char *libname,
  2971. const luaL_Reg *l);
  2972. <
  2973. Opens a library.
  2974. When called with `libname` equal to `NULL`, it simply registers all
  2975. functions in the list `l` (see |luaL_Reg()|) into the table on
  2976. the top of the stack.
  2977. When called with a non-null `libname`, `luaL_register` creates a new
  2978. table `t`, sets it as the value of the global variable `libname`, sets
  2979. it as the value of `package.loaded[libname]`, and registers on it all
  2980. functions in the list `l`. If there is a table in
  2981. `package.loaded[libname]` or in variable `libname`, reuses this table
  2982. instead of creating a new one.
  2983. In any case the function leaves the table on the top of the stack.
  2984. luaL_typename *luaL_typename()*
  2985. >
  2986. const char *luaL_typename (lua_State *L, int idx);
  2987. <
  2988. Returns the name of the type of the value at index `idx`.
  2989. luaL_typerror *luaL_typerror()*
  2990. >
  2991. int luaL_typerror (lua_State *L, int narg, const char *tname);
  2992. <
  2993. Generates an error with a message like the following:
  2994. `location` `: bad argument` `narg` `to` `'func'` `(` `tname`
  2995. `expected, got` `rt` `)`
  2996. where `location` is produced by `luaL_where` (see
  2997. |luaL_where()|), `func` is the name of the current function, and
  2998. `rt` is the type name of the actual argument.
  2999. luaL_unref *luaL_unref()*
  3000. >
  3001. void luaL_unref (lua_State *L, int t, int ref);
  3002. <
  3003. Releases reference `ref` from the table at index `t` (see
  3004. |luaL_ref()|). The entry is removed from the table, so that the
  3005. referred object can be collected. The reference `ref` is also freed to
  3006. be used again.
  3007. If `ref` is `LUA_NOREF` or `LUA_REFNIL`, `luaL_unref` does nothing.
  3008. luaL_where *luaL_where()*
  3009. >
  3010. void luaL_where (lua_State *L, int lvl);
  3011. <
  3012. Pushes onto the stack a string identifying the current position of the
  3013. control at level `lvl` in the call stack. Typically this string has
  3014. the following format:
  3015. `chunkname:currentline:`
  3016. Level 0 is the running function, level 1 is the function that called
  3017. the running function, etc.
  3018. This function is used to build a prefix for error messages.
  3019. ==============================================================================
  3020. 5 STANDARD LIBRARIES *luaref-Lib*
  3021. The standard libraries provide useful functions that are implemented directly
  3022. through the C API. Some of these functions provide essential services to the
  3023. language (e.g., `type` and `getmetatable`); others provide access to "outside"
  3024. services (e.g., I/O); and others could be implemented in Lua itself, but are
  3025. quite useful or have critical performance requirements that deserve an
  3026. implementation in C (e.g., `sort`).
  3027. All libraries are implemented through the official C API and are provided as
  3028. separate C modules. Currently, Lua has the following standard libraries:
  3029. - basic library;
  3030. - package library;
  3031. - string manipulation;
  3032. - table manipulation;
  3033. - mathematical functions (sin, log, etc.);
  3034. - input and output;
  3035. - operating system facilities;
  3036. - debug facilities.
  3037. Except for the basic and package libraries, each library provides all its
  3038. functions as fields of a global table or as methods of its objects.
  3039. *luaref-openlibs*
  3040. To have access to these libraries, the C host program should call the
  3041. `luaL_openlibs` function, which opens all standard libraries (see
  3042. |luaL_openlibs()|). Alternatively, the host program can open the libraries
  3043. individually by calling `luaopen_base` (for the basic library),
  3044. `luaopen_package` (for the package library), `luaopen_string` (for the string
  3045. library), `luaopen_table` (for the table library), `luaopen_math` (for the
  3046. mathematical library), `luaopen_io` (for the I/O and the Operating System
  3047. libraries), and `luaopen_debug` (for the debug library). These functions are
  3048. declared in `lualib.h` and should not be called directly: you must call them
  3049. like any other Lua C function, e.g., by using `lua_call` (see |lua_call()|).
  3050. ==============================================================================
  3051. 5.1 Basic Functions *luaref-libBasic*
  3052. The basic library provides some core functions to Lua. If you do not include
  3053. this library in your application, you should check carefully whether you need
  3054. to provide implementations for some of its facilities.
  3055. assert({v} [, {message}]) *luaref-assert()*
  3056. Issues an error when the value of its argument `v` is false (i.e., `nil` or
  3057. `false`); otherwise, returns all its arguments. `message` is an error message;
  3058. when absent, it defaults to "assertion failed!"
  3059. collectgarbage({opt} [, {arg}]) *luaref-collectgarbage()*
  3060. This function is a generic interface to the garbage collector. It
  3061. performs different functions according to its first argument, {opt}:
  3062. `"stop"` stops the garbage collector.
  3063. `"restart"` restarts the garbage collector.
  3064. `"collect"` performs a full garbage-collection cycle.
  3065. `"count"` returns the total memory in use by Lua (in Kbytes).
  3066. `"step"` performs a garbage-collection step. The step "size" is
  3067. controlled by {arg} (larger values mean more steps) in a
  3068. non-specified way. If you want to control the step size
  3069. you must experimentally tune the value of {arg}. Returns
  3070. `true` if the step finished a collection cycle.
  3071. `"setpause"` sets {arg} /100 as the new value for the `pause` of
  3072. the collector (see |luaref-langGC|).
  3073. `"setstepmul"` sets {arg} /100 as the new value for the `step
  3074. multiplier` of the collector (see |luaref-langGC|).
  3075. dofile({filename}) *luaref-dofile()*
  3076. Opens the named file and executes its contents as a Lua chunk. When
  3077. called without arguments, `dofile` executes the contents of the
  3078. standard input (`stdin`). Returns all values returned by the chunk. In
  3079. case of errors, `dofile` propagates the error to its caller (that is,
  3080. `dofile` does not run in protected mode).
  3081. error({message} [, {level}]) *luaref-error()*
  3082. Terminates the last protected function called and returns `message` as
  3083. the error message. Function {error} never returns.
  3084. Usually, {error} adds some information about the error position at the
  3085. beginning of the message. The {level} argument specifies how to get
  3086. the error position. With level 1 (the default), the error position is
  3087. where the {error} function was called. Level 2 points the error to
  3088. where the function that called {error} was called; and so on. Passing
  3089. a level 0 avoids the addition of error position information to the
  3090. message.
  3091. _G *luaref-_G()*
  3092. A global variable (not a function) that holds the global environment
  3093. (that is, `_G._G = _G`). Lua itself does not use this variable;
  3094. changing its value does not affect any environment, nor vice-versa.
  3095. (Use `setfenv` to change environments.)
  3096. getfenv({f}) *luaref-getfenv()*
  3097. Returns the current environment in use by the function. {f} can be a
  3098. Lua function or a number that specifies the function at that stack
  3099. level: Level 1 is the function calling `getfenv`. If the given
  3100. function is not a Lua function, or if {f} is 0, `getfenv` returns the
  3101. global environment. The default for {f} is 1.
  3102. getmetatable({object}) *luaref-getmetatable()*
  3103. If {object} does not have a metatable, returns `nil`. Otherwise, if
  3104. the object's metatable has a `"__metatable"` field, returns the
  3105. associated value. Otherwise, returns the metatable of the given
  3106. object.
  3107. ipairs({t}) *luaref-ipairs()*
  3108. Returns three values: an iterator function, the table {t}, and 0, so
  3109. that the construction
  3110. `for i,v in ipairs(t) do` `body` `end`
  3111. will iterate over the pairs (`1,t[1]`), (`2,t[2]`), ..., up to the
  3112. first integer key absent from the table.
  3113. load({func} [, {chunkname}]) *luaref-load()*
  3114. Loads a chunk using function {func} to get its pieces. Each call to
  3115. {func} must return a string that concatenates with previous results. A
  3116. return of `nil` (or no value) signals the end of the chunk.
  3117. If there are no errors, returns the compiled chunk as a function;
  3118. otherwise, returns `nil` plus the error message. The environment of
  3119. the returned function is the global environment.
  3120. {chunkname} is used as the chunk name for error messages and debug
  3121. information.
  3122. loadfile([{filename}]) *luaref-loadfile()*
  3123. Similar to `load` (see |luaref-load()|), but gets the chunk from file
  3124. {filename} or from the standard input, if no file name is given.
  3125. loadstring({string} [, {chunkname}]) *luaref-loadstring()*
  3126. Similar to `load` (see |luaref-load()|), but gets the chunk from the
  3127. given {string}.
  3128. To load and run a given string, use the idiom
  3129. >
  3130. assert(loadstring(s))()
  3131. <
  3132. next({table} [, {index}]) *luaref-next()*
  3133. Allows a program to traverse all fields of a table. Its first argument
  3134. is a table and its second argument is an index in this table. `next`
  3135. returns the next index of the table and its associated value. When
  3136. called with `nil` as its second argument, `next` returns an initial
  3137. index and its associated value. When called with the last index, or
  3138. with `nil` in an empty table, `next` returns `nil`. If the second
  3139. argument is absent, then it is interpreted as `nil`. In particular,
  3140. you can use `next(t)` to check whether a table is empty.
  3141. The order in which the indices are enumerated is not specified, `even
  3142. for` `numeric indices`. (To traverse a table in numeric order, use a
  3143. numerical `for` or the `ipairs` |luaref-ipairs()| function.)
  3144. The behavior of `next` is `undefined` if, during the traversal, you
  3145. assign any value to a non-existent field in the table. You may however
  3146. modify existing fields. In particular, you may clear existing fields.
  3147. pairs({t}) *luaref-pairs()*
  3148. Returns three values: the `next` |luaref-next()| function, the table
  3149. {t}, and `nil`, so that the construction
  3150. `for k,v in pairs(t) do` `body` `end`
  3151. will iterate over all key-value pairs of table {t}.
  3152. pcall({f}, {arg1}, {...}) *luaref-pcall()*
  3153. Calls function {f} with the given arguments in `protected mode`. This
  3154. means that any error inside {f} is not propagated; instead, `pcall`
  3155. catches the error and returns a status code. Its first result is the
  3156. status code (a boolean), which is `true` if the call succeeds without
  3157. errors. In such case, `pcall` also returns all results from the call,
  3158. after this first result. In case of any error, `pcall` returns `false`
  3159. plus the error message.
  3160. print({...}) *luaref-print()*
  3161. Receives any number of arguments, and prints their values to `stdout`,
  3162. using the `tostring` |luaref-tostring()| function to convert them to
  3163. strings. `print` is not intended for formatted output, but only as a
  3164. quick way to show a value, typically for debugging. For formatted
  3165. output, use `string.format` (see |string.format()|).
  3166. rawequal({v1}, {v2}) *luaref-rawequal()*
  3167. Checks whether {v1} is equal to {v2}, without invoking any metamethod.
  3168. Returns a boolean.
  3169. rawget({table}, {index}) *luaref-rawget()*
  3170. Gets the real value of `table[index]`, without invoking any
  3171. metamethod. {table} must be a table; {index} may be any value.
  3172. rawset({table}, {index}, {value}) *luaref-rawset()*
  3173. Sets the real value of `table[index]` to {value}, without invoking any
  3174. metamethod. {table} must be a table, {index} any value different from
  3175. `nil`, and {value} any Lua value.
  3176. This function returns {table}.
  3177. select({index}, {...}) *luaref-select()*
  3178. If {index} is a number, returns all arguments after argument number
  3179. {index}. Otherwise, {index} must be the string `"#"`, and `select`
  3180. returns the total number of extra arguments it received.
  3181. setfenv({f}, {table}) *luaref-setfenv()*
  3182. Sets the environment to be used by the given function. {f} can be a
  3183. Lua function or a number that specifies the function at that stack
  3184. level: Level 1 is the function calling `setfenv`. `setfenv` returns
  3185. the given function.
  3186. As a special case, when {f} is 0 `setfenv` changes the environment of
  3187. the running thread. In this case, `setfenv` returns no values.
  3188. setmetatable({table}, {metatable}) *luaref-setmetatable()*
  3189. Sets the metatable for the given table. (You cannot change the
  3190. metatable of other types from Lua, only from C.) If {metatable} is
  3191. `nil`, removes the metatable of the given table. If the original
  3192. metatable has a `"__metatable"` field, raises an error.
  3193. This function returns {table}.
  3194. tonumber({e} [, {base}]) *luaref-tonumber()*
  3195. Tries to convert its argument to a number. If the argument is already
  3196. a number or a string convertible to a number, then `tonumber` returns
  3197. this number; otherwise, it returns `nil`.
  3198. An optional argument specifies the base to interpret the numeral. The
  3199. base may be any integer between 2 and 36, inclusive. In bases above
  3200. 10, the letter `A` (in either upper or lower case) represents 10, `B`
  3201. represents 11, and so forth, with `Z'` representing 35. In base 10
  3202. (the default), the number may have a decimal part, as well as an
  3203. optional exponent part (see |luaref-langLexConv|). In other bases,
  3204. only unsigned integers are accepted.
  3205. tostring({e}) *luaref-tostring()*
  3206. Receives an argument of any type and converts it to a string in a
  3207. reasonable format. For complete control of how numbers are converted,
  3208. use `string.format` (see |string.format()|).
  3209. *__tostring*
  3210. If the metatable of {e} has a `"__tostring"` field, `tostring` calls
  3211. the corresponding value with {e} as argument, and uses the result of
  3212. the call as its result.
  3213. type({v}) *luaref-type()*
  3214. Returns the type of its only argument, coded as a string. The possible
  3215. results of this function are `"nil"` (a string, not the value `nil`),
  3216. `"number"`, `"string"`, `"boolean`, `"table"`, `"function"`,
  3217. `"thread"`, and `"userdata"`.
  3218. unpack({list} [, {i} [, {j}]]) *luaref-unpack()*
  3219. Returns the elements from the given table. This function is equivalent
  3220. to
  3221. >
  3222. return list[i], list[i+1], ..., list[j]
  3223. <
  3224. except that the above code can be written only for a fixed number of
  3225. elements. By default, {i} is 1 and {j} is the length of the list, as
  3226. defined by the length operator(see |luaref-langLength|).
  3227. _VERSION *luaref-_VERSION()*
  3228. A global variable (not a function) that holds a string containing the
  3229. current interpreter version. The current contents of this string is
  3230. `"Lua 5.1"` .
  3231. xpcall({f}, {err}) *luaref-xpcall()*
  3232. This function is similar to `pcall` (see |luaref-pcall()|), except that
  3233. you can set a new error handler.
  3234. `xpcall` calls function {f} in protected mode, using {err} as the
  3235. error handler. Any error inside {f} is not propagated; instead,
  3236. `xpcall` catches the error, calls the {err} function with the original
  3237. error object, and returns a status code. Its first result is the
  3238. status code (a boolean), which is true if the call succeeds without
  3239. errors. In this case, `xpcall` also returns all results from the call,
  3240. after this first result. In case of any error, `xpcall` returns
  3241. `false` plus the result from {err}.
  3242. ==============================================================================
  3243. 5.2 Coroutine Manipulation *luaref-libCoro*
  3244. The operations related to coroutines comprise a sub-library of the basic
  3245. library and come inside the table `coroutine`. See |luaref-langCoro| for a
  3246. general description of coroutines.
  3247. coroutine.create({f}) *coroutine.create()*
  3248. Creates a new coroutine, with body {f}. {f} must be a Lua function.
  3249. Returns this new coroutine, an object with type `"thread"`.
  3250. coroutine.resume({co} [, {val1}, {...}]) *coroutine.resume()*
  3251. Starts or continues the execution of coroutine {co}. The first time
  3252. you resume a coroutine, it starts running its body. The values {val1},
  3253. {...} are passed as arguments to the body function. If the coroutine has
  3254. yielded, `resume` restarts it; the values {val1}, {...} are passed as
  3255. the results from the yield.
  3256. If the coroutine runs without any errors, `resume` returns `true` plus
  3257. any values passed to `yield` (if the coroutine yields) or any values
  3258. returned by the body function(if the coroutine terminates). If there
  3259. is any error, `resume` returns `false` plus the error message.
  3260. coroutine.running() *coroutine.running()*
  3261. Returns the running coroutine, or `nil` when called by the main
  3262. thread.
  3263. coroutine.status({co}) *coroutine.status()*
  3264. Returns the status of coroutine {co}, as a string: `"running"`, if the
  3265. coroutine is running (that is, it called `status`); `"suspended"`, if
  3266. the coroutine is suspended in a call to `yield`, or if it has not
  3267. started running yet; `"normal"` if the coroutine is active but not
  3268. running (that is, it has resumed another coroutine); and `"dead"` if
  3269. the coroutine has finished its body function, or if it has stopped
  3270. with an error.
  3271. coroutine.wrap({f}) *coroutine.wrap()*
  3272. Creates a new coroutine, with body {f}. {f} must be a Lua function.
  3273. Returns a function that resumes the coroutine each time it is called.
  3274. Any arguments passed to the function behave as the extra arguments to
  3275. `resume`. Returns the same values returned by `resume`, except the
  3276. first boolean. In case of error, propagates the error.
  3277. coroutine.yield({...}) *coroutine.yield()*
  3278. Suspends the execution of the calling coroutine. The coroutine cannot
  3279. be running a C function, a metamethod, or an iterator. Any arguments
  3280. to `yield` are passed as extra results to `resume`.
  3281. ==============================================================================
  3282. 5.3 - Modules *luaref-libModule*
  3283. The package library provides basic facilities for loading and building modules
  3284. in Lua. It exports two of its functions directly in the global environment:
  3285. `require` and `module` (see |luaref-require()| and |luaref-module()|). Everything else is
  3286. exported in a table `package`.
  3287. module({name} [, {...}]) *luaref-module()*
  3288. Creates a module. If there is a table in `package.loaded[name]`, this
  3289. table is the module. Otherwise, if there is a global table `t` with
  3290. the given name, this table is the module. Otherwise creates a new
  3291. table `t` and sets it as the value of the global {name} and the value
  3292. of `package.loaded[name]`. This function also initializes `t._NAME`
  3293. with the given name, `t._M` with the module (`t` itself), and
  3294. `t._PACKAGE` with the package name (the full module name minus last
  3295. component; see below). Finally, `module` sets `t` as the new
  3296. environment of the current function and the new value of
  3297. `package.loaded[name]`, so that `require` (see |luaref-require()|)
  3298. returns `t`.
  3299. If {name} is a compound name (that is, one with components separated
  3300. by dots), `module` creates (or reuses, if they already exist) tables
  3301. for each component. For instance, if {name} is `a.b.c`, then `module`
  3302. stores the module table in field `c` of field `b` of global `a`.
  3303. This function may receive optional `options` after the module name,
  3304. where each option is a function to be applied over the module.
  3305. require({modname}) *luaref-require()*
  3306. Loads the given module. The function starts by looking into the
  3307. `package.loaded` table to determine whether {modname} is already
  3308. loaded. If it is, then `require` returns the value stored at
  3309. `package.loaded[modname]`. Otherwise, it tries to find a `loader` for
  3310. the module.
  3311. To find a loader, first `require` queries `package.preload[modname]`.
  3312. If it has a value, this value (which should be a function) is the
  3313. loader. Otherwise `require` searches for a Lua loader using the path
  3314. stored in `package.path`. If that also fails, it searches for a C
  3315. loader using the path stored in `package.cpath`. If that also fails,
  3316. it tries an `all-in-one` loader (see below).
  3317. When loading a C library, `require` first uses a dynamic link facility
  3318. to link the application with the library. Then it tries to find a C
  3319. function inside this library to be used as the loader. The name of
  3320. this C function is the string `"luaopen_"` concatenated with a copy of
  3321. the module name where each dot is replaced by an underscore. Moreover,
  3322. if the module name has a hyphen, its prefix up to (and including) the
  3323. first hyphen is removed. For instance, if the module name is
  3324. `a.v1-b.c`, the function name will be `luaopen_b_c`.
  3325. If `require` finds neither a Lua library nor a C library for a module,
  3326. it calls the `all-in-one loader`. This loader searches the C path for
  3327. a library for the root name of the given module. For instance, when
  3328. requiring `a.b.c`, it will search for a C library for `a`. If found,
  3329. it looks into it for an open function for the submodule; in our
  3330. example, that would be `luaopen_a_b_c`. With this facility, a package
  3331. can pack several C submodules into one single library, with each
  3332. submodule keeping its original open function.
  3333. Once a loader is found, `require` calls the loader with a single
  3334. argument, {modname}. If the loader returns any value, `require`
  3335. assigns the returned value to `package.loaded[modname]`. If the loader
  3336. returns no value and has not assigned any value to
  3337. `package.loaded[modname]`, then `require` assigns `true` to this
  3338. entry. In any case, `require` returns the final value of
  3339. `package.loaded[modname]`.
  3340. If there is any error loading or running the module, or if it cannot
  3341. find any loader for the module, then `require` signals an error.
  3342. package.cpath *package.cpath*
  3343. The path used by `require` to search for a C loader.
  3344. Lua initializes the C path `package.cpath` in the same way it
  3345. initializes the Lua path `package.path`, using the environment
  3346. variable `LUA_CPATH` (plus another default path defined in
  3347. `luaconf.h`).
  3348. package.loaded *package.loaded()*
  3349. A table used by `require` to control which modules are already loaded.
  3350. When you require a module `modname` and `package.loaded[modname]` is
  3351. not false, `require` simply returns the value stored there.
  3352. package.loadlib({libname}, {funcname}) *package.loadlib()*
  3353. Dynamically links the host program with the C library {libname}.
  3354. Inside this library, looks for a function {funcname} and returns this
  3355. function as a C function. (So, {funcname} must follow the protocol
  3356. (see |lua_CFunction()|)).
  3357. This is a low-level function. It completely bypasses the package and
  3358. module system. Unlike `require`, it does not perform any path
  3359. searching and does not automatically adds extensions. {libname} must
  3360. be the complete file name of the C library, including if necessary a
  3361. path and extension. {funcname} must be the exact name exported by the
  3362. C library (which may depend on the C compiler and linker used).
  3363. This function is not supported by ANSI C. As such, it is only
  3364. available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD,
  3365. plus other Unix systems that support the `dlfcn` standard).
  3366. package.path *package.path*
  3367. The path used by `require` to search for a Lua loader.
  3368. At start-up, Lua initializes this variable with the value of the
  3369. environment variable `LUA_PATH` or with a default path defined in
  3370. `luaconf.h`, if the environment variable is not defined. Any `";;"` in
  3371. the value of the environment variable is replaced by the default path.
  3372. A path is a sequence of `templates` separated by semicolons. For each
  3373. template, `require` will change each interrogation mark in the
  3374. template by `filename`, which is `modname` with each dot replaced by a
  3375. "directory separator" (such as `"/"` in Unix); then it will try to
  3376. load the resulting file name. So, for instance, if the Lua path is
  3377. >
  3378. "./?.lua;./?.lc;/usr/local/?/init.lua"
  3379. <
  3380. the search for a Lua loader for module `foo` will try to load the
  3381. files `./foo.lua`, `./foo.lc`, and `/usr/local/foo/init.lua`, in that
  3382. order.
  3383. package.preload *package.preload()*
  3384. A table to store loaders for specific modules (see |luaref-require()|).
  3385. package.seeall({module}) *package.seeall()*
  3386. Sets a metatable for {module} with its `__index` field referring to
  3387. the global environment, so that this module inherits values from the
  3388. global environment. To be used as an option to function {module}.
  3389. ==============================================================================
  3390. 5.4 - String Manipulation *luaref-libString*
  3391. This library provides generic functions for string manipulation, such as
  3392. finding and extracting substrings, and pattern matching. When indexing a
  3393. string in Lua, the first character is at position 1 (not at 0, as in C).
  3394. Indices are allowed to be negative and are interpreted as indexing backwards,
  3395. from the end of the string. Thus, the last character is at position -1, and
  3396. so on.
  3397. The string library provides all its functions inside the table `string`.
  3398. It also sets a metatable for strings where the `__index` field points to the
  3399. `string` table. Therefore, you can use the string functions in object-oriented
  3400. style. For instance, `string.byte(s, i)` can be written as `s:byte(i)`.
  3401. string.byte({s} [, {i} [, {j}]]) *string.byte()*
  3402. Returns the internal numerical codes of the characters `s[i]`,
  3403. `s[i+1]`,..., `s[j]`. The default value for {i} is 1; the default
  3404. value for {j} is {i}.
  3405. Note that numerical codes are not necessarily portable across
  3406. platforms.
  3407. string.char({...}) *string.char()*
  3408. Receives zero or more integers. Returns a string with length equal to
  3409. the number of arguments, in which each character has the internal
  3410. numerical code equal to its correspondent argument.
  3411. Note that numerical codes are not necessarily portable across
  3412. platforms.
  3413. string.dump({function}) *string.dump()*
  3414. Returns a string containing a binary representation of the given
  3415. function, so that a later |luaref-loadstring()| on this string returns a
  3416. copy of the function. {function} must be a Lua function without
  3417. upvalues.
  3418. string.find({s}, {pattern} [, {init} [, {plain}]]) *string.find()*
  3419. Looks for the first match of {pattern} in the string {s}. If it finds
  3420. a match, then {find} returns the indices of {s} where this occurrence
  3421. starts and ends; otherwise, it returns `nil`. A third, optional
  3422. numerical argument {init} specifies where to start the search; its
  3423. default value is 1 and may be negative. A value of {true} as a fourth,
  3424. optional argument {plain} turns off the pattern matching facilities,
  3425. so the function does a plain "find substring" operation, with no
  3426. characters in {pattern} being considered "magic". Note that if {plain}
  3427. is given, then {init} must be given as well.
  3428. If the pattern has captures, then in a successful match the captured
  3429. values are also returned, after the two indices.
  3430. string.format({formatstring}, {...}) *string.format()*
  3431. Returns a formatted version of its variable number of arguments
  3432. following the description given in its first argument (which must be a
  3433. string). The format string follows the same rules as the `printf`
  3434. family of standard C functions. The only differences are that the
  3435. options/modifiers `*`, `l`, `L`, `n`, `p`, and `h` are not supported
  3436. and that there is an extra option, `q`. The `q` option formats a
  3437. string in a form suitable to be safely read back by the Lua
  3438. interpreter: the string is written between double quotes, and all
  3439. double quotes, newlines, embedded zeros, and backslashes in the string
  3440. are correctly escaped when written. For instance, the call
  3441. >
  3442. string.format('%q', 'a string with "quotes" and \n new line')
  3443. <
  3444. will produce the string:
  3445. >
  3446. "a string with \"quotes\" and \
  3447. new line"
  3448. <
  3449. The options `c`, `d`, `E`, `e`, `f`, `g`, `G`, `i`, `o`, `u`, `X`, and
  3450. `x` all expect a number as argument, whereas `q` and `s` expect a
  3451. string.
  3452. This function does not accept string values containing embedded zeros.
  3453. string.gmatch({s}, {pattern}) *string.gmatch()*
  3454. Returns an iterator function that, each time it is called, returns the
  3455. next captures from {pattern} over string {s}.
  3456. If {pattern} specifies no captures, then the whole match is produced
  3457. in each call.
  3458. As an example, the following loop
  3459. >
  3460. s = "hello world from Lua"
  3461. for w in string.gmatch(s, "%a+") do
  3462. print(w)
  3463. end
  3464. <
  3465. will iterate over all the words from string {s}, printing one per
  3466. line. The next example collects all pairs `key=value` from the given
  3467. string into a table:
  3468. >
  3469. t = {}
  3470. s = "from=world, to=Lua"
  3471. for k, v in string.gmatch(s, "(%w+)=(%w+)") do
  3472. t[k] = v
  3473. end
  3474. <
  3475. string.gsub({s}, {pattern}, {repl} [, {n}]) *string.gsub()*
  3476. Returns a copy of {s} in which all occurrences of the {pattern} have
  3477. been replaced by a replacement string specified by {repl}, which may
  3478. be a string, a table, or a function. `gsub` also returns, as its
  3479. second value, the total number of substitutions made.
  3480. If {repl} is a string, then its value is used for replacement. The
  3481. character `%` works as an escape character: any sequence in {repl} of
  3482. the form `%n`, with {n} between 1 and 9, stands for the value of the
  3483. {n} -th captured substring (see below). The sequence `%0` stands for
  3484. the whole match. The sequence `%%` stands for a single `%`.
  3485. If {repl} is a table, then the table is queried for every match, using
  3486. the first capture as the key; if the pattern specifies no captures,
  3487. then the whole match is used as the key.
  3488. If {repl} is a function, then this function is called every time a
  3489. match occurs, with all captured substrings passed as arguments, in
  3490. order; if the pattern specifies no captures, then the whole match is
  3491. passed as a sole argument.
  3492. If the value returned by the table query or by the function call is a
  3493. string or a number, then it is used as the replacement string;
  3494. otherwise, if it is `false` or `nil`, then there is no replacement
  3495. (that is, the original match is kept in the string).
  3496. The optional last parameter {n} limits the maximum number of
  3497. substitutions to occur. For instance, when {n} is 1 only the first
  3498. occurrence of `pattern` is replaced.
  3499. Here are some examples:
  3500. >
  3501. x = string.gsub("hello world", "(%w+)", "%1 %1")
  3502. --> x="hello hello world world"
  3503. x = string.gsub("hello world", "%w+", "%0 %0", 1)
  3504. --> x="hello hello world"
  3505. x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
  3506. --> x="world hello Lua from"
  3507. x = string.gsub("home = `HOME, user = ` USER", "%$(%w+)", os.getenv)
  3508. --> x="home = /home/roberto, user = roberto"
  3509. x = string.gsub("4+5 = `return 4+5` ", "% `(.-)%` ", function (s)
  3510. return loadstring(s)()
  3511. end)
  3512. --> x="4+5 = 9"
  3513. local t = {name="lua", version="5.1"}
  3514. x = string.gsub(" `name%-` version.tar.gz", "%$(%w+)", t)
  3515. --> x="lua-5.1.tar.gz"
  3516. <
  3517. string.len({s}) *string.len()*
  3518. Receives a string and returns its length. The empty string `""` has
  3519. length 0. Embedded zeros are counted, so `"a\000b\000c"` has length 5.
  3520. string.lower({s}) *string.lower()*
  3521. Receives a string and returns a copy of this string with all uppercase
  3522. letters changed to lowercase. All other characters are left unchanged.
  3523. The definition of what an uppercase letter is depends on the current
  3524. locale.
  3525. string.match({s}, {pattern} [, {init}]) *string.match()*
  3526. Looks for the first `match` of {pattern} in the string {s}. If it
  3527. finds one, then `match` returns the captures from the pattern;
  3528. otherwise it returns `nil`. If {pattern} specifies no captures, then
  3529. the whole match is returned. A third, optional numerical argument
  3530. {init} specifies where to start the search; its default value is 1 and
  3531. may be negative.
  3532. string.rep({s}, {n}) *string.rep()*
  3533. Returns a string that is the concatenation of {n} copies of the string
  3534. {s}.
  3535. string.reverse({s}) *string.reverse()*
  3536. Returns a string that is the string {s} reversed.
  3537. string.sub({s}, {i} [, {j}]) *string.sub()*
  3538. Returns the substring of {s} that starts at {i} and continues until
  3539. {j}; {i} and {j} may be negative. If {j} is absent, then it is assumed
  3540. to be equal to `-1` (which is the same as the string length). In
  3541. particular, the call `string.sub(s,1,j)` returns a prefix of {s} with
  3542. length {j}, and `string.sub(s,-i)` returns a suffix of {s} with length
  3543. {i}.
  3544. string.upper({s}) *string.upper()*
  3545. Receives a string and returns a copy of that string with all lowercase
  3546. letters changed to uppercase. All other characters are left unchanged.
  3547. The definition of what a lowercase letter is depends on the current
  3548. locale.
  3549. ------------------------------------------------------------------------------
  3550. 5.4.1 Patterns *luaref-patterns* *luaref-libStringPat*
  3551. A character class is used to represent a set of characters. The following
  3552. combinations are allowed in describing a character class:
  3553. - `x` (where `x` is not one of the magic characters `^$()%.[]*+-?`)
  3554. represents the character `x` itself.
  3555. - `.` (a dot) represents all characters.
  3556. - `%a` represents all letters.
  3557. - `%c` represents all control characters.
  3558. - `%d` represents all digits.
  3559. - `%l` represents all lowercase letters.
  3560. - `%p` represents all punctuation characters.
  3561. - `%s` represents all space characters.
  3562. - `%u` represents all uppercase letters.
  3563. - `%w` represents all alphanumeric characters.
  3564. - `%x` represents all hexadecimal digits.
  3565. - `%z` represents the character with representation `0`.
  3566. - `%x` (where `x` is any non-alphanumeric character) represents the
  3567. character `x`. This is the standard way to escape the magic
  3568. characters. Any punctuation character (even the non-magic) can be
  3569. preceded by a `%` when used to represent itself in a pattern.
  3570. - `[set]` represents the class which is the union of all characters in
  3571. `set`. A range of characters may be specified by separating the end
  3572. characters of the range with a `-`. All classes `%x` described
  3573. above may also be used as components in `set`. All other characters
  3574. in `set` represent themselves. For example, `[%w_]` (or `[_%w]`)
  3575. represents all alphanumeric characters plus the underscore, `[0-7]`
  3576. represents the octal digits, and `[0-7%l%-]` represents the octal
  3577. digits plus the lowercase letters plus the `-` character.
  3578. The interaction between ranges and classes is not defined. Therefore,
  3579. patterns like `[%a-z]` or `[a-%%]` have no meaning.
  3580. - `[^set]` represents the complement of `set`, where `set` is interpreted
  3581. as above.
  3582. For all classes represented by single letters (`%a`, `%c`, etc.), the
  3583. corresponding uppercase letter represents the complement of the class. For
  3584. instance, `%S` represents all non-space characters.
  3585. The definitions of letter, space, and other character groups depend on the
  3586. current locale. In particular, the class `[a-z]` may not be equivalent to `%l`.
  3587. *luaref-patternitem*
  3588. Pattern Item:~
  3589. -------------
  3590. A pattern item may be
  3591. - a single character class, which matches any single character in the
  3592. class;
  3593. - a single character class followed by `*`, which matches 0 or more
  3594. repetitions of characters in the class. These repetition items will
  3595. always match the longest possible sequence;
  3596. - a single character class followed by `+`, which matches 1 or more
  3597. repetitions of characters in the class. These repetition items will
  3598. always match the longest possible sequence;
  3599. - a single character class followed by `-`, which also matches 0 or
  3600. more repetitions of characters in the class. Unlike `*`, these
  3601. repetition items will always match the shortest possible sequence;
  3602. - a single character class followed by `?`, which matches 0 or 1
  3603. occurrences of a character in the class;
  3604. - `%n`, for `n` between 1 and 9; such item matches a substring equal to the
  3605. `n` -th captured string (see below);
  3606. - `%bxy`, where `x` and `y` are two distinct characters; such item matches
  3607. strings that start with `x`, end with `y`, and where the `x` and `y`
  3608. are balanced. This means that, if one reads the string from left to
  3609. right, counting `+1` for an `x` and `-1` for a `y`, the ending `y` is the first
  3610. `y` where the count reaches 0. For instance, the item `%b()` matches
  3611. expressions with balanced parentheses.
  3612. *luaref-pattern*
  3613. Pattern:~
  3614. --------
  3615. A pattern is a sequence of pattern items. A `^` at the beginning of a pattern
  3616. anchors the match at the beginning of the subject string. A `$` at the end of
  3617. a pattern anchors the match at the end of the subject string. At other
  3618. positions, `^` and `$` have no special meaning and represent themselves.
  3619. *luaref-capture*
  3620. Captures:~
  3621. ---------
  3622. A pattern may contain sub-patterns enclosed in parentheses; they describe
  3623. captures. When a match succeeds, the substrings of the subject string that
  3624. match captures are stored (captured) for future use. Captures are numbered
  3625. according to their left parentheses. For instance, in the pattern
  3626. `"(a*(.)%w(%s*))"`, the part of the string matching `"a*(.)%w(%s*)"` is stored
  3627. as the first capture (and therefore has number 1); the character matching `.`
  3628. is captured with number 2, and the part matching `%s*` has number 3.
  3629. As a special case, the empty capture `()` captures the current string position
  3630. (a number). For instance, if we apply the pattern `"()aa()"` on the
  3631. string `"flaaap"`, there will be two captures: 3 and 5.
  3632. A pattern cannot contain embedded zeros. Use `%z` instead.
  3633. ==============================================================================
  3634. 5.5 Table Manipulation *luaref-libTable*
  3635. This library provides generic functions for table manipulation. It provides
  3636. all its functions inside the table `table`.
  3637. Most functions in the table library assume that the table represents an array
  3638. or a list. For those functions, when we talk about the "length" of a table we
  3639. mean the result of the length operator.
  3640. table.concat({table} [, {sep} [, {i} [, {j}]]]) *table.concat()*
  3641. Given an array where all elements are strings or numbers, returns
  3642. `table[i]..sep..table[i+1] ... sep..table[j]`. The default value for
  3643. {sep} is the empty string, the default for {i} is 1, and the default
  3644. for {j} is the length of the table. If {i} is greater than {j},
  3645. returns the empty string.
  3646. table.foreach({table}, {f}) *table.foreach()*
  3647. Executes the given {f} over all elements of {table}. For each element,
  3648. {f} is called with the index and respective value as arguments. If {f}
  3649. returns a non-`nil` value, then the loop is broken, and this value is
  3650. returned as the final value of `table.foreach`.
  3651. See |luaref-next()| for extra information about table traversals.
  3652. table.foreachi({table}, {f}) *table.foreachi()*
  3653. Executes the given {f} over the numerical indices of {table}. For each
  3654. index, {f} is called with the index and respective value as arguments.
  3655. Indices are visited in sequential order, from 1 to `n`, where `n` is
  3656. the length of the table. If {f} returns a non-`nil` value, then the
  3657. loop is broken and this value is returned as the result of
  3658. `table.foreachi`.
  3659. table.insert({table}, [{pos},] {value}) *table.insert()*
  3660. Inserts element {value} at position {pos} in {table}, shifting up
  3661. other elements to open space, if necessary. The default value for
  3662. {pos} is `n+1`, where `n` is the length of the table (see
  3663. |luaref-langLength|), so that a call `table.insert(t,x)` inserts `x`
  3664. at the end of table `t`.
  3665. table.maxn({table}) *table.maxn()*
  3666. Returns the largest positive numerical index of the given table, or
  3667. zero if the table has no positive numerical indices. (To do its job
  3668. this function does a linear traversal of the whole table.)
  3669. table.remove({table} [, {pos}]) *table.remove()*
  3670. Removes from {table} the element at position {pos}, shifting down
  3671. other elements to close the space, if necessary. Returns the value of
  3672. the removed element. The default value for {pos} is `n`, where `n` is
  3673. the length of the table (see |luaref-langLength|), so that a call
  3674. `table.remove(t)` removes the last element of table `t`.
  3675. table.sort({table} [, {comp}]) *table.sort()*
  3676. Sorts table elements in a given order, `in-place`, from `table[1]` to
  3677. `table[n]`, where `n` is the length of the table (see
  3678. |luaref-langLength|). If {comp} is given, then it must be a function
  3679. that receives two table elements, and returns true when the first is
  3680. less than the second (so that `not comp(a[i+1],a[i])` will be true
  3681. after the sort). If {comp} is not given, then the standard Lua
  3682. operator `<` is used instead.
  3683. The sort algorithm is `not` stable, that is, elements considered equal by the
  3684. given order may have their relative positions changed by the sort.
  3685. ==============================================================================
  3686. 5.6 Mathematical Functions *luaref-libMath*
  3687. This library is an interface to most of the functions of the standard C math
  3688. library. It provides all its functions inside the table `math`.
  3689. math.abs({x}) *math.abs()*
  3690. Returns the absolute value of {x}.
  3691. math.acos({x}) *math.acos()*
  3692. Returns the arc cosine of {x} (in radians).
  3693. math.asin({x}) *math.asin()*
  3694. Returns the arc sine of {x} (in radians).
  3695. math.atan({x}) *math.atan()*
  3696. Returns the arc tangent of {x} (in radians).
  3697. math.atan2({x}, {y}) *math.atan2()*
  3698. Returns the arc tangent of `x/y` (in radians), but uses the signs of
  3699. both parameters to find the quadrant of the result. (It also handles
  3700. correctly the case of {y} being zero.)
  3701. math.ceil({x}) *math.ceil()*
  3702. Returns the smallest integer larger than or equal to {x}.
  3703. math.cos({x}) *math.cos()*
  3704. Returns the cosine of {x} (assumed to be in radians).
  3705. math.cosh({x}) *math.cosh()*
  3706. Returns the hyperbolic cosine of {x}.
  3707. math.deg({x}) *math.deg()*
  3708. Returns the angle {x} (given in radians) in degrees.
  3709. math.exp({x}) *math.exp()*
  3710. Returns the value `e^x`.
  3711. math.floor({x}) *math.floor()*
  3712. Returns the largest integer smaller than or equal to {x}.
  3713. math.fmod({x}, {y}) *math.fmod()*
  3714. Returns the remainder of the division of {x} by {y}.
  3715. math.frexp({x}) *math.frexp()*
  3716. Returns `m` and `e` such that `x = m * 2^e`, `e` is an integer and the
  3717. absolute value of `m` is in the range `[0.5, 1)` (or zero when {x} is
  3718. zero).
  3719. math.huge *math.huge()*
  3720. The value `HUGE_VAL`, a value larger than or equal to any other
  3721. numerical value.
  3722. math.ldexp({m}, {e}) *math.ldexp()*
  3723. Returns `m * 2^e` (`e` should be an integer).
  3724. math.log({x}) *math.log()*
  3725. Returns the natural logarithm of {x}.
  3726. math.log10({x}) *math.log10()*
  3727. Returns the base-10 logarithm of {x}.
  3728. math.max({x}, {...}) *math.max()*
  3729. Returns the maximum value among its arguments.
  3730. math.min({x}, {...}) *math.min()*
  3731. Returns the minimum value among its arguments.
  3732. math.modf({x}) *math.modf()*
  3733. Returns two numbers, the integral part of {x} and the fractional part
  3734. of {x}.
  3735. math.pi *math.pi()*
  3736. The value of `pi`.
  3737. math.pow({x}, {y}) *math.pow()*
  3738. Returns `x^y`. (You can also use the expression `x^y` to compute this
  3739. value.)
  3740. math.rad({x}) *math.rad()*
  3741. Returns the angle {x} (given in degrees) in radians.
  3742. math.random([{m} [, {n}]]) *math.random()*
  3743. This function is an interface to the simple pseudo-random generator
  3744. function `rand` provided by ANSI C. (No guarantees can be given for
  3745. its statistical properties.)
  3746. When called without arguments, returns a pseudo-random real number in
  3747. the range `[0,1)`. When called with a number {m}, `math.random`
  3748. returns a pseudo-random integer in the range `[1, m]`. When called
  3749. with two numbers {m} and {n}, `math.random` returns a pseudo-random
  3750. integer in the range `[m, n]`.
  3751. math.randomseed({x}) *math.randomseed()*
  3752. Sets {x} as the "seed" for the pseudo-random generator: equal seeds
  3753. produce equal sequences of numbers.
  3754. math.sin({x}) *math.sin()*
  3755. Returns the sine of {x} (assumed to be in radians).
  3756. math.sinh({x}) *math.sinh()*
  3757. Returns the hyperbolic sine of {x}.
  3758. math.sqrt({x}) *math.sqrt()*
  3759. Returns the square root of {x}. (You can also use the expression
  3760. `x^0.5` to compute this value.)
  3761. math.tan({x}) *math.tan()*
  3762. Returns the tangent of {x} (assumed to be in radians).
  3763. math.tanh({x}) *math.tanh()*
  3764. Returns the hyperbolic tangent of {x}.
  3765. ==============================================================================
  3766. 5.6 Input and Output Facilities *luaref-libIO*
  3767. The I/O library provides two different styles for file manipulation. The first
  3768. one uses implicit file descriptors; that is, there are operations to set a
  3769. default input file and a default output file, and all input/output operations
  3770. are over these default files. The second style uses explicit file
  3771. descriptors.
  3772. When using implicit file descriptors, all operations are supplied by
  3773. table `io`. When using explicit file descriptors, the operation `io.open` returns
  3774. a file descriptor and then all operations are supplied as methods of the file
  3775. descriptor.
  3776. The table `io` also provides three predefined file descriptors with their usual
  3777. meanings from C: `io.stdin`, `io.stdout`, and `io.stderr`.
  3778. Unless otherwise stated, all I/O functions return `nil` on failure (plus an
  3779. error message as a second result) and some value different from `nil` on
  3780. success.
  3781. io.close([{file}]) *io.close()*
  3782. Equivalent to `file:close`. Without a {file}, closes the default
  3783. output file.
  3784. io.flush() *io.flush()*
  3785. Equivalent to `file:flush` over the default output file.
  3786. io.input([{file}]) *io.input()*
  3787. When called with a file name, it opens the named file (in text mode),
  3788. and sets its handle as the default input file. When called with a file
  3789. handle, it simply sets this file handle as the default input file.
  3790. When called without parameters, it returns the current default input
  3791. file.
  3792. In case of errors this function raises the error, instead of returning
  3793. an error code.
  3794. io.lines([{filename}]) *io.lines()*
  3795. Opens the given file name in read mode and returns an iterator
  3796. function that, each time it is called, returns a new line from the
  3797. file. Therefore, the construction
  3798. `for line in io.lines(filename) do` `body` `end`
  3799. will iterate over all lines of the file. When the iterator function
  3800. detects the end of file, it returns `nil` (to finish the loop) and
  3801. automatically closes the file.
  3802. The call `io.lines()` (without a file name) is equivalent to
  3803. `io.input():lines()`; that is, it iterates over the lines of the
  3804. default input file. In this case it does not close the file when the
  3805. loop ends.
  3806. io.open({filename} [, {mode}]) *io.open()*
  3807. This function opens a file, in the mode specified in the string
  3808. {mode}. It returns a new file handle, or, in case of errors, `nil`
  3809. plus an error message.
  3810. The {mode} string can be any of the following:
  3811. - `"r"` read mode (the default);
  3812. - `"w"` write mode;
  3813. - `"a"` append mode;
  3814. - `"r+"` update mode, all previous data is preserved;
  3815. - `"w+"` update mode, all previous data is erased;
  3816. - `"a+"` append update mode, previous data is preserved, writing is
  3817. only allowed at the end of file.
  3818. The {mode} string may also have a `b` at the end, which is needed in
  3819. some systems to open the file in binary mode. This string is exactly
  3820. what is used in the standard C function `fopen`.
  3821. io.output([{file}]) *io.output()*
  3822. Similar to `io.input`, but operates over the default output file.
  3823. io.popen({prog} [, {mode}]) *io.popen()*
  3824. Starts program {prog} in a separated process and returns a file handle
  3825. that you can use to read data from this program (if {mode} is `"r"`,
  3826. the default) or to write data to this program (if {mode} is `"w"`).
  3827. This function is system dependent and is not available on all
  3828. platforms.
  3829. io.read({...}) *io.read()*
  3830. Equivalent to `io.input():read`.
  3831. io.tmpfile() *io.tmpfile()*
  3832. Returns a handle for a temporary file. This file is opened in update
  3833. mode and it is automatically removed when the program ends.
  3834. io.type({obj}) *io.type()*
  3835. Checks whether {obj} is a valid file handle. Returns the string
  3836. `"file"` if {obj} is an open file handle, `"closed file"` if {obj} is
  3837. a closed file handle, or `nil` if {obj} is not a file handle.
  3838. io.write({...}) *io.write()*
  3839. Equivalent to `io.output():write`.
  3840. file:close() *luaref-file:close()*
  3841. Closes `file`. Note that files are automatically closed when their
  3842. handles are garbage collected, but that takes an unpredictable amount
  3843. of time to happen.
  3844. file:flush() *luaref-file:flush()*
  3845. Saves any written data to `file`.
  3846. file:lines() *luaref-file:lines()*
  3847. Returns an iterator function that, each time it is called, returns a
  3848. new line from the file. Therefore, the construction
  3849. `for line in file:lines() do` `body` `end`
  3850. will iterate over all lines of the file. (Unlike `io.lines`, this
  3851. function does not close the file when the loop ends.)
  3852. file:read({...}) *luaref-file:read()*
  3853. Reads the file `file`, according to the given formats, which specify
  3854. what to read. For each format, the function returns a string (or a
  3855. number) with the characters read, or `nil` if it cannot read data with
  3856. the specified format. When called without formats, it uses a default
  3857. format that reads the entire next line (see below).
  3858. The available formats are
  3859. `"*n"` reads a number; this is the only format that returns a
  3860. number instead of a string.
  3861. `"*a"` reads the whole file, starting at the current position. On
  3862. end of file, it returns the empty string.
  3863. `"*l"` reads the next line (skipping the end of line), returning
  3864. `nil` on end of file. This is the default format.
  3865. `number` reads a string with up to that number of characters,
  3866. returning `nil` on end of file. If number is zero, it reads
  3867. nothing and returns an empty string, or `nil` on end of file.
  3868. file:seek([{whence}] [, {offset}]) *luaref-file:seek()*
  3869. Sets and gets the file position, measured from the beginning of the
  3870. file, to the position given by {offset} plus a base specified by the
  3871. string {whence}, as follows:
  3872. - `"set"`: base is position 0 (beginning of the file);
  3873. - `"cur"`: base is current position;
  3874. - `"end"`: base is end of file;
  3875. In case of success, function `seek` returns the final file position,
  3876. measured in bytes from the beginning of the file. If this function
  3877. fails, it returns `nil`, plus a string describing the error.
  3878. The default value for {whence} is `"cur"`, and for {offset} is 0.
  3879. Therefore, the call `file:seek()` returns the current file position,
  3880. without changing it; the call `file:seek("set")` sets the position to
  3881. the beginning of the file (and returns 0); and the call
  3882. `file:seek("end")` sets the position to the end of the file, and
  3883. returns its size.
  3884. file:setvbuf({mode} [, {size}]) *luaref-file:setvbuf()*
  3885. Sets the buffering mode for an output file. There are three available
  3886. modes:
  3887. `"no"` no buffering; the result of any output operation appears
  3888. immediately.
  3889. `"full"` full buffering; output operation is performed only when
  3890. the buffer is full (or when you explicitly `flush` the file
  3891. (see |io.flush()|).
  3892. `"line"` line buffering; output is buffered until a newline is
  3893. output or there is any input from some special files (such as
  3894. a terminal device).
  3895. For the last two cases, {size} specifies the size of the buffer, in
  3896. bytes. The default is an appropriate size.
  3897. file:write({...}) *luaref-file:write()*
  3898. Writes the value of each of its arguments to `file`. The arguments
  3899. must be strings or numbers. To write other values, use `tostring`
  3900. |luaref-tostring()| or `string.format` |string.format()| before
  3901. `write`.
  3902. ==============================================================================
  3903. 5.8 Operating System Facilities *luaref-libOS*
  3904. This library is implemented through table `os`.
  3905. os.clock() *os.clock()*
  3906. Returns an approximation of the amount in seconds of CPU time used by
  3907. the program.
  3908. os.date([{format} [, {time}]]) *os.date()*
  3909. Returns a string or a table containing date and time, formatted
  3910. according to the given string {format}.
  3911. If the {time} argument is present, this is the time to be formatted
  3912. (see the `os.time` function |os.time()| for a description of this
  3913. value). Otherwise, `date` formats the current time.
  3914. If {format} starts with `!`, then the date is formatted in
  3915. Coordinated Universal Time. After this optional character, if {format}
  3916. is the string `"*t"`, then `date` returns a table with the following
  3917. fields: `year` (four digits), `month` (1-12), `day` (1-31), `hour`
  3918. (0-23), `min` (0-59), `sec` (0-61), `wday` (weekday, Sunday is 1),
  3919. `yday` (day of the year), and `isdst` (daylight saving flag, a
  3920. boolean).
  3921. If {format} is not `"*t"`, then `date` returns the date as a string,
  3922. formatted according to the same rules as the C function `strftime`.
  3923. When called without arguments, `date` returns a reasonable date and
  3924. time representation that depends on the host system and on the current
  3925. locale (that is, `os.date()` is equivalent to `os.date("%c")`).
  3926. os.difftime({t2}, {t1}) *os.difftime()*
  3927. Returns the number of seconds from time {t1} to time {t2}. In POSIX,
  3928. Windows, and some other systems, this value is exactly `t2 - t1` .
  3929. os.execute([{command}]) *os.execute()*
  3930. This function is equivalent to the C function `system`. It passes
  3931. {command} to be executed by an operating system shell. It returns a
  3932. status code, which is system-dependent. If {command} is absent, then
  3933. it returns nonzero if a shell is available and zero otherwise.
  3934. os.exit([{code}]) *os.exit()*
  3935. Calls the C function `exit`, with an optional {code}, to terminate the
  3936. host program. The default value for {code} is the success code.
  3937. os.getenv({varname}) *os.getenv()*
  3938. Returns the value of the process environment variable {varname}, or
  3939. `nil` if the variable is not defined.
  3940. os.remove({filename}) *os.remove()*
  3941. Deletes the file with the given name. Directories must be empty to be
  3942. removed. If this function fails, it returns `nil`, plus a string
  3943. describing the error.
  3944. os.rename({oldname}, {newname}) *os.rename()*
  3945. Renames file named {oldname} to {newname}. If this function fails, it
  3946. returns `nil`, plus a string describing the error.
  3947. os.setlocale({locale} [, {category}]) *os.setlocale()*
  3948. Sets the current locale of the program. {locale} is a string
  3949. specifying a locale; {category} is an optional string describing which
  3950. category to change: `"all"`, `"collate"`, `"ctype"`, `"monetary"`,
  3951. `"numeric"`, or `"time"`; the default category is `"all"`. The
  3952. function returns the name of the new locale, or `nil` if the request
  3953. cannot be honored.
  3954. os.time([{table}]) *os.time()*
  3955. Returns the current time when called without arguments, or a time
  3956. representing the date and time specified by the given table. This
  3957. table must have fields `year`, `month`, and `day`, and may have fields
  3958. `hour`, `min`, `sec`, and `isdst` (for a description of these fields,
  3959. see the `os.date` function |os.date()|).
  3960. The returned value is a number, whose meaning depends on your system.
  3961. In POSIX, Windows, and some other systems, this number counts the
  3962. number of seconds since some given start time (the "epoch"). In other
  3963. systems, the meaning is not specified, and the number returned by
  3964. `time` can be used only as an argument to `date` and `difftime`.
  3965. os.tmpname() *os.tmpname()*
  3966. Returns a string with a file name that can be used for a temporary
  3967. file. The file must be explicitly opened before its use and explicitly
  3968. removed when no longer needed.
  3969. ==============================================================================
  3970. 5.9 The Debug Library *luaref-libDebug*
  3971. This library provides the functionality of the debug interface to Lua
  3972. programs. You should exert care when using this library. The functions
  3973. provided here should be used exclusively for debugging and similar tasks, such
  3974. as profiling. Please resist the temptation to use them as a usual programming
  3975. tool: they can be very slow. Moreover, several of its functions violate some
  3976. assumptions about Lua code (e.g., that variables local to a function cannot be
  3977. accessed from outside or that userdata metatables cannot be changed by Lua
  3978. code) and therefore can compromise otherwise secure code.
  3979. All functions in this library are provided inside the `debug` table. All
  3980. functions that operate over a thread have an optional first argument which is
  3981. the thread to operate over. The default is always the current thread.
  3982. debug.debug() *debug.debug()*
  3983. Enters an interactive mode with the user, running each string that the
  3984. user enters. Using simple commands and other debug facilities, the
  3985. user can inspect global and local variables, change their values,
  3986. evaluate expressions, and so on. A line containing only the word
  3987. `cont` finishes this function, so that the caller continues its
  3988. execution.
  3989. Note that commands for `debug.debug` are not lexically nested within
  3990. any function, and so have no direct access to local variables.
  3991. debug.getfenv(o) *debug.getfenv()*
  3992. Returns the environment of object {o}.
  3993. debug.gethook([{thread}]) *debug.gethook()*
  3994. Returns the current hook settings of the thread, as three values: the
  3995. current hook function, the current hook mask, and the current hook
  3996. count (as set by the `debug.sethook` function).
  3997. debug.getinfo([{thread},] {function} [, {what}]) *debug.getinfo()*
  3998. Returns a table with information about a function. You can give the
  3999. function directly, or you can give a number as the value of
  4000. {function}, which means the function running at level {function} of
  4001. the call stack of the given thread: level 0 is the current function
  4002. (`getinfo` itself); level 1 is the function that called `getinfo`; and
  4003. so on. If {function} is a number larger than the number of active
  4004. functions, then `getinfo` returns `nil`.
  4005. The returned table may contain all the fields returned by
  4006. `lua_getinfo` (see |lua_getinfo()|), with the string {what}
  4007. describing which fields to fill in. The default for {what} is to get
  4008. all information available, except the table of valid lines. If
  4009. present, the option `f` adds a field named `func` with the function
  4010. itself. If present, the option `L` adds a field named `activelines`
  4011. with the table of valid lines.
  4012. For instance, the expression `debug.getinfo(1,"n").name` returns the
  4013. name of the current function, if a reasonable name can be found, and
  4014. `debug.getinfo(print)` returns a table with all available information
  4015. about the `print` function.
  4016. debug.getlocal([{thread},] {level}, {local}) *debug.getlocal()*
  4017. This function returns the name and the value of the local variable
  4018. with index {local} of the function at level {level} of the stack. (The
  4019. first parameter or local variable has index 1, and so on, until the
  4020. last active local variable.) The function returns `nil` if there is no
  4021. local variable with the given index, and raises an error when called
  4022. with a {level} out of range. (You can call `debug.getinfo`
  4023. |debug.getinfo()| to check whether the level is valid.)
  4024. Variable names starting with `(` (open parentheses) represent
  4025. internal variables (loop control variables, temporaries, and C
  4026. function locals).
  4027. debug.getmetatable({object}) *debug.getmetatable()*
  4028. Returns the metatable of the given {object} or `nil` if it does not
  4029. have a metatable.
  4030. debug.getregistry() *debug.getregistry()*
  4031. Returns the registry table (see |luaref-apiRegistry|).
  4032. debug.getupvalue({func}, {up}) *debug.getupvalue()*
  4033. This function returns the name and the value of the upvalue with index
  4034. {up} of the function {func}. The function returns `nil` if there is no
  4035. upvalue with the given index.
  4036. debug.setfenv({object}, {table}) *debug.setfenv()*
  4037. Sets the environment of the given {object} to the given {table}.
  4038. Returns {object}.
  4039. debug.sethook([{thread},] {hook}, {mask} [, {count}]) *debug.sethook()*
  4040. Sets the given function as a hook. The string {mask} and the number
  4041. {count} describe when the hook will be called. The string mask may
  4042. have the following characters, with the given meaning:
  4043. - `"c"` : The hook is called every time Lua calls a function;
  4044. - `"r"` : The hook is called every time Lua returns from a function;
  4045. - `"l"` : The hook is called every time Lua enters a new line of
  4046. code.
  4047. With a {count} different from zero, the hook is called after every
  4048. {count} instructions.
  4049. When called without arguments, the `debug.sethook` turns off the hook.
  4050. When the hook is called, its first parameter is a string describing
  4051. the event that triggered its call: `"call"`, `"return"` (or `"tail
  4052. return"`), `"line"`, and `"count"`. For line events, the hook also
  4053. gets the new line number as its second parameter. Inside a hook, you
  4054. can call `getinfo` with level 2 to get more information about the
  4055. running function (level 0 is the `getinfo` function, and level 1 is
  4056. the hook function), unless the event is `"tail return"`. In this case,
  4057. Lua is only simulating the return, and a call to `getinfo` will return
  4058. invalid data.
  4059. debug.setlocal([{thread},] {level}, {local}, {value}) *debug.setlocal()*
  4060. This function assigns the value {value} to the local variable with
  4061. index {local} of the function at level {level} of the stack. The
  4062. function returns `nil` if there is no local variable with the given
  4063. index, and raises an error when called with a {level} out of range.
  4064. (You can call `getinfo` to check whether the level is valid.)
  4065. Otherwise, it returns the name of the local variable.
  4066. debug.setmetatable({object}, {table}) *debug.setmetatable()*
  4067. Sets the metatable for the given {object} to the given {table} (which
  4068. can be `nil`).
  4069. debug.setupvalue({func}, {up}, {value}) *debug.setupvalue()*
  4070. This function assigns the value {value} to the upvalue with index {up}
  4071. of the function {func}. The function returns `nil` if there is no
  4072. upvalue with the given index. Otherwise, it returns the name of the
  4073. upvalue.
  4074. debug.traceback([{thread},] [{message}] [,{level}]) *debug.traceback()*
  4075. Returns a string with a traceback of the call stack. An optional
  4076. {message} string is appended at the beginning of the traceback. An
  4077. optional {level} number tells at which level to start the traceback
  4078. (default is 1, the function calling `traceback`).
  4079. ==============================================================================
  4080. A BIBLIOGRAPHY *luaref-bibliography*
  4081. This help file is a minor adaptation from this main reference:
  4082. - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes.,
  4083. "Lua: 5.1 reference manual", https://www.lua.org/manual/5.1/manual.html
  4084. Lua is discussed in these references:
  4085. - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes.,
  4086. "Lua --- an extensible extension language".
  4087. "Software: Practice & Experience" 26, 6 (1996) 635-652.
  4088. - L. H. de Figueiredo, R. Ierusalimschy, and W. Celes.,
  4089. "The design and implementation of a language for extending applications".
  4090. "Proc. of XXI Brazilian Seminar on Software and Hardware" (1994) 273-283.
  4091. - L. H. de Figueiredo, R. Ierusalimschy, and W. Celes.,
  4092. "Lua: an extensible embedded language".
  4093. "Dr. Dobb's Journal" 21, 12 (Dec 1996) 26-33.
  4094. - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes.,
  4095. "The evolution of an extension language: a history of Lua".
  4096. "Proc. of V Brazilian Symposium on Programming Languages" (2001) B-14-B-28.
  4097. ==============================================================================
  4098. B COPYRIGHT AND LICENSES *luaref-copyright*
  4099. This help file has the same copyright and license as Lua 5.1 and the Lua 5.1
  4100. manual:
  4101. Copyright (c) 1994-2006 Lua.org, PUC-Rio.
  4102. Permission is hereby granted, free of charge, to any person obtaining a copy
  4103. of this software and associated documentation files (the "Software"), to deal
  4104. in the Software without restriction, including without limitation the rights
  4105. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  4106. copies of the Software, and to permit persons to whom the Software is
  4107. furnished to do so, subject to the following conditions:
  4108. The above copyright notice and this permission notice shall be included in all
  4109. copies or substantial portions of the Software.
  4110. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4111. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4112. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4113. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4114. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4115. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  4116. SOFTWARE.
  4117. ==============================================================================
  4118. C LUAREF DOC *luarefvim* *luarefvimdoc* *luaref-help* *luaref-doc*
  4119. This is a Vim help file containing a reference for Lua 5.1, and it is -- with
  4120. a few exceptions and adaptations -- a copy of the Lua 5.1 Reference Manual
  4121. (see |luaref-bibliography|). For usage information, refer to
  4122. |luaref-doc|. For copyright information, see |luaref-copyright|.
  4123. The main ideas and concepts on how to implement this reference were taken from
  4124. Christian Habermann's CRefVim project
  4125. (https://www.vim.org/scripts/script.php?script_id=614).
  4126. Adapted for bundled Nvim documentation; the original plugin can be found at
  4127. https://www.vim.org/scripts/script.php?script_id=1291
  4128. ------------------------------------------------------------------------------
  4129. vi:tw=78:ts=4:ft=help:norl:et