Unions User-defined types in which all members share the same memory location. Derived Classes Single and multiple inheritance, virtual functions, multiple base classes, abstract classes, scope rules.
Member-Access Control Controlling access to class members: public , private , and protected keywords. Friend functions and classes.
Overloading Overloaded operators, rules for operator overloading. Templates Template specifications, function templates, class templates, typename keyword, templates vs.
Event Handling Declaring events and event handlers. C Language Reference. Skip to main content. This browser is no longer supported. Through the use of C functions, Lua can be augmented to cope with a wide range of different domains, thus creating customized programming languages sharing a syntactical framework. Lua is free software, and is provided as usual with no guarantees, as stated in its license.
The implementation described in this manual is available at Lua's official web site, www. Like any other reference manual, this document is dry in places. For a discussion of the decisions behind the design of Lua, see the technical papers available at Lua's web site. For a detailed introduction to programming in Lua, see Roberto's book, Programming in Lua. This means that variables do not have types; only values do. There are no type definitions in the language.
All values carry their own type. All values in Lua are first-class values. This means that all values can be stored in variables, passed as arguments to other functions, and returned as results. There are eight basic types in Lua: nil , boolean , number , string , function , userdata , thread , and table.
The type nil has one single value, nil , whose main property is to be different from any other value; it usually represents the absence of a useful value. The type boolean has two values, false and true. Both nil and false make a condition false; any other value makes it true. The type number represents both integer numbers and real floating-point numbers.
The type string represents immutable sequences of bytes. Lua is also encoding-agnostic; it makes no assumptions about the contents of a string. The type number uses two internal representations, or two subtypes, one called integer and the other called float. Therefore, the programmer may choose to mostly ignore the difference between integers and floats or to assume complete control over the representation of each number.
The option with 32 bits for both integers and floats is particularly attractive for small machines and embedded systems. Both are represented by the type function. The type userdata is provided to allow arbitrary C data to be stored in Lua variables. A userdata value represents a block of raw memory.
There are two kinds of userdata: full userdata , which is an object with a block of memory managed by Lua, and light userdata , which is simply a C pointer value. Userdata has no predefined operations in Lua, except assignment and identity test. This guarantees the integrity of data owned by the host program. Lua threads are not related to operating-system threads. Lua supports coroutines on all systems, even those that do not support threads natively.
The type table implements associative arrays, that is, arrays that can have as indices not only numbers, but any Lua value except nil and NaN. Tables can be heterogeneous ; that is, they can contain values of all types except nil. Any key with value nil is not considered part of the table.
Conversely, any key that is not part of a table has an associated value nil. Tables are the sole data-structuring mechanism in Lua; they can be used to represent ordinary arrays, lists, symbol tables, sets, records, graphs, trees, etc. To represent records, Lua uses the field name as an index. The language supports this representation by providing a.
Like indices, the values of table fields can be of any type. In particular, because functions are first-class values, table fields can contain functions. The indexing of tables follows the definition of raw equality in the language.
The expressions a[i] and a[j] denote the same table element if and only if i and j are raw equal that is, equal without metamethods. In particular, floats with integral values are equal to their respective integers e. To avoid ambiguities, any float with integral value used as a key is converted to its respective integer.
For instance, if you write a[2. On the other hand, 2 and " 2 " are different Lua values and therefore denote different table entries. Tables, functions, threads, and full userdata values are objects : variables do not actually contain these values, only references to them.
Assignment, parameter passing, and function returns always manipulate references to such values; these operations do not imply any kind of copy. In particular, you can define new variables and parameters with that name.
Lua keeps a distinguished environment called the global environment. Therefore, by default, free names in Lua code refer to entries in the global environment and, therefore, they are also called global variables.
Moreover, all standard libraries are loaded in the global environment and some functions there operate on that environment. You can use load or loadfile to load a chunk with a different environment. In C, you have to load the chunk and then change the value of its first upvalue. When you use Lua standalone, the lua application is the host program.
Whenever an error occurs during the compilation or execution of a Lua chunk, control returns to the host, which can take appropriate measures such as printing an error message. Lua code can explicitly generate an error by calling the error function. If you need to catch errors in Lua, you can use pcall or xpcall to call a given function in protected mode. Whenever there is an error, an error object also called an error message is propagated with information about the error. Lua itself only generates errors whose error object is a string, but programs may generate errors with any value as the error object.
It is up to the Lua program or its host to handle such error objects. This function is called with the original error object and returns a new error object.
It is called before the error unwinds the stack, so that it can gather more information about the error, for instance by inspecting the stack and creating a stack traceback. This message handler is still protected by the protected call; so, an error inside the message handler will call the message handler again. If this loop goes on for too long, Lua breaks it and returns an appropriate message. The message handler is called only for regular runtime errors.
It is not called for memory-allocation errors nor for errors while running finalizers. This metatable is an ordinary Lua table that defines the behavior of the original value under certain special operations. You can change several aspects of the behavior of operations over a value by setting specific fields in its metatable.
If it finds one, Lua calls this function to perform the addition. The key for each event in a metatable is a string with the event name prefixed by two underscores; the corresponding values are called metamethods.
Unless stated otherwise, metamethods should be function values. You can query the metatable of any value using the getmetatable function. Lua queries metamethods in metatables using a raw access see rawget. Tables and full userdata have individual metatables although multiple tables and userdata can share their metatables. Values of all other types share one single metatable per type; that is, there is one single metatable for all numbers, one for all strings, etc.
A metatable controls how an object behaves in arithmetic operations, bitwise operations, order comparisons, concatenation, length operation, calls, and indexing. For the unary operators negation, length, and bitwise NOT , the metamethod is computed and called with a dummy second operand, equal to the first one.
This extra operand is only to simplify Lua's internals by making these operators behave like a binary operation and may be removed in future versions. For most uses this extra operand is irrelevant. A detailed list of events controlled by metatables is given next. Each operation is identified by its corresponding key.
If any operand for an addition is not a number nor a string coercible to a number , Lua will try to call a metamethod. First, Lua will check the first operand even if it is valid. If Lua can find a metamethod, it calls the metamethod with the two operands as arguments, and the result of the call adjusted to one value is the result of the operation.
Otherwise, it raises an error. Behavior similar to the addition operation. Behavior similar to the bitwise AND operation. Behavior similar to the addition operation, except that Lua will try a metamethod if any operand is neither a string nor a number which is always coercible to a string. If the object is not a string, Lua will try its metamethod. If there is a metamethod, Lua calls it with the object as argument, and the result of the call always adjusted to one value is the result of the operation.
Otherwise, Lua raises an error. Behavior similar to the addition operation, except that Lua will try a metamethod only when the values being compared are either both tables or both full userdata and they are not primitively equal. The result of the call is always converted to a boolean. Behavior similar to the addition operation, except that Lua will try a metamethod only when the values being compared are neither both numbers nor both strings.
Unlike other operations, the less-equal operation can use two different events. As with the other comparison operators, the result is always a boolean. This event happens when table is not a table or when key is not present in table. The metamethod is looked up in table.
Despite the name, the metamethod for this event can be either a function or a table. If it is a function, it is called with table and key as arguments, and the result of the call adjusted to one value is the result of the operation. If it is a table, the final result is the result of indexing this table with key. This indexing is regular, not raw, and therefore can trigger another metamethod. Like the index event, this event happens when table is not a table or when key is not present in table.
Like with indexing, the metamethod for this event can be either a function or a table. If it is a function, it is called with table , key , and value as arguments. If it is a table, Lua does an indexing assignment to this table with the same key and value. This assignment is regular, not raw, and therefore can trigger another metamethod. If necessary, the metamethod itself can call rawset to do the assignment. This event happens when Lua tries to call a non-function value that is, func is not a function.
The metamethod is looked up in func. If present, the metamethod is called with func as its first argument, followed by the arguments of the original call args.
All results of the call are the result of the operation. This is the only metamethod that allows multiple results. It is a good practice to add all needed metamethods to a table before setting it as a metatable of some object. Because metatables are regular tables, they can contain arbitrary fields, not only the event names defined above.
Some functions in the standard library e. This means that you do not have to worry about allocating memory for new objects or freeing it when the objects are no longer needed. Lua manages memory automatically by running a garbage collector to collect all dead objects that is, objects that are no longer accessible from Lua. All memory used by Lua is subject to automatic management: strings, tables, userdata, functions, threads, internal structures, etc.
Lua implements an incremental mark-and-sweep collector. It uses two numbers to control its garbage-collection cycles: the garbage-collector pause and the garbage-collector step multiplier. Both use percentage points as units e. The garbage-collector pause controls how long the collector waits before starting a new cycle. Larger values make the collector less aggressive. Values smaller than mean the collector will not wait to start a new cycle.
A value of means that the collector waits for the total memory in use to double before starting a new cycle. The garbage-collector step multiplier controls the relative speed of the collector relative to memory allocation. Larger values make the collector more aggressive but also increase the size of each incremental step. You should not use values smaller than , because they make the collector too slow and can result in the collector never finishing a cycle.
The default is , which means that the collector runs at "twice" the speed of memory allocation. If you then set the pause to , the collector behaves as in old Lua versions, doing a complete collection every time Lua doubles its memory usage.
You can also use these functions to control the collector directly e. These metamethods are also called finalizers. Finalizers allow you to coordinate Lua's garbage collection with external resource management such as closing files, network or database connections, or freeing your own memory.
For an object table or userdata to be finalized when collected, you must mark it for finalization. When a marked object becomes garbage, it is not collected immediately by the garbage collector.
Instead, Lua puts it in a list. After the collection, Lua goes through that list. At the end of each garbage-collection cycle, the finalizers for objects are called in the reverse order that the objects were marked for finalization, among those collected in that cycle; that is, the first finalizer to be called is the one associated with the object marked last in the program.
The execution of each finalizer may occur at any point during the execution of the regular code. Because the object being collected must still be used by the finalizer, that object and other objects accessible only through it must be resurrected by Lua. Usually, this resurrection is transient, and the object memory is freed in the next garbage-collection cycle.
However, if the finalizer stores the object in some global place e. Moreover, if the finalizer marks a finalizing object for finalization again, its finalizer will be called again in the next cycle where the object is unreachable. In any case, the object memory is freed only in a GC cycle where the object is unreachable and not marked for finalization. If any finalizer marks objects for collection during that phase, these marks have no effect.
A weak reference is ignored by the garbage collector. In other words, if the only references to an object are weak references, then the garbage collector will collect that object. A weak table can have weak keys, weak values, or both. A table with weak values allows the collection of its values, but prevents the collection of its keys.
A table with both weak keys and weak values allows the collection of both keys and values. In any case, if either the key or the value is collected, the whole pair is removed from the table.
A table with weak keys and strong values is also called an ephemeron table. In an ephemeron table, a value is considered reachable only if its key is reachable. In particular, if the only reference to a key comes through its value, the pair is removed. Any change in the weakness of a table may take effect only at the next collect cycle. In particular, if you change the weakness to a stronger mode, Lua may still collect some items from that table before the change takes effect.
Only objects that have an explicit construction are removed from weak tables. Values, such as numbers and light C functions, are not subject to garbage collection, and therefore are not removed from weak tables unless their associated values are collected. Although strings are subject to garbage collection, they do not have an explicit construction, and therefore are not removed from weak tables. Resurrected objects that is, objects being finalized and objects accessible only through objects being finalized have a special behavior in weak tables.
They are removed from weak values before running their finalizers, but are removed from weak keys only in the next collection after running their finalizers, when such objects are actually freed. This behavior allows the finalizer to access properties associated with the object through weak tables.
If a weak table is among the resurrected objects in a collection cycle, it may not be properly cleared until the next cycle. A coroutine in Lua represents an independent thread of execution. Unlike threads in multithread systems, however, a coroutine only suspends its execution by explicitly calling a yield function.
You create a coroutine by calling coroutine. Its sole argument is a function that is the main function of the coroutine. The create function only creates a new coroutine and returns a handle to it an object of type thread ; it does not start the coroutine. You execute a coroutine by calling coroutine. When you first call coroutine. Extra arguments passed to coroutine. After the coroutine starts running, it runs until it terminates or yields. A coroutine can terminate its execution in two ways: normally, when its main function returns explicitly or implicitly, after the last instruction ; and abnormally, if there is an unprotected error.
In case of normal termination, coroutine. In case of errors, coroutine. A coroutine yields by calling coroutine. When a coroutine yields, the corresponding coroutine. In the case of a yield, coroutine. The next time you resume the same coroutine, it continues its execution from the point where it yielded, with the call to coroutine. Like coroutine. Any arguments passed to this function go as extra arguments to coroutine.
Unlike coroutine. As an example of how coroutines work, consider the following code: function foo a print "foo", a return coroutine. In other words, this section describes which tokens are valid, how they can be combined, and what their combinations mean. It ignores spaces including new lines and comments between lexical elements tokens , except as delimiters between names and keywords.
Names also called identifiers in Lua can be any string of letters, digits, and underscores, not beginning with a digit and not being a reserved word. Identifiers are used to name variables, table fields, and labels. The following keywords are reserved and cannot be used as names: and break do else elseif end false for function goto if in local nil not or repeat return then true until while Lua is a case-sensitive language: and is a reserved word, but And and AND are two different, valid names.
A backslash followed by a line break results in a newline in the string. A short literal string cannot contain unescaped line breaks nor escapes not forming a valid escape sequence. We can specify any byte in a short literal string by its numeric value including embedded zeros. Note that if a decimal escape sequence is to be followed by a digit, it must be expressed using exactly three digits. Literal strings can also be defined using a long format enclosed by long brackets.
We define an opening long bracket of level n as an opening square bracket followed by n equal signs followed by another opening square bracket. A long literal starts with an opening long bracket of any level and ends at the first closing long bracket of the same level.
It can contain any text except a closing bracket of the same level. Literals in this bracketed form can run for several lines, do not interpret any escape sequences, and ignore long brackets of any other level. Any kind of end-of-line sequence carriage return, newline, carriage return followed by newline, or newline followed by carriage return is converted to a simple newline. For convenience, when the opening long bracket is immediately followed by a newline, the newline is not included in the string.
However, Lua opens files for parsing in text mode, and the system file functions may have problems with some control characters. So, it is safer to represent non-text data as a quoted literal with explicit escape sequences for the non-text characters. A numeric constant or numeral can be written with an optional fractional part and an optional decimal exponent, marked by a letter ' e ' or ' E '. Lua also accepts hexadecimal constants, which start with 0x or 0X. Hexadecimal constants also accept an optional fractional part plus an optional binary exponent, marked by a letter ' p ' or ' P '.
A numeric constant with a radix point or an exponent denotes a float; otherwise, if its value fits in an integer, it denotes an integer. If the text immediately after -- is not an opening long bracket, the comment is a short comment , which runs until the end of the line.
Otherwise, it is a long comment , which runs until the corresponding closing long bracket. Long comments are frequently used to disable code temporarily. There are three kinds of variables in Lua: global variables, local variables, and table fields.
Before the first assignment to a variable, its value is nil. The syntax var. This set includes assignments, control structures, function calls, and variable declarations. This possibility leads to an ambiguity in Lua's grammar. To avoid this ambiguity, it is a good practice to always precede with a semicolon statements that start with a parenthesis: ; print or io.
As such, chunks can define local variables, receive arguments, and return values. A chunk can be stored in a file or in a string inside the host program. To execute a chunk, Lua first loads it, precompiling the chunk's code into instructions for a virtual machine, and then Lua executes the compiled code with an interpreter for the virtual machine.
Chunks can also be precompiled into binary form; see program luac and function string. Programs in source and compiled forms are interchangeable; Lua automatically detects the file type and acts accordingly see load. Therefore, the syntax for assignment defines a list of variables on the left side and a list of expressions on the right side. Before the assignment, the list of values is adjusted to the length of the list of variables.
If there are more values than needed, the excess values are thrown away. If there are fewer values than needed, the list is extended with as many nil 's as needed. The assignment statement first evaluates all its expressions and only then the assignments are performed. The condition expression of a control structure can return any value. Both false and nil are considered false. All values different from nil and false are considered true in particular, the number 0 and the empty string are also true.
In the repeat — until loop, the inner block does not end at the until keyword, but only after the condition. So, the condition can refer to local variables declared inside the loop block. The goto statement transfers the program control to a label. A goto may jump to any visible label as long as it does not enter into the scope of a local variable. Labels and empty statements are called void statements , as they perform no actions. The return statement is used to return values from a function or a chunk which is an anonymous function.
If it is really necessary to return in the middle of a block, then an explicit inner block can be used, as in the idiom do return end , because now return is the last statement in its inner block.
The numerical for loop repeats a block of code while a control variable runs through an arithmetic progression. They must all result in numbers. The names shown here are for explanatory purposes only. If the third expression the step is absent, then a step of 1 is used. You can use break and goto to exit a for loop. The loop variable v is local to the loop body.
If you need its value after the loop, assign it to another variable before exiting the loop. The generic for statement works over functions, called iterators. On each iteration, the iterator function is called to produce a new value, stopping when this new value is nil. Its results are an iterator function, a state , and an initial value for the first iterator variable.
The names are here for explanatory purposes only. You can use break to exit a for loop. If you need these values, then assign them to other variables before breaking or exiting the loop. Otherwise, all variables are initialized with nil. Vararg expressions, denoted by three dots ' Both function calls and vararg expressions can result in multiple values. If an expression is used as the last or the only element of a list of expressions, then no adjustment is made unless the expression is enclosed in parentheses.
In all other contexts, Lua adjusts the result list to one element, either discarding all values except the first one or adding a single nil if there are no values. Thus, f x,y,z is always a single value, even if f returns several values. The value of f x,y,z is the first value returned by f or nil if f does not return any values. Exponentiation uses the ISO C function pow , so that it works for non-integer exponents too. Modulo is defined as the remainder of a division that rounds the quotient towards minus infinity floor division.
In case of overflows in integer arithmetic, all operations wrap around , according to the usual rules of two-complement arithmetic. In other words, they return the unique representable integer that is equal modulo 2 64 to the mathematical result. Both right and left shifts fill the vacant bits with zeros. Negative displacements shift to the other direction; displacements with absolute values equal to or higher than the number of bits in an integer result in zero as all bits are shifted out.
Bitwise operators always convert float operands to integers. Exponentiation and float division always convert integer operands to floats. All other arithmetic operations applied to mixed numbers integers and floats convert the integer operand to a float; this is called the usual rule. The C API also converts both integers to floats and floats to integers, as needed.
Moreover, string concatenation accepts numbers as arguments, besides strings. Lua also converts strings to numbers, whenever a number is expected.
In a conversion from integer to float, if the integer value has an exact representation as a float, that is the result. Otherwise, the conversion gets the nearest higher or the nearest lower representable value. This kind of conversion never fails.
The conversion from float to integer checks whether the float has an exact representation as an integer that is, the float has an integral value and it is in the range of integer representation. If it does, that representation is the result. Otherwise, the conversion fails. The conversion from strings to numbers goes as follows: First, the string is converted to an integer or a float, following its syntax and the rules of the Lua lexer.
The string may have also leading and trailing spaces and a sign. Then, the resulting number float or integer is converted to the type float or integer required by the context e. All conversions from strings to numbers accept both a dot and the current locale mark as the radix character. The Lua lexer, however, accepts only a dot. The conversion from numbers to strings uses a non-specified human-readable format.
For complete control over how numbers are converted to strings, use the format function from the string library see string. If the types are different, then the result is false.
Otherwise, the values of the operands are compared. Strings are compared in the obvious way. Numbers are equal if they denote the same mathematical value. Tables, userdata, and threads are compared by reference: two objects are considered equal only if they are the same object. Every time you create a new object a table, userdata, or thread , this new object is different from any previously existing object.
A closure is always equal to itself. Closures with any detectable difference different behavior, different definition are always different. Closures created at different times but with no detectable differences may be classified as equal or not depending on internal caching details. Equality comparisons do not convert strings to numbers or vice versa. The order operators work as follows.
If both arguments are numbers, then they are compared according to their mathematical values regardless of their subtypes. Otherwise, if both arguments are strings, then their values are compared according to the current locale. Following the IEEE standard, NaN is considered neither smaller than, nor equal to, nor greater than any value including itself. The negation operator not always returns false or true.
The conjunction operator and returns its first argument if this value is false or nil ; otherwise, and returns its second argument. The disjunction operator or returns its first argument if this value is different from nil and false ; otherwise, or returns its second argument. Both and and or use short-circuit evaluation; that is, the second operand is evaluated only if necessary.
The length of a string is its number of bytes that is, the usual meaning of string length when each character is one byte. The length operator applied on a table returns a border in that table. A table with exactly one border is called a sequence. Note that non-natural keys do not interfere with whether a table is a sequence. When t is a sequence, t returns its only border, which corresponds to the intuitive notion of the length of the sequence.
When t is not a sequence, t can return any of its borders. The exact one depends on details of the internal representation of the table, which in turn can depend on how the table was populated and the memory addresses of its non-numeric keys. The computation of the length of a table has a guaranteed worst time of O log n , where n is the largest natural key in the table. The concatenation '.. All other binary operators are left associative. Every time a constructor is evaluated, a new table is created.
A constructor can be used to create an empty table or to create a table and initialize some of its fields. Fields in the other formats do not affect this counting. This order would be relevant only when there are repeated keys.
The field list can have an optional trailing separator, as a convenience for machine-generated code. If the value of prefixexp has type function , then this function is called with the given arguments. A call v:name args is syntactic sugar for v. A call of the form f' string ' or f" string " or f[[ string ]] is syntactic sugar for f ' string ' ; that is, the argument list is a single literal string.
A call of the form return functioncall is called a tail call. Lua implements proper tail calls or proper tail recursion : in a tail call, the called function reuses the stack entry of the calling function. Therefore, there is no limit on the number of nested tail calls that a program can execute. However, a tail call erases any debug information about the calling function.
Note that a tail call only happens with a particular syntax, where the return has one single function call as argument; this syntax makes the calling function return exactly the returns of the called function.
A function definition is an executable expression, whose value has type function. When Lua precompiles a chunk, all its function bodies are precompiled too.
Then, whenever Lua executes the function definition, the function is instantiated or closed. This function instance or closure is the final value of the expression. A vararg function does not adjust its argument list; instead, it collects all extra 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 of all actual extra arguments, similar to a function with multiple results. If a vararg expression is used inside another expression or in the middle of a list of expressions, then its return list is adjusted to one element.
If the expression is used as the last element of a list of expressions, then no adjustment is made unless that last expression is enclosed in parentheses. As an example, consider the following definitions: function f a, b end function g a, b, If control reaches the end of a function without encountering a return statement, then the function returns with no results. There is a system-dependent limit on the number of values that a function may return. This limit is guaranteed to be larger than The colon syntax is used for defining methods , that is, functions that have an implicit extra parameter self.
There have also been some improvements to overload resolution. NET Core 3. The features include nullable reference types, recursive pattern matching, default interface methods, async streams, ranges and indexes, pattern based using and using declarations, null coalescing assignment, and readonly instance members. C 9 Specification Proposals C 9 is available with. NET 5. The features include records, top-level statements, pattern matching enhancements, init only setters, target-typed new expressions, module initializers, extending partial methods, static anonymous functions, target-typed conditional expressions, covariant return types, extension GetEnumerator in foreach loops, lambda discard parameters, attributes on local functions, native sized integers, function pointers, suppress emitting localsinit flag, and unconstrained type parameter annotations.
C 10 Specification Proposals C 10 is available with. NET 6. The features include record structs, parameterless struct constructors, global using directives, file-scoped namespaces, extended property patterns, improved interpolated strings, constant interpolated strings, lambda improvements, caller-argument expression, enhanced line directives, generic attributes, improved definite assignment analysis, and AsyncMethodBuilder override.
C Programming Guide Includes information about how to use the C programming language. Skip to main content. This browser is no longer supported. Download Microsoft Edge More info. Contents Exit focus mode. Is this page helpful? Please rate your experience Yes No. Any additional feedback? Submit and view feedback for This product This page.
0コメント