Nvim:help pages,generated fromsource using thetree-sitter-vimdoc parser.
{ a } means 0 or morea's, and[ a ] means an optionala.and break do else elseifend false for function ifin local nil not orrepeat return then true until while
and is a reserved word, butAnd andAND aretwo different, valid names. As a convention, names starting with an underscorefollowed by uppercase letters (such as_VERSION) are reserved for internalglobal variables used by Lua.+ - * / % ^ #== ~= <= >= < > =( ) { } [ ]; : , . .. ...\a bell\b backspace\f form feed\n newline\r carriage return\t horizontal tab\v vertical tab\\ backslash\" quotation mark (double quote)\' apostrophe (single quote)\ddd, whereddd is a sequence of up to threedecimal digits. (Note that if a numerical escape is to be followed by a digit,it must be expressed using exactly three digits.) Strings in Lua may containany 8-bit value, including embedded zeros, which can be specified as\0.[[, an opening longbracket of level 1 is written as[=[, and so on.A closing long bracket is defined similarly; for instance, a closing longbracket of level 4 is written as]====]. A long string starts with anopening long bracket of any level and ends at the first closing long bracketof the same level. Literals in this bracketed form may run for several lines,do not interpret any escape sequences, and ignore long brackets of any otherlevel. They may contain anything except a closing bracket of the proper level.a is coded as 97, newline is coded as 10, and1 iscoded as 49), the five literals below denote the same string:a = 'alo\n123"'a = "alo\n123\""a = '\97lo\10\04923"'a = [[alo123"]]a = [==[alo123"]==]0x. Examples of valid numerical constants are3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56
--) anywhere outside a string. If thetext immediately after-- is not an opening long bracket, the comment is ashort comment, which runs until the end of the line. Otherwise, it is a longcomment, which runs until the corresponding closing long bracket. Longcomments are frequently used to disable code temporarily.nil,boolean,number,string,function,userdata,thread, andtable. Nil is the type of the valuenil, whose main property is to be different from any other value; it usuallyrepresents the absence of a useful value. Boolean is the type of the valuesfalse andtrue. Bothnil andfalse make a condition false; any othervalue makes it true. Number represents real (double-precision floating-point)numbers. (It is easy to build Lua interpreters that use other internalrepresentations for numbers, such as single-precision float or long integers;see fileluaconf.h.) String represents arrays of characters. Lua is 8-bitclean: strings may contain any 8-bit character, including embedded zeros(\0) (seelua-literal).thread represents independent threads of execution and it is used toimplement coroutines (seelua-coroutine). Do not confuse Lua threads withoperating-system threads. Lua supports coroutines on all systems, even thosethat do not support threads.table implements associative arrays, that is, arrays that can beindexed not only with numbers, but with any value (exceptnil). Tables canbe heterogeneous; that is, they can contain values of all types (exceptnil). Tables are the sole data structuring mechanism in Lua; they may beused to represent ordinary arrays, symbol tables, sets, records, graphs,trees, etc. To represent records, Lua uses the field name as an index. Thelanguage supports this representation by providinga.name as syntactic sugarfora["name"]. There are several convenient ways to create tables in Lua(seelua-tableconstructor).nil). Inparticular, because functions are first-class values, table fields may containfunctions. Thus tables may also carry methods (seelua-function-define).type returns a string describing the type of a givenvalue (seelua-type()).format function from the string library (seestring.format()).var ::= Name
nil.var ::= prefixexp [ exp ]
prefixexp) should result in a table value; the secondexpression (exp) identifies a specific entry inside that table. Theexpression denoting the table to be indexed has a restricted syntax; seelua-expressions for details.var.NAME is just syntactic sugar forvar["NAME"] :var ::= prefixexp . Name
getfenv (seelua_getfenv()). To replace it, you callsetfenv (seesetfenv()).(You can only manipulate the environment of C functions through the debuglibrary; seelua-lib-debug.)x is equivalent to_env.x, which in turn isequivalent togettable_event(_env, "x")_env is the environment of the running function. (The_env variable isnot defined in Lua. We use it here only for explanatory purposes.)t[i] is equivalent to acallgettable_event(t,i). (Seelua-metatable for a complete description ofthegettable_event function. This function is not defined or callable inLua. We use it here only for explanatory purposes.)chunk ::= {stat [ ; ]};; is not legal.luac fordetails. Programs in source and compiled forms are interchangeable; Luaautomatically detects the file type and acts accordingly.block ::= chunk
stat ::= do block end
return orbreak statementin the middle of another block (seelua-control).stat ::= varlist1 = explist1varlist1 ::= var { , var }explist1 ::= exp { , exp }nils as needed. If the list of expressions ends with a functioncall, then all values returned by this call enter in the list of values,before the adjustment (except when the call is enclosed in parentheses; seelua-expressions).i = 3i, a[i] = i+1, 20a[3] to 20, without affectinga[4] because thei ina[i] is evaluated (to3) before it is assigned 4. Similarly, the linex, y = y, xx andy.t[i] = val isequivalent tosettable_event(t,i,val). (Seelua-metatable for a completedescription of thesettable_event function. This function is not defined orcallable in Lua. We use it here only for explanatory purposes.)x = val is equivalent to theassignment_env.x = val, which in turn is equivalent tosettable_event(_env, "x", val)_env is the environment of the running function. (The_env variable isnot defined in Lua. We use it here only for explanatory purposes.)if,while, andrepeat have the usual meaning andfamiliar syntax:stat ::= while exp do block endstat ::= repeat block until expstat ::= if exp then block { elseif exp then block } [ else block ] endfor statement, in two flavors (seelua-for).false andnil are considered false. All values differentfromnil andfalse are considered true (in particular, the number 0 and theempty string are also true).repeat-until loop, the inner block does not end at theuntil keyword,but only after the condition. So, the condition can refer to local variablesdeclared inside the loop block.return statement is used to return values from a function or a chunk(which is just a function). Functions and chunks may return more than onevalue, so the syntax for thereturn statement isstat ::=return[explist1]break statement is used to terminate the execution of awhile,repeat,orfor loop, skipping to the next statement after the loop:stat ::=breakbreak ends the innermost enclosing loop.return andbreak statements can only be written as thelaststatement of a block. If it is really necessary toreturn orbreak in themiddle of a block, then an explicit inner block can be used, as in the idiomsdo return end anddo break end, because nowreturn andbreak arethe last statements in their (inner) blocks.for statement has two forms: one numeric and one generic.for loop repeats a block of code while a control variable runsthrough an arithmetic progression. It has the following syntax:stat ::= for Name = exp , exp [ , exp ] do block end
block is repeated forname starting at the value of the firstexp, untilit passes the secondexp by steps of the thirdexp. More precisely,afor statement likefor var = e1, e2, e3 do block enddo local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3) if not ( var and limit and step ) then error() end while ( step >0 and var <= limit ) or ( step <=0 and var >= limit ) do block var = var + step endendvar,limit andstep are invisible variables. The names are here for explanatory purposes only.break to exit afor loop.var is local to the loop; you cannot use its value after thefor ends or is broken. If you need this value, assign it to another variable before breaking or exiting the loop.for statement works over functions, callediterators. On eachiteration, the iterator function is called to produce a new value, stoppingwhen this new value isnil. The genericfor loop has the following syntax:stat ::= for namelist in explist1 do block endnamelist ::= Name { , Name }for statement likeforvar1, ..., varninexplistdoblockenddo local f, s, var = explist while true do local var1, ..., varn = f(s, var) var = var1 if var == nil then break end block endendexplist is evaluated only once. Its results are an iterator function, astate, and an initial value for the first iterator variable.f,s, andvar are invisible variables. The names are here for explanatory purposes only.break to exit afor loop.var1, ..., varn are local to the loop; you cannot use their values after thefor ends. If you need these values, then assign them to other variables before breaking or exiting the loop.stat ::= functioncall
stat ::= local namelist [ = explist1 ]namelist ::= Name { , Name }nil.exp ::= prefixexpexp ::= nil | false | trueexp ::= Numberexp ::= Stringexp ::= functionexp ::= tableconstructorexp ::= ...exp ::= exp binop expexp ::= unop expprefixexp ::= var | functioncall | ( exp )
...), can only be used inside vararg functions;they are explained inlua-function-define.not (seelua-logicalop), and the unary length operator (seelua-length).f() -- adjusted to 0 resultsg(f(), x) -- f() is adjusted to 1 resultg(x, f()) -- g gets x plus all results from f()a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)a,b = ... -- a gets the first vararg parameter, b gets -- the second (both a and b may get nil if there -- is no corresponding vararg parameter)a,b,c = x, f() -- f() is adjusted to 2 resultsa,b,c = f() -- f() is adjusted to 3 resultsreturn f() -- returns all results from f()return ... -- returns all received vararg parametersreturn x,y,f() -- returns x, y, and all results from f(){f()} -- creates a list with all results from f(){...} -- creates a list with all vararg parameters{f(), nil} -- f() is adjusted to 1 result(f(x,y,z)) is always a single value, even iff returns several values.(The value of(f(x,y,z)) is the first value returned byf ornil iff does notreturn any values.)+ (addition),- (subtraction),* (multiplication),/ (division),% (modulo)and^ (exponentiation); and unary- (negation). If the operands are numbers,or strings that can be converted to numbers (seelua-coercion), then alloperations have the usual meaning. Exponentiation works for any exponent. Forinstance,x^(-0.5) computes the inverse of the square root ofx. Modulo isdefined asa % b == a - math.floor(a/b)*b== ~= < > <= >=
false ortrue.==) first compares the type of its operands. If the types aredifferent, then the result isfalse. Otherwise, the values of the operandsare compared. Numbers and strings are compared in the usual way. Objects(tables, userdata, threads, and functions) are compared by reference: twoobjects are considered equal only if they are the same object. Every time youcreate a new object (a table, userdata, or function), this new object isdifferent from any previously existing object."0"==0 evaluates tofalse, andt[0] andt["0"] denote different entries in a table.~= is exactly the negation of equality (==).and or not
false andnil as false and anything else as true.not always returnsfalse ortrue. The conjunctionoperatorand returns its first argument if this value isfalse ornil;otherwise,and returns its second argument. The disjunctionoperatoror returns its first argument if this value is differentfromnil andfalse; otherwise,or returns its second argument.Bothand andor use short-cut evaluation, that is, the second operand isevaluated only if necessary. Here are some examples:10 or 20 --> 1010 or error() --> 10nil or "a" --> "a"nil and 10 --> nilfalse and error() --> falsefalse and nil --> falsefalse or nil --> nil10 and 20 --> 20
--> indicates the result of the preceding expression.)..).If both operands are strings or numbers, then they are converted to stringsaccording to the rules mentioned inlua-coercion. Otherwise, the"concat" metamethod is called (seelua-metatable).#. The length of astring is its number of bytes (that is, the usual meaning of string lengthwhen each character is one byte).t is defined to be any integer indexn such thatt[n] isnotnil andt[n+1] isnil; moreover, ift[1] isnil,n may be zero. For aregular array, with non-nil values from 1 to a givenn, its length is exactlythatn, the index of its last value. If the array has "holes" (thatis,nil values between other non-nil values), then#t may be any of theindices that directly precedes anil value (that is, it may consider anysuchnil value as the end of the array).orand< > <= >= ~= ==..+ -* /not # - (unary)^
..) and exponentiation (^) operators are rightassociative. All other binary operators are left associative.tableconstructor ::= { [ fieldlist ] }fieldlist ::= field { fieldsep field } [ fieldsep ]field ::= [ exp ] = exp | Name = exp | expfieldsep ::= , | ;[exp1] = exp2 adds to the new table an entry withkeyexp1 and valueexp2. A field of the formname = exp is equivalent to["name"] = exp. Finally, fields of the formexp are equivalent to[i] = exp, wherei are consecutive numerical integers, starting with 1.Fields in the other formats do not affect this counting. For example,a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }do local t = {} t[f(1)] = g t[1] = "x" -- 1st exp t[2] = "y" -- 2nd exp t.x = 1 -- temp["x"] = 1 t[3] = f(x) -- 3rd exp t[30] = 23 t[4] = 45 -- 4th exp a = tendexp and the expression is afunction call, then all values returned by the call enter the listconsecutively (seelua-function). To avoid this, enclose the functioncall in parentheses (seelua-expressions).functioncall ::= prefixexp args
prefixexp andargs are evaluated. If the valueofprefixexp has typefunction, then this function is called with the givenarguments. Otherwise, theprefixexp "call" metamethod is called, having asfirst parameter the value ofprefixexp, followed by the original callarguments (seelua-metatable).functioncall ::= prefixexp : Name args
v:name(args) is syntactic sugarforv.name(v,args), except thatv is evaluated only once.args ::= ( [ explist1 ] )args ::= tableconstructorargs ::= String
f{fields} is syntactic sugar forf({fields}), that is, theargument list is a single new table. A call of the formf'string'(orf"string" orf[[string]]) is syntactic sugar forf('string'), that is, the argument list is a single literal string.( in a function call. This restriction avoids some ambiguitiesin the language. If you writea = f(g).x(a)a = f(g).x(a). So, if you want twostatements, you must add a semi-colon between them. If you actually want tocallf, you must remove the line break before(g).returnfunctioncall is called a tail call. Luaimplements proper tail calls (or proper tail recursion): in a tail call, thecalled function reuses the stack entry of the calling function. Therefore,there is no limit on the number of nested tail calls that a program canexecute. However, a tail call erases any debug information about the callingfunction. Note that a tail call only happens with a particular syntax, wherethereturn has one single function call as argument; this syntax makes thecalling function return exactly the returns of the called function. So, noneof the following examples are tail calls:return (f(x)) -- results adjusted to 1return 2 * f(x)return x, f(x) -- additional resultsf(x); return -- results discardedreturn x or f(x) -- results adjusted to 1function ::= function funcbodyfuncbody ::= ( [ parlist1 ] ) block end
stat ::= function funcname funcbodystat ::= local function Name funcbodyfuncname ::= Name { . Name } [ : Name ]function f ()bodyendf = function ()bodyendfunction t.a.b.c.f ()bodyendt.a.b.c.f = function ()bodyendlocal function f ()bodyendlocal f; f = function f ()bodyendlocal f = function f ()bodyendf.)function. When Lua pre-compiles a chunk, all its function bodies arepre-compiled too. Then, whenever Lua executes the function definition, thefunction is instantiated (or closed). This function instance (or closure) isthe final value of the expression. Different instances of the same functionmay refer to different external local variables and may have differentenvironment tables.parlist1 ::= namelist [ , ... ] | ...
...) at the end of its parameter list. Avararg function does not adjust its argument list; instead, it collects allextra arguments and supplies them to the function through a vararg expression,which is also written as three dots. The value of this expression is a list ofall actual extra arguments, similar to a function with multiple results. If avararg expression is used inside another expression or in the middle of a listof expressions, then its return list is adjusted to one element. If theexpression is used as the last element of a list of expressions, then noadjustment is made (unless the call is enclosed in parentheses).function f(a, b) endfunction g(a, b, ...) endfunction r() return 1,2,3 endCALL PARAMETERSf(3) a=3, b=nilf(3, 4) a=3, b=4f(3, 4, 5) a=3, b=4f(r(), 10) a=1, b=10f(r()) a=1, b=2g(3) a=3, b=nil, ... --> (nothing)g(3, 4) a=3, b=4, ... --> (nothing)g(3, 4, 5, 8) a=3, b=4, ... --> 5 8g(5, r()) a=5, b=1, ... --> 2 3
return statement (seelua-control).If control reaches the end of a function without encounteringareturn statement, then the function returns with no results.self. Thus, the statementfunction t.a.b.c:f (params)bodyendt.a.b.c:f = function (self,params)bodyendx = 10 -- global variabledo -- new block local x = x -- new `x`, with value 10 print(x) --> 10 x = x+1 do -- another block local x = x+1 -- another `x` print(x) --> 12 end print(x) --> 11endprint(x) --> 10 (the global one)local x = x, the newx being declared isnot in scope yet, and so the secondx refers to the outside variable.a = {}local x = 20for i=1,10 do local y = 0 a[i] = function () y=y+1; return x+y endendy variable, while all ofthem share the samex.error function (seeerror()). If you need to catch errors in Lua, you can use thepcallfunction (seepcall())."__add" in its metatable. If it finds one, Lua calls that functionto perform the addition.getmetatable function(seegetmetatable()).setmetatable function (seesetmetatable()). You cannot change the metatable of other types from Lua(except using the debug library); you must use the C API for that.__; for instance, the key for operation "add"is the string "__add". The semantics of these operations is better explainedby a Lua function describing how the interpreter executes that operation.rawget,tonumber, etc.) aredescribed inlua-lib-core. In particular, to retrieve the metamethod of agiven object, we use the expressionmetatable(obj)[event]
rawget(metatable(obj) or {}, event)nil).getbinhandler below defines how Lua chooses a handler for abinary operation. First, Lua tries the first operand. If its type does notdefine a handler for the operation, then Lua tries the second operand.function getbinhandler (op1, op2, event) return metatable(op1)[event] or metatable(op2)[event]endop1 + op2 isfunction add_event (op1, op2) local o1, o2 = tonumber(op1), tonumber(op2) if o1 and o2 then -- both operands are numeric? return o1 + o2 -- `+` here is the primitive `add` else -- at least one of the operands is not numeric local h = getbinhandler(op1, op2, "__add") if h then -- call the handler with both operands return h(op1, op2) else -- no handler available: default behavior error(...) end endend% operation. Behavior similar to the "add" operation, with theoperationo1 - floor(o1/o2)*o2 as the primitive operation.^ (exponentiation) operation. Behavior similar to the "add" operation,with the functionpow (from the C math library) as the primitive operation.- operation.function unm_event (op) local o = tonumber(op) if o then -- operand is numeric? return -o -- `-` here is the primitive `unm` else -- the operand is not numeric. -- Try to get a handler from the operand local h = metatable(op).__unm if h then -- call the handler with the operand return h(op) else -- no handler available: default behavior error(...) end endend.. (concatenation) operation.function concat_event (op1, op2) if (type(op1) == "string" or type(op1) == "number") and (type(op2) == "string" or type(op2) == "number") then return op1 .. op2 -- primitive string concatenation else local h = getbinhandler(op1, op2, "__concat") if h then return h(op1, op2) else error(...) end endend# operation.function len_event (op) if type(op) == "string" then return strlen(op) -- primitive string length elseif type(op) == "table" then return #op -- primitive table length else local h = metatable(op).__len if h then -- call the handler with the operand return h(op) else -- no handler available: default behavior error(...) end endendgetcomphandler defines how Lua chooses a metamethod forcomparison operators. A metamethod only is selected when both objects beingcompared have the same type and the same metamethod for the selectedoperation.function getcomphandler (op1, op2, event) if type(op1) ~= type(op2) then return nil end local mm1 = metatable(op1)[event] local mm2 = metatable(op2)[event] if mm1 == mm2 then return mm1 else return nil endendfunction eq_event (op1, op2) if type(op1) ~= type(op2) then -- different types? return false -- different objects end if op1 == op2 then -- primitive equal? return true -- objects are equal end -- try metamethod local h = getcomphandler(op1, op2, "__eq") if h then return h(op1, op2) else return false endenda ~= b is equivalent tonot (a == b).< operation.function lt_event (op1, op2) if type(op1) == "number" and type(op2) == "number" then return op1 < op2 -- numeric comparison elseif type(op1) == "string" and type(op2) == "string" then return op1 < op2 -- lexicographic comparison else local h = getcomphandler(op1, op2, "__lt") if h then return h(op1, op2) else error(...); end endenda > b is equivalent tob < a.<= operation.function le_event (op1, op2) if type(op1) == "number" and type(op2) == "number" then return op1 <= op2 -- numeric comparison elseif type(op1) == "string" and type(op2) == "string" then return op1 <= op2 -- lexicographic comparison else local h = getcomphandler(op1, op2, "__le") if h then return h(op1, op2) else h = getcomphandler(op1, op2, "__lt") if h then return not h(op2, op1) else error(...); end end endenda >= b is equivalent tob <= a. Note that, in the absence of a "le"metamethod, Lua tries the "lt", assuming thata <= b is equivalenttonot (b < a).table[key].function gettable_event (table, key) local h if type(table) == "table" then local v = rawget(table, key) if v ~= nil then return v end h = metatable(table).__index if h == nil then return nil end else h = metatable(table).__index if h == nil then error(...); end end if type(h) == "function" then return h(table, key) -- call the handler else return h[key] -- or repeat operation on itendtable[key] = value.function settable_event (table, key, value) local h if type(table) == "table" then local v = rawget(table, key) if v ~= nil then rawset(table, key, value); return end h = metatable(table).__newindex if h == nil then rawset(table, key, value); return end else h = metatable(table).__newindex if h == nil then error(...); end end if type(h) == "function" then return h(table, key,value) -- call the handler else h[key] = value -- or repeat operation on itendfunction function_event (func, ...) if type(func) == "function" then return func(...) -- primitive call else local h = metatable(func).__call if h then return h(func, ...) else error(...) end endendsetfenv. You can get the environment of a Lua function or therunning thread by callinggetfenv (seelua_getfenv()). To manipulate theenvironment of other objects (userdata, C functions, other threads) you mustuse the C API.lua_gc (seelua_gc()) in C orcollectgarbage (seecollectgarbage()) in Lua. Both get percentage pointsas arguments (so an argument of 100 means a real value of 1). With thesefunctions you can also control the collector directly (e.g., stop and restartit).__gc in their metatables are not collectedimmediately by the garbage collector. Instead, Lua puts them in a list. Afterthe collection, Lua does the equivalent of the following function for eachuserdata in that list:function gc_event (udata) local h = metatable(udata).__gc if h then h(udata) endend__mode field of its metatable. If the__mode field is astring containing the characterk, the keys in the table are weak.If__mode containsv, the values in the table are weak.__mode. Otherwise, the weak behavior of the tables controlled by thismetatable is undefined.coroutine.create (seecoroutine.create()). Its sole argument is a function that is the mainfunction of the coroutine. Thecreate function only creates a new coroutineand returns a handle to it (an object of typethread); it does not start thecoroutine execution.coroutine.resume (seecoroutine.resume()),passing as its first argument the thread returned bycoroutine.create, thecoroutine starts its execution, at the first line of its main function. Extraarguments passed tocoroutine.resume are passed on to the coroutine mainfunction. After the coroutine starts running, it runs until it terminates oryields.coroutine.resume returnstrue, plus any values returned by the coroutinemain function. In case of errors,coroutine.resume returnsfalse plus anerror message.coroutine.yield (seecoroutine.yield()). When a coroutine yields, the correspondingcoroutine.resume returns immediately, even if the yield happens insidenested function calls (that is, not in the main function, but in a functiondirectly or indirectly called by the main function). In the case of a yield,coroutine.resume also returnstrue, plus any values passed tocoroutine.yield. The next time you resume the same coroutine, it continuesits execution from the point where it yielded, with the call tocoroutine.yield returning any extra arguments passed tocoroutine.resume.coroutine.create, thecoroutine.wrap function (seecoroutine.wrap()) also creates a coroutine, but instead of returningthe coroutine itself, it returns a function that, when called, resumes thecoroutine. Any arguments passed to this function go as extra arguments tocoroutine.resume.coroutine.wrap returns all the values returned bycoroutine.resume, except the first one (the boolean error code). Unlikecoroutine.resume,coroutine.wrap does not catch errors; any error ispropagated to the caller.function foo1 (a) print("foo", a) return coroutine.yield(2*a)endco = coroutine.create(function (a,b) print("co-body", a, b) local r = foo1(a+1) print("co-body", r) local r, s = coroutine.yield(a+b, a-b) print("co-body", r, s) return b, "end"end)print("main", coroutine.resume(co, 1, 10))print("main", coroutine.resume(co, "r"))print("main", coroutine.resume(co, "x", "y"))print("main", coroutine.resume(co, "x", "y"))co-body 1 10foo 2main true 4co-body rmain true 11 -9co-body x ymain true 10 endmain false cannot resume dead coroutine
lua.h.macro instead. All such macros use each of its arguments exactly once(except for the first argument, which is always a Lua state), and so do notgenerate hidden side-effects.luai_apicheck,in fileluaconf.h.nil, number, string, etc.).n elements, then index 1 represents the firstelement (that is, the element that was pushed onto the stack first) and indexn represents the last element; index-1 also represents the last element(that is, the element at the top) and index-n represents the first element.We say that an index is valid if it lies between 1 and the stack top (that is,if1 <= abs(index) <= top).lua_checkstack to grow the stack size (seelua_checkstack()).LUA_MINSTACK stack positionsare available.LUA_MINSTACK is defined as 20, so that usually you do nothave to worry about stack space unless your code has loops pushing elementsonto the stack.lua_checkstack. Such indices are called acceptable indices. More formally,we define an acceptable index as follows:(index < 0 && abs(index) <= top) || (index > 0 && index <= stackspace)LUA_GLOBALSINDEX. The environment of the running C function is always atpseudo-indexLUA_ENVIRONINDEX.lua_getfield(L, LUA_GLOBALSINDEX, varname);lua_upvalueindex. The first value associated with a function is at positionlua_upvalueindex(1), and so on. Any access tolua_upvalueindex(n),wheren is greater than the number of upvalues of the current function,produces an acceptable (but invalid) index.LUA_REGISTRYINDEX. Any C library can store data into thistable, but it should take care to choose keys different from those used byother libraries, to avoid collisions. Typically, you should use as key astring containing your library name or a light userdata with the address of aC object in your code.longjmp facility to handle errors. (You can alsochoose to use exceptions if you use C++; see fileluaconf.h.) When Lua facesany error (such as memory allocation errors, type errors, syntax errors, andruntime errors) it raises an error; that is, it does a long jump. A protectedenvironment usessetjmp to set a recover point; any error jumps to the mostrecent active recover point.lua_newstate,lua_close,lua_load,lua_pcall, andlua_cpcall (seelua_newstate(),lua_close(),lua_load(),lua_pcall(), andlua_cpcall()).lua_error (seelua_error()).realloc, but not exactly the same. Its arguments areud, an opaque pointer passed tolua_newstate (seelua_newstate());ptr, a pointer to the block being allocated/reallocated/freed;osize, the original size of the block;nsize, the new size of the block.ptr isNULL if and only ifosize is zero. Whennsize is zero, the allocator must returnNULL; ifosize is not zero, it should free the block pointed to byptr. Whennsize is not zero, the allocator returnsNULL if and only if it cannot fill the request. Whennsize is not zero andosize is zero, the allocator should behave likemalloc. Whennsize andosize are not zero, the allocator behaves likerealloc. Lua assumes that the allocator never fails whenosize >= nsize.luaL_newstate (seeluaL_newstate()).static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; /* not used */ if (nsize == 0) { free(ptr); return NULL; } else return realloc(ptr, nsize);}free(NULL) has no effect and thatrealloc(NULL, size) is equivalent tomalloc(size). ANSI C ensures both behaviors.panicfunction and then callsexit(EXIT_FAILURE), thus exiting the host application. Your panic function may avoid this exit by never returning (e.g., doing a long jump).lua_call;nargs is the number of arguments that you pushed onto the stack. All arguments and the function value are popped from the stack when the function is called. The function results are pushed onto the stack when the function returns. The number of results is adjusted tonresults, unlessnresults isLUA_MULTRET. In this case,all results from the function are pushed. Lua takes care that the returned values fit into the stack space. The function results are pushed onto the stack in direct order (the first result is pushed first), so that after the call the last result is on the top of the stack.longjmp).a = f("how", t.x, 14)lua_getfield(L, LUA_GLOBALSINDEX, "f"); // function to be calledlua_pushstring(L, "how"); // 1st argumentlua_getfield(L, LUA_GLOBALSINDEX, "t"); // table to be indexedlua_getfield(L, -1, "x"); // push result of t.x (2nd arg)lua_remove(L, -2); // remove 't' from the stacklua_pushinteger(L, 14); // 3rd argumentlua_call(L, 3, 1); // call 'f' with 3 arguments and 1 resultlua_setfield(L, LUA_GLOBALSINDEX, "a"); // set global 'a'lua_gettop(L) (seelua_gettop()) returns the number of arguments received by the function. The first argument (if any) is at index 1 and its last argument is at indexlua_gettop(L). To return values to Lua, a C function just pushes them onto the stack, in direct order (the first result is pushed first), and returns the number of results. Any other value in the stack below the results will be properly discarded by Lua. Like a Lua function, a C function called by Lua can also return many results.static int foo (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ lua_Number sum = 0; int i; for (i = 1; i <= n; i++) { if (!lua_isnumber(L, i)) { lua_pushstring(L, "incorrect argument"); lua_error(L); } sum += lua_tonumber(L, i); } lua_pushnumber(L, sum/n); /* first result */ lua_pushnumber(L, sum); /* second result */ return 2; /* number of results */}extra free stack slots in the stack. It returns false if it cannot grow the stack to that size. This function never shrinks the stack; if the stack is already larger than the new size, it is left unchanged.n values at the top of the stack, pops them, and leaves the result at the top. Ifn is 1, the result is the single string on the stack (that is, the function does nothing); ifn is 0, the result is the empty string. Concatenation is done following the usual semantics of Lua (seelua-concat).func in protected mode.func starts with only one element in its stack, a light userdata containingud. In case of errors,lua_cpcall returns the same error codes aslua_pcall (seelua_pcall()), plus the error object on the top of the stack; otherwise, it returns zero, and does not change the stack. All values returned byfunc are discarded.narr array elements andnrec non-array elements. This pre-allocation is useful when you know exactly how many elements the table will have. Otherwise you can use the functionlua_newtable (seelua_newtable()).lua_dump calls functionwriter (seelua_Writer) with the givendata to write them.index1 andindex2 are equal, following the semantics of the Lua== operator (that is, may call metamethods). Otherwise returns 0. Also returns 0 if any of the indices is non valid.what:LUA_GCSTOP stops the garbage collector.LUA_GCRESTART restarts the garbage collector.LUA_GCCOLLECT performs a full garbage-collection cycle.LUA_GCCOUNT returns the current amount of memory (in Kbytes) in use by Lua.LUA_GCCOUNTB returns the remainder of dividing the current amount of bytes of memory in use by Lua by 1024.LUA_GCSTEP performs an incremental step of garbage collection. The step "size" is controlled bydata (larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value ofdata. The function returns 1 if the step finished a garbage-collection cycle.LUA_GCSETPAUSE setsdata /100 as the new value for thepause of the collector (seelua-gc). The function returns the previous value of the pause.LUA_GCSETSTEPMULsetsdata /100 as the new value for thestepmultiplier of the collector (seelua-gc). The function returns the previous value of the step multiplier.ud is notNULL, Lua stores in*ud the opaque pointer passed tolua_newstate (seelua_newstate()).t[k], wheret is the value at the given valid indexindex. As in Lua, this function may trigger a metamethod for the "index" event (seelua-metatable).name. It is defined as a macro:#define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s)t[k], wheret is the value at the given valid indexindex andk is the value at the top of the stack.ptrdiff_t, which is usually the largest integral type the machine handles "comfortably".nil, and 0 otherwise.index1 is smaller than the value at acceptable indexindex2, following the semantics of the Lua< operator (that is, may call metamethods). Otherwise returns 0. Also returns 0 if any of the indices is non valid.int lua_load (lua_State *L, lua_Reader reader, void *data, const char *chunkname);lua_load pushes the compiled chunk as a Lua function on top of the stack. Otherwise, it pushes an error message. The return values oflua_load are:0: no errors;LUA_ERRSYNTAX : syntax error during pre-compilation;LUA_ERRMEM : memory allocation error.lua_load automatically detects whether the chunk is text or binary, and loads it accordingly (see programluac).lua_load function uses a user-suppliedreader function to read the chunk (seelua_Reader). Thedata argument is an opaque value passed to the reader function.chunkname argument gives a name to the chunk, which is used for error messages and in debug information (seelua-apiDebug).NULL if cannot create the state (due to lack of memory). The argumentf is the allocator function; Lua does all memory allocation for this state through this function. The second argument,ud, is an opaque pointer that Lua simply passes to the allocator in every call.lua_createtable(L, 0, 0) (seelua_createtable()).lua_State (seelua_State) that represents this new thread. The new state returned by this function shares with the original state all global objects (such as tables), but has an independent execution stack.gc metamethod, Lua calls the metamethod and marks the userdata as finalized. When this userdata is collected again then Lua frees its corresponding memory.lua_next returns 0 (and pushes nothing)./* table is in the stack at index 't' */lua_pushnil(L); /* first key */while (lua_next(L, t) != 0) { /* uses 'key' (at index -2) and 'value' (at index -1) */ printf("%s - %s\n", lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1))); /* removes 'value'; keeps 'key' for next iteration */ lua_pop(L, 1);}lua_tolstring (seelua_tolstring()) directly on a key, unless you know that the key is actually a string. Recall thatlua_tolstringchanges the value at the given index; this confuses the next call tolua_next.luaconf.h.#); for userdata, this is the size of the block of memory allocated for the userdata; for other values, it is 0.nargs andnresults have the same meaning as inlua_call (seelua_call()). If there are no errors during the call,lua_pcall behaves exactly likelua_call. However, if there is any error,lua_pcall catches it, pushes a single value on the stack (the error message), and returns an error code. Likelua_call,lua_pcall always removes the function and its arguments from the stack.errfunc is 0, then the error message returned on the stack is exactly the original error message. Otherwise,errfunc is the stack index of anerrorhandler function. (In the current implementation, this index cannot be a pseudo-index.) In case of runtime errors, this function will be called with the error message and its return value will be the message returned on the stack bylua_pcall.lua_pcall, since by then the stack has unwound.lua_pcall function returns 0 in case of success or one of the following error codes (defined inlua.h):LUA_ERRRUN a runtime error.LUA_ERRMEM memory allocation error. For such errors, Lua does not call the error handler function.LUA_ERRERR error while running the error handler function.n elements from the stack.b onto the stack.lua_pushcclosure is called to create and push the C function onto the stack, with the argumentn telling how many values should be associated with the function.lua_pushcclosure also pops these values from the stack.function that, when called, invokes the corresponding C function.lua_pushcfunction is defined as a macro:#define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0)sprintf, but has some important differences:%% (inserts a% in the string),%s (inserts a zero-terminated string, with no size restrictions),%f (inserts alua_Number),%p (inserts a pointer as a hexadecimal numeral),%d (inserts anint), and%c (inserts anint as a character).n onto the stack.s with sizelen onto the stack. Lua makes (or reuses) an internal copy of the given string, so the memory ats can be freed or reused immediately after the function returns. The string can contain embedded zeros.n onto the stack.s onto the stack. Lua makes (or reuses) an internal copy of the given string, so the memory ats can be freed or reused immediately after the function returns. The string cannot contain embedded zeros; it is assumed to end at the first zero.L onto the stack. Returns 1 if this thread is the main thread of its state.const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp);lua_pushfstring (seelua_pushfstring()), except that it receives ava_list instead of a variable number of arguments.index1 andindex2 are primitively equal (that is, without calling metamethods). Otherwise returns 0. Also returns 0 if any of the indices are non valid.lua_gettable (seelua_gettable()), but does a raw access (i.e., without metamethods).t[n], wheret is the value at the given valid indexindex. The access is raw; that is, it does not invoke metamethods.lua_settable (seelua_settable()), but does a raw assignment (i.e., without metamethods).t[n] = v, wheret is the value at the given valid indexindex andv is the value at the top of the stack.lua_load (seelua_load()). Every time it needs another piece of the chunk,lua_load calls the reader, passing along itsdata parameter. The reader must return a pointer to a block of memory with a new piece of the chunk and setsize to the block size. The block must exist until the reader function is called again. To signal the end of the chunk, the reader must returnNULL. The reader function may return pieces of any size greater than zero.f as the new value of globalname. It is defined as a macro:#define lua_register(L,n,f) \ (lua_pushcfunction(L, f), lua_setglobal(L, n))lua_resume (seelua_resume()) withnarg being the number of arguments. This call returns when the coroutine suspends or finishes its execution. When it returns, the stack contains all values passed tolua_yield (seelua_yield()), or all values returned by the body function.lua_resume returnsLUA_YIELD if the coroutine yields, 0 if the coroutine finishes its execution without errors, or an error code in case of errors (seelua_pcall()). In case of errors, the stack is not unwound, so you can use the debug API over it. The error message is on the top of the stack. To restart a coroutine, you put on its stack only the values to be passed as results fromlua_yield, and then calllua_resume.f with user dataud.lua_setfenv returns 0. Otherwise it returns 1.t[k] = v, wheret is the value at the given valid indexindex andv is the value at the top of the stack.name. It is defined as a macro:#define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s)t[k] = v, wheret is the value at the given valid indexindex,v is the value at the top of the stack, andk is the value just below the top.nil. Ifindex is 0, then all stack elements are removed.lua_newstate (seelua_newstate()), which creates a Lua state from scratch.L.LUA_YIELD if the thread is suspended.lua_toboolean returns 1 for any Lua value different fromfalse andnil; otherwise it returns 0. It also returns 0 when called with a non-valid index. (If you want to accept only actual boolean values, uselua_isbooleanlua_isboolean() to test the value's type.)NULL.lua_Integer (seelua_Integer). The Lua value must be a number or a string convertible to a number (seelua-coercion); otherwise,lua_tointeger returns 0.len is notNULL, it also sets*len with the string length. The Lua value must be a string or a number; otherwise, the function returnsNULL. If the value is a number, thenlua_tolstring alsochanges the actual value in the stack to astring. (This change confuseslua_nextlua_next() whenlua_tolstring is applied to keys during a table traversal.)lua_tolstring returns a fully aligned pointer to a string inside the Lua state. This string always has a zero (\0) after its last character (as in C), but may contain other zeros in its body. Because Lua has garbage collection, there is no guarantee that the pointer returned bylua_tolstring will be valid after the corresponding value is removed from the stack.lua_Number (seelua_Number). The Lua value must be a number or a string convertible to a number (seelua-coercion); otherwise,lua_tonumber returns 0.void*). The value may be a userdata, a table, a thread, or a function; otherwise,lua_topointer returnsNULL. Different objects will give different pointers. There is no way to convert the pointer back to its original value.lua_State*lua_State). This value must be a thread; otherwise, the function returnsNULL.NULL.LUA_TNONE for a non-valid index (that is, an index to an "empty" stack position). The types returned bylua_type are coded by the following constants defined inlua.h :LUA_TNIL,LUA_TNUMBER,LUA_TBOOLEAN,LUA_TSTRING,LUA_TTABLE,LUA_TFUNCTION,LUA_TUSERDATA,LUA_TTHREAD, andLUA_TLIGHTUSERDATA.tp, which must be one the values returned bylua_type.lua_dump (seelua_dump()). Every time it produces another piece of chunk,lua_dump calls the writer, passing along the buffer to be written (p), its size (sz), and thedata parameter supplied tolua_dump.lua_dump from calling the writer again.same global state.n values from the stackfrom, and pushes them onto the stackto.return lua_yield (L, nresults);lua_yield in that way, the running coroutine suspends its execution, and the call tolua_resume (seelua_resume()) that started this coroutine returns. The parameternresults is the number of values from the stack that are passed as results tolua_resume.10 20 30 40 50* (from bottom to top; the* marks the top), thenlua_pushvalue(L, 3) --> 10 20 30 40 50 30*lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30*lua_remove(L, -3) --> 10 20 30 40 30 30*lua_remove(L, 6) --> 10 20 30 40 30*lua_insert(L, 1) --> 30 10 20 30 40*lua_insert(L, -1) --> 30 10 20 30 40* (no effect)lua_replace(L, 2) --> 30 40 20 30*lua_settop(L, -3) --> 30 40*lua_settop(L, 6) --> 30 40 nil nil nil nil*
typedef struct lua_Debug { int event; const char *name; /* (n) */ const char *namewhat; /* (n) */ const char *what; /* (S) */ const char *source; /* (S) */ int currentline; /* (l) */ int nups; /* (u) number of upvalues */ int linedefined; /* (S) */ int lastlinedefined; /* (S) */ char short_src[LUA_IDSIZE]; /* (S) */ /* private part */ other fields} lua_Debug;lua_getstack (seelua_getstack()) fills only the private partof this structure, for later use. To fill the other fields oflua_Debug withuseful information, calllua_getinfo (seelua_getinfo()).lua_Debug have the following meaning:source If the function was defined in a string, thensource is that string. If the function was defined in a file, thensource starts with a@ followed by the file name.short_src a "printable" version ofsource, to be used in error messages.linedefined the line number where the definition of the function starts.lastlinedefined the line number where the definition of the function ends.what the string"Lua" if the function is a Lua function,"C" if it is a C function,"main" if it is the main part of a chunk, and"tail" if it was a function that did a tail call. In the latter case, Lua has no other information about the function.currentline the current line where the given function is executing. When no line information is available,currentline is set to -1.name a reasonable name for the given function. Because functions in Lua are first-class values, they do not have a fixed name: some functions may be the value of multiple global variables, while others may be stored only in a table field. Thelua_getinfo function checks how the function was called to find a suitable name. If it cannot find a name, thenname is set toNULL.namewhat explains thename field. The value ofnamewhat can be"global","local","method","field","upvalue", or"" (the empty string), according to how the function was called. (Lua uses the empty string when no other option seems to apply.)nups the number of upvalues of the function.ar must be a valid activation record that was filled by a previous call tolua_getstack (seelua_getstack()) or given as argument to a hook (seelua_Hook).what string with the character>. (In that case,lua_getinfo pops the function in the top of the stack.) For instance, to know in which line a functionf was defined, you can write the following code:lua_Debug ar;lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global 'f' */lua_getinfo(L, ">S", &ar);printf("%d\n", ar.linedefined);what selects some fields of the structurear to be filled or a value to be pushed on the stack:'n' fills in the fieldname andnamewhat'S' fills in the fieldssource,short_src,linedefined,lastlinedefined, andwhat'l' fills in the fieldcurrentline'u' fills in the fieldnups'f' pushes onto the stack the function that is running at the given level'L' pushes onto the stack a table whose indices are the numbers of the lines that are valid on the function. (Avalid line is a line with some associated code, that is, a line where you can put a break point. Non-valid lines include empty lines and comments.)what).ar must be a valid activation record that was filled by a previous call tolua_getstack (seelua_getstack()) or given as argument to a hook (seelua_Hook). The indexn selects which local variable to inspect (1 is the first parameter or active local variable, and so on, until the last active local variable).lua_getlocal pushes the variable's value onto the stack and returns its name.( (open parentheses) represent internal variables (loop control variables, temporaries, and C function locals).NULL (and pushes nothing) when the index is greater than the number of active local variables.lua_Debug (seelua_Debug) structure with an identification of theactivation record of the function executing at a given level. Level 0 is the current running function, whereas leveln+1 is the function that has called leveln. When there are no errors,lua_getstack returns 1; when called with a level greater than the stack depth, it returns 0.lua_getupvalue gets the indexn of an upvalue, pushes the upvalue's value onto the stack, and returns its name.funcindex points to the closure in the stack. (Upvalues have no particular order, as they are active through the whole function. So, they are numbered in an arbitrary order.)NULL (and pushes nothing) when the index is greater than the number of upvalues. For C functions, this function uses the empty string"" as a name for all upvalues.ar argument has its fieldevent set to the specific event that triggered the hook. Lua identifies these events with the following constants:LUA_HOOKCALL,LUA_HOOKRET,LUA_HOOKTAILRET,LUA_HOOKLINE, andLUA_HOOKCOUNT. Moreover, for line events, the fieldcurrentline is also set. To get the value of any other field inar, the hook must calllua_getinfo (seelua_getinfo()). For return events,event may beLUA_HOOKRET, the normal value, orLUA_HOOKTAILRET. In the latter case, Lua is simulating a return from a function that did a tail call; in this case, it is useless to calllua_getinfo.f is the hook function.mask specifies on which events the hook will be called: it is formed by a bitwiseor of the constantsLUA_MASKCALL,LUA_MASKRET,LUA_MASKLINE, andLUA_MASKCOUNT. Thecount argument is only meaningful when the mask includesLUA_MASKCOUNT. For each event, the hook is called as explained below:The call hook: is called when the interpreter calls a function. The hook is called just after Lua enters the new function, before the function gets its arguments.The return hook: is called when the interpreter returns from a function. The hook is called just before Lua leaves the function. You have no access to the values to be returned by the function.The line hook: is called when the interpreter is about to start the execution of a new line of code, or when it jumps back in the code (even to the same line). (This event only happens while Lua is executing a Lua function.)The count hook: is called after the interpreter executes everycount instructions. (This event only happens while Lua is executing a Lua function.)mask to zero.ar andn are as inlua_getlocal (seelua_getlocal()).lua_setlocal assigns the value at the top of the stack to the variable and returns its name. It also pops the value from the stack.NULL (and pops nothing) when the index is greater than the number of active local variables.funcindex andn are as in thelua_getupvalue (seelua_getupvalue()).NULL (and pops nothing) when the index is greater than the number of upvalues.int listvars (lua_State *L, int level) { lua_Debug ar; int i; const char *name; if (lua_getstack(L, level, &ar) == 0) return 0; /* failure: no such level in the stack */ i = 1; while ((name = lua_getlocal(L, &ar, i++)) != NULL) { printf("local %d %s\n", i-1, name); lua_pop(L, 1); /* remove variable value */ } lua_getinfo(L, "f", &ar); /* retrieves function */ i = 1; while ((name = lua_getupvalue(L, -1, i++)) != NULL) { printf("upvalue %d %s\n", i-1, name); lua_pop(L, 1); /* remove upvalue value */ } return 1;}lauxlib.hand have a prefixluaL_.luaL_check* orluaL_opt*. All of thesefunctions raise an error if the check is not satisfied. Because the errormessage is formatted for arguments (e.g., "bad argument #1"), you should notuse these functions for other stack values.s with lengthl to the bufferB (seeluaL_Buffer). The string may contain embedded zeros.B (seeluaL_Buffer) a string of lengthn previously copied to the buffer area (seeluaL_prepbuffer()).s to the bufferB (seeluaL_Buffer). The string may not contain embedded zeros.B (seeluaL_Buffer). Pops the value.void luaL_argcheck (lua_State *L, int cond, int narg, const char *extramsg);cond is true. If not, raises an error with the following message, wherefunc is retrieved from the call stack:bad argument #<narg> to <func> (<extramsg>)
func is retrieved from the call stack:bad argument #<narg> to <func> (<extramsg>)
return luaL_argerror(args).string buffer.b of typeluaL_Buffer.luaL_buffinit(L, &b) (seeluaL_buffinit()).luaL_add* functions.luaL_pushresult(&b) (seeluaL_pushresult()). This call leaves the final string on the top of the stack.luaL_addvalueluaL_addvalue().) After callingluaL_pushresult the stack is back to its level when the buffer was initialized, plus the final string on its top.B. This function does not allocate any space; the buffer must be declared as a variable (seeluaL_Buffer).obj has a metatable and this metatable has a fielde, this function calls this field and passes the object as its only argument. In this case this function returns 1 and pushes onto the stack the value returned by the call. If there is no metatable or no metamethod, this function returns 0 (without pushing any value on the stack).nil) at positionnarg.narg is a number and returns this number cast to anint.narg is a number and returns this number cast to alua_Integer (seelua_Integer).narg is a number and returns this number cast to along.const char *luaL_checklstring (lua_State *L, int narg, size_t *l);narg is a string and returns this string; ifl is notNULL fills*l with the string's length.narg is a number and returns this number (seelua_Number).int luaL_checkoption (lua_State *L, int narg, const char *def, const char *const lst[]);narg is a string and searches for this string in the arraylst (which must be NULL-terminated). Returns the index in the array where the string was found. Raises an error if the argument is not a string or if the string cannot be found.def is notNULL, the function usesdef as a default value when there is no argumentnarg or if this argument isnil.top + sz elements, raising an error if the stack cannot grow to that size.msg is an additional text to go into the error message.narg is a string and returns this string.(luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))(luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))fmt plus any extra arguments, following the same rules oflua_pushfstring (seelua_pushfstring()). It also adds at the beginning of the message the file name and the line number where the error occurred, if this information is available.return luaL_error(args).e from the metatable of the object at indexobj. If the object does not have a metatable, or if the metatable does not have this field, returns 0 and pushes nothing.tname in the registry (seeluaL_newmetatable()).const char *luaL_gsub (lua_State *L, const char *s, const char *p, const char *r);s by replacing any occurrence of the stringp with the stringr. Pushes the resulting string on the stack and returns it.int luaL_loadbuffer (lua_State *L, const char *buff, size_t sz, const char *name);lua_load (seelua_load()) to load the chunk in the buffer pointed to bybuff with sizesz.lua_load.name is the chunk name, used for debug information and error messages.lua_load (seelua_load()) to load the chunk in the file namedfilename. Iffilename isNULL, then it loads from the standard input. The first line in the file is ignored if it starts with a#.lua_load, but it has an extra error codeLUA_ERRFILE if it cannot open/read the file.lua_load, this function only loads the chunk; it does not run it.lua_load (seelua_load()) to load the chunk in the zero-terminated strings.lua_load.lua_load, this function only loads the chunk; it does not run it.tname, returns 0. Otherwise, creates a new table to be used as a metatable for userdata, adds it to the registry with keytname, and returns 1.tname in the registry.lua_newstate (seelua_newstate()) with an allocator based on the standard Crealloc function and then sets a panic function (seelua_atpanic()) that prints an error message to the standard error output in case of fatal errors.NULL if there is a memory allocation error.narg is a number, returns this number cast to anint. If this argument is absent or isnil, returnsd. Otherwise, raises an error.lua_Integer luaL_optinteger (lua_State *L, int narg, lua_Integer d);narg is a number, returns this number cast to alua_Integer (seelua_Integer). If this argument is absent or isnil, returnsd. Otherwise, raises an error.narg is a number, returns this number cast to along. If this argument is absent or isnil, returnsd. Otherwise, raises an error.const char *luaL_optlstring (lua_State *L, int narg, const char *d, size_t *l);narg is a string, returns this string. If this argument is absent or isnil, returnsd. Otherwise, raises an error.l is notNULL, fills the position*l with the results' length.narg is a number, returns this number. If this argument is absent or isnil, returnsd. Otherwise, raises an error.narg is a string, returns this string. If this argument is absent or isnil, returnsd. Otherwise, raises an error.LUAL_BUFFERSIZE where you can copy a string to be added to bufferB (seeluaL_Buffer). After copying the string into this space you must callluaL_addsize (seeluaL_addsize()) with the size of the string to actually add it to the buffer.B leaving the final string on the top of the stack.reference, in the table at indext, for the object at the top of the stack (and pops the object).t,luaL_ref ensures the uniqueness of the key it returns. You can retrieve an object referred by referencer by callinglua_rawgeti(L, t, r) (seelua_rawgeti()). FunctionluaL_unref (seeluaL_unref()) frees a reference and its associated object.nil,luaL_ref returns the constantLUA_REFNIL. The constantLUA_NOREF is guaranteed to be different from any reference returned byluaL_ref.luaL_register (seeluaL_register()).name is the function name andfunc is a pointer to the function. Any array ofluaL_Reg must end with a sentinel entry in which bothname andfunc areNULL.void luaL_register (lua_State *L, const char *libname, const luaL_Reg *l);libname equal toNULL, it simply registers all functions in the listl (seeluaL_Reg) into the table on the top of the stack.libname,luaL_register creates a new tablet, sets it as the value of the global variablelibname, sets it as the value ofpackage.loaded[libname], and registers on it all functions in the listl. If there is a table inpackage.loaded[libname] or in variablelibname, reuses this table instead of creating a new one.idx.location: bad argumentnargto'func'(tnameexpected, gotrt)location is produced byluaL_where (seeluaL_where()),func is the name of the current function, andrt is the type name of the actual argument.ref from the table at indext (seeluaL_ref()). The entry is removed from the table, so that the referred object can be collected. The referenceref is also freed to be used again.ref isLUA_NOREF orLUA_REFNIL,luaL_unref does nothing.lvl in the call stack. Typically this string has the following format:chunkname:currentline:type andgetmetatable); others provide access to "outside"services (e.g., I/O); and others could be implemented in Lua itself, but arequite useful or have critical performance requirements that deserve animplementation in C (e.g.,sort).luaL_openlibs function, which opens all standard libraries (seeluaL_openlibs()). Alternatively, the host program can open the librariesindividually by callingluaopen_base (for the basic library),luaopen_package (for the package library),luaopen_string (for the stringlibrary),luaopen_table (for the table library),luaopen_math (for themathematical library),luaopen_io (for the I/O and the Operating Systemlibraries), andluaopen_debug (for the debug library). These functions aredeclared inlualib.h and should not be called directly: you must call themlike any other Lua C function, e.g., by usinglua_call (seelua_call()).{v} [,{message}])assert()v is false (i.e.,nil orfalse); otherwise, returns all its arguments.message is an error message; when absent, it defaults to "assertion failed!"{opt} [,{arg}])collectgarbage(){opt}:"stop" stops the garbage collector."restart" restarts the garbage collector."collect" performs a full garbage-collection cycle."count" returns the total memory in use by Lua (in Kbytes)."step" performs a garbage-collection step. The step "size" is controlled by{arg} (larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value of{arg}. Returnstrue if the step finished a collection cycle."setpause" sets{arg} /100 as the new value for thepause of the collector (seelua-gc)."setstepmul" sets{arg} /100 as the new value for thestep multiplier of the collector (seelua-gc).{filename})dofile()dofile executes the contents of the standard input (stdin). Returns all values returned by the chunk. In case of errors,dofile propagates the error to its caller (that is,dofile does not run in protected mode).{message} [,{level}])error()message as the error message. Function{error} never returns.{error} adds some information about the error position at the beginning of the message. The{level} argument specifies how to get the error position. With level 1 (the default), the error position is where the{error} function was called. Level 2 points the error to where the function that called{error} was called; and so on. Passing a level 0 avoids the addition of error position information to the message._G._G = _G). Lua itself does not use this variable; changing its value does not affect any environment, nor vice-versa. (Usesetfenv to change environments.){f})getfenv(){f} can be a Lua function or a number that specifies the function at that stack level: Level 1 is the function callinggetfenv. If the given function is not a Lua function, or if{f} is 0,getfenv returns the global environment. The default for{f} is 1.{object})getmetatable(){object} does not have a metatable, returnsnil. Otherwise, if the object's metatable has a"__metatable" field, returns the associated value. Otherwise, returns the metatable of the given object.{t})ipairs(){t}, and 0, so that the constructionfor i,v in ipairs(t) dobodyend1,t[1]), (2,t[2]), ..., up to the first integer key absent from the table.{func} [,{chunkname}])load(){func} to get its pieces. Each call to{func} must return a string that concatenates with previous results. A return ofnil (or no value) signals the end of the chunk.nil plus the error message. The environment of the returned function is the global environment.{chunkname} is used as the chunk name for error messages and debug information.{filename}])loadfile()load (seeload()), but gets the chunk from file{filename} or from the standard input, if no file name is given.{string} [,{chunkname}])loadstring()load (seeload()), but gets the chunk from the given{string}.assert(loadstring(s))(){table} [,{index}])next()next returns the next index of the table and its associated value. When called withnil as its second argument,next returns an initial index and its associated value. When called with the last index, or withnil in an empty table,next returnsnil. If the second argument is absent, then it is interpreted asnil. In particular, you can usenext(t) to check whether a table is empty.for or theipairs() function.)next isundefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields.{t})pairs(){t}, andnil, so that the constructionfor k,v in pairs(t) dobodyend{t}.{f},{arg1},{...})pcall(){f} with the given arguments inprotected mode. This means that any error inside{f} is not propagated; instead,pcall catches the error and returns a status code. Its first result is the status code (a boolean), which istrue if the call succeeds without errors. In such case,pcall also returns all results from the call, after this first result. In case of any error,pcall returnsfalse plus the error message.{...})print()stdout, using thetostringtostring() function to convert them to strings.print is not intended for formatted output, but only as a quick way to show a value, typically for debugging. For formatted output, usestring.format (seestring.format()).{v1},{v2})rawequal(){v1} is equal to{v2}, without invoking any metamethod. Returns a boolean.{table},{index})rawget()table[index], without invoking any metamethod.{table} must be a table;{index} may be any value.{table},{index},{value})rawset()table[index] to{value}, without invoking any metamethod.{table} must be a table,{index} any value different fromnil, and{value} any Lua value.{table}.{index},{...})select(){index} is a number, returns all arguments after argument number{index}. Otherwise,{index} must be the string"#", andselect returns the total number of extra arguments it received.{f},{table})setfenv(){f} can be a Lua function or a number that specifies the function at that stack level: Level 1 is the function callingsetfenv.setfenv returns the given function.{f} is 0setfenv changes the environment of the running thread. In this case,setfenv returns no values.{table},{metatable})setmetatable(){metatable} isnil, removes the metatable of the given table. If the original metatable has a"__metatable" field, raises an error.{table}.{e} [,{base}])tonumber()tonumber returns this number; otherwise, it returnsnil.A (in either upper or lower case) represents 10,B represents 11, and so forth, withZ' representing 35. In base 10 (the default), the number may have a decimal part, as well as an optional exponent part (seelua-lexical). In other bases, only unsigned integers are accepted.{e})tostring()string.format (seestring.format()).{e} has a"__tostring" field,tostring calls the corresponding value with{e} as argument, and uses the result of the call as its result.{v})lua-type()"nil" (a string, not the valuenil),"number","string","boolean,"table","function","thread", and"userdata".{list} [,{i} [,{j}]])unpack()return list[i], list[i+1], ..., list[j]{i} is 1 and{j} is the length of the list, as defined by the length operator (seelua-length)."Lua 5.1" .{f},{err})xpcall()pcall (seepcall()), except that you can set a new error handler.xpcall calls function{f} in protected mode, using{err} as the error handler. Any error inside{f} is not propagated; instead,xpcall catches the error, calls the{err} function with the original error object, and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In this case,xpcall also returns all results from the call, after this first result. In case of any error,xpcall returnsfalse plus the result from{err}.coroutine. Seelua-coroutine for ageneral description of coroutines.{f})coroutine.create(){f}.{f} must be a Lua function. Returns this new coroutine, an object with type"thread".{co} [,{val1},{...}])coroutine.resume(){co}. The first time you resume a coroutine, it starts running its body. The values{val1},{...} are passed as arguments to the body function. If the coroutine has yielded,resume restarts it; the values{val1},{...} are passed as the results from the yield.resume returnstrue plus any values passed toyield (if the coroutine yields) or any values returned by the body function(if the coroutine terminates). If there is any error,resume returnsfalse plus the error message.nil when called by the main thread.{co})coroutine.status(){co}, as a string:"running", if the coroutine is running (that is, it calledstatus);"suspended", if the coroutine is suspended in a call toyield, or if it has not started running yet;"normal" if the coroutine is active but not running (that is, it has resumed another coroutine); and"dead" if the coroutine has finished its body function, or if it has stopped with an error.{f})coroutine.wrap(){f}.{f} must be a Lua function. Returns a function that resumes the coroutine each time it is called. Any arguments passed to the function behave as the extra arguments toresume. Returns the same values returned byresume, except the first boolean. In case of error, propagates the error.{...})coroutine.yield()yield are passed as extra results toresume.require andmodule (seerequire() andmodule()). Everything else isexported in a tablepackage.{name} [,{...}])module()package.loaded[name], this table is the module. Otherwise, if there is a global tablet with the given name, this table is the module. Otherwise creates a new tablet and sets it as the value of the global{name} and the value ofpackage.loaded[name]. This function also initializest._NAME with the given name,t._M with the module (t itself), andt._PACKAGE with the package name (the full module name minus last component; see below). Finally,module setst as the new environment of the current function and the new value ofpackage.loaded[name], so thatrequire() returnst.{name} is a compound name (that is, one with components separated by dots),module creates (or reuses, if they already exist) tables for each component. For instance, if{name} isa.b.c, thenmodule stores the module table in fieldc of fieldb of globala.options after the module name, where each option is a function to be applied over the module.{modname})require()package.loaded table to determine whether{modname} is already loaded. If it is, thenrequire returns the value stored atpackage.loaded[modname]. Otherwise, it tries to find aloader for the module.require queriespackage.preload[modname]. If it has a value, this value (which should be a function) is the loader. Otherwiserequire searches for a Lua loader using the path stored inpackage.path. If that also fails, it searches for a C loader using the path stored inpackage.cpath. If that also fails, it tries anall-in-one loader (see below).require first uses a dynamic link facility to link the application with the library. Then it tries to find a C function inside this library to be used as the loader. The name of this C function is the string"luaopen_" concatenated with a copy of the module name where each dot is replaced by an underscore. Moreover, if the module name has a hyphen, its prefix up to (and including) the first hyphen is removed. For instance, if the module name isa.v1-b.c, the function name will beluaopen_b_c.require finds neither a Lua library nor a C library for a module, it calls theall-in-one loader. This loader searches the C path for a library for the root name of the given module. For instance, when requiringa.b.c, it will search for a C library fora. If found, it looks into it for an open function for the submodule; in our example, that would beluaopen_a_b_c. With this facility, a package can pack several C submodules into one single library, with each submodule keeping its original open function.require calls the loader with a single argument,{modname}. If the loader returns any value,require assigns the returned value topackage.loaded[modname]. If the loader returns no value and has not assigned any value topackage.loaded[modname], thenrequire assignstrue to this entry. In any case,require returns the final value ofpackage.loaded[modname].require signals an error.package.cpath in the same way it initializes the Lua pathpackage.path, using the environment variableLUA_CPATH (plus another default path defined inluaconf.h).require to control which modules are already loaded. When you require a modulemodname andpackage.loaded[modname] is not false,require simply returns the value stored there.{libname},{funcname})package.loadlib(){libname}. Inside this library, looks for a function{funcname} and returns this function as a C function. (So,{funcname} must follow the protocol (seelua_CFunction)).require, it does not perform any path searching and does not automatically adds extensions.{libname} must be the complete file name of the C library, including if necessary a path and extension.{funcname} must be the exact name exported by the C library (which may depend on the C compiler and linker used).dlfcn standard).LUA_PATH or with a default path defined inluaconf.h, if the environment variable is not defined. Any";;" in the value of the environment variable is replaced by the default path.templates separated by semicolons. For each template,require will change each interrogation mark in the template byfilename, which ismodname with each dot replaced by a "directory separator" (such as"/" in Unix); then it will try to load the resulting file name. So, for instance, if the Lua path is"./?.lua;./?.lc;/usr/local/?/init.lua"
foo will try to load the files./foo.lua,./foo.lc, and/usr/local/foo/init.lua, in that order.{module})package.seeall(){module} with its__index field referring to the global environment, so that this module inherits values from the global environment. To be used as an option to function{module}.string.It also sets a metatable for strings where the__index field points to thestring table. Therefore, you can use the string functions in object-orientedstyle. For instance,string.byte(s, i) can be written ass:byte(i).{s} [,{i} [,{j}]])string.byte()s[i],s[i+1],...,s[j]. The default value for{i} is 1; the default value for{j} is{i}.{...})string.char(){function})string.dump(){function} must be a Lua function without upvalues.{s},{pattern} [,{init} [,{plain}]])string.find(){pattern} in the string{s}. If it finds a match, then{find} returns the indices of{s} where this occurrence starts and ends; otherwise, it returnsnil. A third, optional numerical argument{init} specifies where to start the search; its default value is 1 and may be negative. A value of{true} as a fourth, optional argument{plain} turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in{pattern} being considered "magic". Note that if{plain} is given, then{init} must be given as well.{formatstring},{...})string.format()printf family of standard C functions. The only differences are that the options/modifiers*,l,L,n,p, andh are not supported and that there is an extra option,q. Theq option formats a string in a form suitable to be safely read back by the Lua interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written. For instance, the callstring.format('%q', 'a string with "quotes" and \n new line')"a string with \"quotes\" and \ new line"c,d,E,e,f,g,G,i,o,u,X, andx all expect a number as argument, whereasq ands expect a string.{s},{pattern})string.gmatch(){pattern} over string{s}.{pattern} specifies no captures, then the whole match is produced in each call.s = "hello world from Lua"for w in string.gmatch(s, "%a+") do print(w)end{s}, printing one per line. The next example collects all pairskey=value from the given string into a table:t = {}s = "from=world, to=Lua"for k, v in string.gmatch(s, "(%w+)=(%w+)") do t[k] = vend{s},{pattern},{repl} [,{n}])string.gsub(){s} in which all occurrences of the{pattern} have been replaced by a replacement string specified by{repl}, which may be a string, a table, or a function.gsub also returns, as its second value, the total number of substitutions made.{repl} is a string, then its value is used for replacement. The character% works as an escape character: any sequence in{repl} of the form%n, with{n} between 1 and 9, stands for the value of the{n} -th captured substring (see below). The sequence%0 stands for the whole match. The sequence%% stands for a single%.{repl} is a table, then the table is queried for every match, using the first capture as the key; if the pattern specifies no captures, then the whole match is used as the key.{repl} is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order; if the pattern specifies no captures, then the whole match is passed as a sole argument.false ornil, then there is no replacement (that is, the original match is kept in the string).{n} limits the maximum number of substitutions to occur. For instance, when{n} is 1 only the first occurrence ofpattern is replaced.x = string.gsub("hello world", "(%w+)", "%1 %1")--> x="hello hello world world"x = string.gsub("hello world", "%w+", "%0 %0", 1)--> x="hello hello world"x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")--> x="world hello Lua from"x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)--> x="home = /home/roberto, user = roberto"x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) return loadstring(s)() end)--> x="4+5 = 9"local t = {name="lua", version="5.1"}x = string.gsub("$name%-$version.tar.gz", "%$(%w+)", t)--> x="lua-5.1.tar.gz"{s})string.len()"" has length 0. Embedded zeros are counted, so"a\000b\000c" has length 5.{s})string.lower(){s},{pattern} [,{init}])string.match()match of{pattern} in the string{s}. If it finds one, thenmatch returns the captures from the pattern; otherwise it returnsnil. If{pattern} specifies no captures, then the whole match is returned. A third, optional numerical argument{init} specifies where to start the search; its default value is 1 and may be negative.{s},{n})string.rep(){n} copies of the string{s}.{s},{i} [,{j}])string.sub(){s} that starts at{i} and continues until{j};{i} and{j} may be negative. If{j} is absent, then it is assumed to be equal to-1 (which is the same as the string length). In particular, the callstring.sub(s,1,j) returns a prefix of{s} with length{j}, andstring.sub(s,-i) returns a suffix of{s} with length{i}.{s})string.upper()x (wherex is not one of the magic characters^$()%.[]*+-?) represents the characterx itself.. (a dot) represents all characters.%a represents all letters.%c represents all control characters.%d represents all digits.%l represents all lowercase letters.%p represents all punctuation characters.%s represents all space characters.%u represents all uppercase letters.%w represents all alphanumeric characters.%x represents all hexadecimal digits.%z represents the character with representation0.%x (wherex is any non-alphanumeric character) represents the characterx. This is the standard way to escape the magic characters. Any punctuation character (even the non-magic) can be preceded by a% when used to represent itself in a pattern.[set] represents the class which is the union of all characters inset. A range of characters may be specified by separating the end characters of the range with a-. All classes%x described above may also be used as components inset. All other characters inset represent themselves. For example,[%w_] (or[_%w]) represents all alphanumeric characters plus the underscore,[0-7] represents the octal digits, and[0-7%l%-] represents the octal digits plus the lowercase letters plus the- character.[%a-z] or[a-%%] have no meaning.[^set] represents the complement ofset, whereset is interpreted as above.%a,%c, etc.), thecorresponding uppercase letter represents the complement of the class. Forinstance,%S represents all non-space characters.[a-z] may not be equivalent to%l.*, which matches 0 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;+, which matches 1 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;lua-nongreedy-, which also matches 0 or more repetitions of characters in the class. Unlike*, these repetition items will always match the shortest possible sequence;?, which matches 0 or 1 occurrences of a character in the class;%n, forn between 1 and 9; such item matches a substring equal to then -th captured string (see below);%bxy, wherex andy are two distinct characters; such item matches strings that start withx, end withy, and where thex andy are balanced. This means that, if one reads the string from left to right, counting+1 for anx and-1 for ay, the endingy is the firsty where the count reaches 0. For instance, the item%b() matches expressions with balanced parentheses.^ at the beginning of a patternanchors the match at the beginning of the subject string. A$ at the end ofa pattern anchors the match at the end of the subject string. At otherpositions,^ and$ have no special meaning and represent themselves."(a*(.)%w(%s*))", the part of the string matching"a*(.)%w(%s*)" is storedas the first capture (and therefore has number 1); the character matching.is captured with number 2, and the part matching%s* has number 3.() captures the current string position(a number). For instance, if we apply the pattern"()aa()" on thestring"flaaap", there will be two captures: 3 and 5.%z instead.table.{table} [,{sep} [,{i} [,{j}]]])table.concat()table[i]..sep..table[i+1] ... sep..table[j]. The default value for{sep} is the empty string, the default for{i} is 1, and the default for{j} is the length of the table. If{i} is greater than{j}, returns the empty string.{table},{f})table.foreach(){f} over all elements of{table}. For each element,{f} is called with the index and respective value as arguments. If{f} returns a non-`nil` value, then the loop is broken, and this value is returned as the final value oftable.foreach.{table},{f})table.foreachi(){f} over the numerical indices of{table}. For each index,{f} is called with the index and respective value as arguments. Indices are visited in sequential order, from 1 ton, wheren is the length of the table. If{f} returns a non-`nil` value, then the loop is broken and this value is returned as the result oftable.foreachi.{table}, [{pos},]{value})table.insert(){value} at position{pos} in{table}, shifting up other elements to open space, if necessary. The default value for{pos} isn+1, wheren is the length of the table (seelua-length), so that a calltable.insert(t,x) insertsx at the end of tablet.{table})table.maxn(){table} [,{pos}])table.remove(){table} the element at position{pos}, shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for{pos} isn, wheren is the length of the table (seelua-length), so that a calltable.remove(t) removes the last element of tablet.{table} [,{comp}])table.sort()in-place, fromtable[1] totable[n], wheren is the length of the table (seelua-length). If{comp} is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so thatnot comp(a[i+1],a[i]) will be true after the sort). If{comp} is not given, then the standard Lua operator< is used instead.not stable, that is, elements considered equal by thegiven order may have their relative positions changed by the sort.math.{x},{y})math.atan2()x/y (in radians), but uses the signs of both parameters to find the quadrant of the result. (It also handles correctly the case of{y} being zero.){x})math.frexp()m ande such thatx = m * 2^e,e is an integer and the absolute value ofm is in the range[0.5, 1) (or zero when{x} is zero).{x})math.modf(){x} and the fractional part of{x}.{m} [,{n}]])math.random()rand provided by ANSI C. (No guarantees can be given for its statistical properties.)[0,1). When called with a number{m},math.random returns a pseudo-random integer in the range[1, m]. When called with two numbers{m} and{n},math.random returns a pseudo-random integer in the range[m, n].{x})math.randomseed(){x} as the "seed" for the pseudo-random generator: equal seeds produce equal sequences of numbers.{x})math.sqrt(){x}. (You can also use the expressionx^0.5 to compute this value.)io. When using explicit file descriptors, the operationio.open returnsa file descriptor and then all operations are supplied as methods of the filedescriptor.io also provides three predefined file descriptors with their usualmeanings from C:io.stdin,io.stdout, andio.stderr.nil on failure (plus anerror message as a second result) and some value different fromnil onsuccess.{file}])io.close()file:close. Without a{file}, closes the default output file.{file}])io.input(){filename}])io.lines()for line in io.lines(filename) dobodyendnil (to finish the loop) and automatically closes the file.io.lines() (without a file name) is equivalent toio.input():lines(); that is, it iterates over the lines of the default input file. In this case it does not close the file when the loop ends.{filename} [,{mode}])io.open(){mode}. It returns a new file handle, or, in case of errors,nil plus an error message.{mode} string can be any of the following:"r" read mode (the default);"w" write mode;"a" append mode;"r+" update mode, all previous data is preserved;"w+" update mode, all previous data is erased;"a+" append update mode, previous data is preserved, writing is only allowed at the end of file.{mode} string may also have ab at the end, which is needed in some systems to open the file in binary mode. This string is exactly what is used in the standard C functionfopen.{prog} [,{mode}])io.popen(){prog} in a separated process and returns a file handle that you can use to read data from this program (if{mode} is"r", the default) or to write data to this program (if{mode} is"w").{obj})io.type(){obj} is a valid file handle. Returns the string"file" if{obj} is an open file handle,"closed file" if{obj} is a closed file handle, ornil if{obj} is not a file handle.file. Note that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen.for line in file:lines() dobodyendio.lines, this function does not close the file when the loop ends.){...})file:read()file, according to the given formats, which specify what to read. For each format, the function returns a string (or a number) with the characters read, ornil if it cannot read data with the specified format. When called without formats, it uses a default format that reads the entire next line (see below)."*n" reads a number; this is the only format that returns a number instead of a string."*a" reads the whole file, starting at the current position. On end of file, it returns the empty string."*l" reads the next line (skipping the end of line), returningnil on end of file. This is the default format.number reads a string with up to that number of characters, returningnil on end of file. If number is zero, it reads nothing and returns an empty string, ornil on end of file.{whence}] [,{offset}])file:seek(){offset} plus a base specified by the string{whence}, as follows:"set": base is position 0 (beginning of the file);"cur": base is current position;"end": base is end of file;seek returns the final file position, measured in bytes from the beginning of the file. If this function fails, it returnsnil, plus a string describing the error.{whence} is"cur", and for{offset} is 0. Therefore, the callfile:seek() returns the current file position, without changing it; the callfile:seek("set") sets the position to the beginning of the file (and returns 0); and the callfile:seek("end") sets the position to the end of the file, and returns its size.{mode} [,{size}])file:setvbuf()"no" no buffering; the result of any output operation appears immediately."full" full buffering; output operation is performed only when the buffer is full (or when you explicitlyflush the file (seeio.flush())."line" line buffering; output is buffered until a newline is output or there is any input from some special files (such as a terminal device).{size} specifies the size of the buffer, in bytes. The default is an appropriate size.{...})file:write()file. The arguments must be strings or numbers. To write other values, usetostringtostring() orstring.formatstring.format() beforewrite.os.{format} [,{time}]])os.date(){format}.{time} argument is present, this is the time to be formatted (see theos.time functionos.time() for a description of this value). Otherwise,date formats the current time.{format} starts with!, then the date is formatted in Coordinated Universal Time. After this optional character, if{format} is the string"*t", thendate returns a table with the following fields:year (four digits),month (1-12),day (1-31),hour (0-23),min (0-59),sec (0-61),wday (weekday, Sunday is 1),yday (day of the year), andisdst (daylight saving flag, a boolean).{format} is not"*t", thendate returns the date as a string, formatted according to the same rules as the C functionstrftime.date returns a reasonable date and time representation that depends on the host system and on the current locale (that is,os.date() is equivalent toos.date("%c")).{t2},{t1})os.difftime(){t1} to time{t2}. In POSIX, Windows, and some other systems, this value is exactlyt2 - t1 .{command}])os.execute()system. It passes{command} to be executed by an operating system shell. It returns a status code, which is system-dependent. If{command} is absent, then it returns nonzero if a shell is available and zero otherwise.{code}])os.exit()exit, with an optional{code}, to terminate the host program. The default value for{code} is the success code.{varname})os.getenv(){varname}, ornil if the variable is not defined.{filename})os.remove()nil, plus a string describing the error.{oldname},{newname})os.rename(){oldname} to{newname}. If this function fails, it returnsnil, plus a string describing the error.{locale} [,{category}])os.setlocale(){locale} is a string specifying a locale;{category} is an optional string describing which category to change:"all","collate","ctype","monetary","numeric", or"time"; the default category is"all". The function returns the name of the new locale, ornil if the request cannot be honored.{table}])os.time()year,month, andday, and may have fieldshour,min,sec, andisdst (for a description of these fields, see theos.date functionos.date()).time can be used only as an argument todate anddifftime.debug table. Allfunctions that operate over a thread have an optional first argument which isthe thread to operate over. The default is always the current thread.cont finishes this function, so that the caller continues its execution.debug.debug are not lexically nested within any function, and so have no direct access to local variables.{thread}])debug.gethook()debug.sethook function).{thread},]{function} [,{what}])debug.getinfo(){function}, which means the function running at level{function} of the call stack of the given thread: level 0 is the current function (getinfo itself); level 1 is the function that calledgetinfo; and so on. If{function} is a number larger than the number of active functions, thengetinfo returnsnil.lua_getinfo (seelua_getinfo()), with the string{what} describing which fields to fill in. The default for{what} is to get all information available, except the table of valid lines. If present, the optionf adds a field namedfunc with the function itself. If present, the optionL adds a field namedactivelines with the table of valid lines.debug.getinfo(1,"n").name returns the name of the current function, if a reasonable name can be found, anddebug.getinfo(print) returns a table with all available information about theprint function.{thread},]{level},{local})debug.getlocal(){local} of the function at level{level} of the stack. (The first parameter or local variable has index 1, and so on, until the last active local variable.) The function returnsnil if there is no local variable with the given index, and raises an error when called with a{level} out of range. (You can calldebug.getinfodebug.getinfo() to check whether the level is valid.)( (open parentheses) represent internal variables (loop control variables, temporaries, and C function locals).{object})debug.getmetatable(){object} ornil if it does not have a metatable.{func},{up})debug.getupvalue(){up} of the function{func}. The function returnsnil if there is no upvalue with the given index.{object},{table})debug.setfenv(){object} to the given{table}. Returns{object}.{thread},]{hook},{mask} [,{count}])debug.sethook(){mask} and the number{count} describe when the hook will be called. The string mask may have the following characters, with the given meaning:"c" : The hook is called every time Lua calls a function;"r" : The hook is called every time Lua returns from a function;"l" : The hook is called every time Lua enters a new line of code.{count} different from zero, the hook is called after every{count} instructions.debug.sethook turns off the hook."call","return" (or"tail return"),"line", and"count". For line events, the hook also gets the new line number as its second parameter. Inside a hook, you can callgetinfo with level 2 to get more information about the running function (level 0 is thegetinfo function, and level 1 is the hook function), unless the event is"tail return". In this case, Lua is only simulating the return, and a call togetinfo will return invalid data.{thread},]{level},{local},{value})debug.setlocal(){value} to the local variable with index{local} of the function at level{level} of the stack. The function returnsnil if there is no local variable with the given index, and raises an error when called with a{level} out of range. (You can callgetinfo to check whether the level is valid.) Otherwise, it returns the name of the local variable.{object},{table})debug.setmetatable(){object} to the given{table} (which can benil).{func},{up},{value})debug.setupvalue(){value} to the upvalue with index{up} of the function{func}. The function returnsnil if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue.{thread},] [{message} [,{level}]])debug.traceback(){message} string is appended at the beginning of the traceback. An optional{level} number tells at which level to start the traceback (default is 1, the function callingtraceback).