| Lua base functions |
|---|
| Lua base functions and variables These are the "base" functions in Lua (that is, those that are not in library tables). _G Variable which is the global environment table. (_G._G == _G) You cannot change the environment by assigning to _G, use setfenv instead. assert (v, message) Raises an error if value of v is nil or false. Message is optional, defaults to "assertion failed!". If no error, returns the value v. It is very useful that assert returns the value on success, as you can build an assert into the same line that does something that might fail. For example: In this case if the loadstring function succeeds it returns a function, that is then executed by the final brackets, otherwise you get an error message. collectgarbage (opt, arg) Note that this has changed considerably since Lua 5.0.
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. 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 1 mean the collector will not wait to start a new cycle. A value of 2 means that the collector waits for the total memory in use to double before starting a new cycle. The 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. Values smaller than 1 make the collector too slow and may result in the collector never finishing a cycle. The default, 2, means that the collector runs at "twice" the speed of memory allocation. Both "setpause" and "setstepmul" get percentage points as arguments (so an argument of 100 means a real value of 1). Both default to 200 when Lua starts up (and since they are divided by 100, effectively the default is 2 as described above). dofile (filename) Opens the named file, parses and executes its contents as a Lua chunk. Raises errors if they occur. Returns any value returned by the chunk. Same as: error (message, level) Raises an error with the supplied message. Never returns. If a level is supplied the error points to the current function (level 1 or nil), the parent function (level 2) and so on. If you are writing a "validation function" that checks things passed to it, you would normally make the level 2, so that the error message points to the line that calls the validator, rather than the validator itself. gcinfo () Returns Kb of dynamic memory in use. This function is deprecated in Lua 5.1. Use collectgarbage ("count") instead. getfenv (f) Returns the current environment used by the nominated function f. f can be a function or a number representing the stack level, where 1 is the currently running function, 2 is its parent and so on. The environment is where "global" variables are stored. The default for f is 1 (the current function). getmetatable (t) Returns metatable for the nominated object, which can be:
In Lua 5.1, all objects can have metatables (not just tables). ipairs (t) Returns an iterator function, the table t, and 0, for use in the generic "for" loop. The iterator function, called repeatedly, returns the key and value pairs for each table item, until it finds the first missing integer key. For example, if keys 1 to 8 are present, and key 9 is nil, will return the first 8 values. This occurs even if there is a key present for item 10. In other words, you cannot use ipairs to iterate over a table with "holes" in the key ranges. load (f, debugname) Loads a chunk using function f to get its pieces. Each call to f must return a string that concatenates with previous results. A return of nil (or no value) signals the end of the chunk. If there are no errors, returns the compiled chunk as a function; otherwise, returns nil plus the error message. The environment of the returned function is the global environment. This could be used to gradually build up a chunk (for example from a network), or to write a preprocessor that reads in a file, preprocess it (like the C preprocessor) and returns the altered code to the Lua interpreter. The example below shows generating code from entries in a table. loadfile (filename) Opens the named file, parses it and returns the compiled chunk as a function. Does not execute it. loadlib (libraryname, funcname) This function has been moved in Lua 5.1 to the "package" table. See: package.loadlib. loadstring (str, debugname) Parses the string and returns the compiled chunk as a function. Does not execute it. If the string cannot be parsed returns nil plus an error message. The optional debugname is used in debug error messages. You can avoid the intermediate variable "f" in this example by simply putting the brackets on the same line: If the string was produced by string.dump, loadstring converts it back into the original function. module (name, ···) Creates a module. This is intended for use with external "package" files, however it can be used internally as shown in the example below. The module effectively has its own global variable space (because module does a setfenv) so that any functions or variables used in the module are local to the module name (for example, foo.add in the example below). If there is a table in package.loaded[name], this table is the module. Thus, if the module has already been requested (by a require statement) another new table is not created. Otherwise, if there is a global table t with the given name, this table is the module. Otherwise creates a new table t and sets it as the value of the global name and the value of package.loaded[name]. This function also initializes t._NAME with the given name, t._M with the module (t itself), and t._PACKAGE with the package name (the full module name minus last component). Finally, module sets t as the new environment of the current function and the new value of package.loaded[name], so that require returns t. The example below shows the creation of the module "foo". In practice you would probably put the contents of the "test" function into a separate file, and then: require "test" The nice thing about this approach is that nothing inside the module will "pollute" the global namespace, excepting the module name itself (foo in this case). Internally inside the module functions can call each other without having to use the package name (eg. add could call subtract without using foo.subtract). You can make a "private" function inside the "foo" package by simply putting "local" in front of the function name. After the module has been created, we can see that: foo._M is foo itself (ie. the module) foo._NAME is "foo" foo._PACKAGE is an empty string (if the module was "foo.bar" then _PACKAGE would be "foo.") newproxy () This is a very experimental feature. It is undocumented, even on the Lua site. According to the Lua developers, newproxy is unofficial in Lua 5.0. You can (should?) create proxy tables without this function. Just create an empty table and set appropriate metamethods for it. In brief, what it does is create a full userdata of zero length, and attaches a metatable to it. The original idea was to make metatables available without the overhead of creating an "owner" table, but this idea seems to have been abandoned. next (table, index) Traverses all fields in a table. Returns the next index, value pair. If index is nil (the default), returns the first pair. When called with the last index of the table (or with an index of nil for an empty table), returns nil. Only non-nil values are returned. Order is not specified (eg. is not necessarily alphabetic sequence). Behaviour is undefined if you assign values to non-existent fields during the traversal. You may however modify or delete existing fields. pairs (t) Returns the 'next' function, the table t, and nil, for use in a for loop. pcall (f, arg1, arg2, ...) Calls function f with the supplied arguments in protected mode. Catches errors and returns: On success:
On failure:
print (a1, a2, a3, ...) Prints its arguments to stdout (or the output window in the case of MUSHclient), formatted by calling 'tostring'. Not intended for formatted output, but rather for debugging. Each argument is separated by a space. rawequal (v1, v2) Returns a boolean depending on v1 == v2 without invoking any table metamethods. rawget (table, index) Gets the real value of table [index] without invoking metamethods. Index should not be nil. This example shows that the Note function is not really in the global environment. MUSHclient adds a metamethod to pull it from the "world" table. rawset (table, index, value) Sets the value of table [index] to value, without invoking metamethods. 'table' must be a table, and 'index' must not be nil. require (modname) Loads the named module. First checks the table package.loaded to see if it has already been loaded. If so, returns the value there. Otherwise it tries to find a loader for the module. It tries these things:
Once a loader is found, require calls the loader with a single argument, modname. If the loader returns any value, require assigns the returned value to package.loaded [modname]. If the loader returns no value and has not assigned any value to package.loaded [modname], then require assigns true to this entry. In any case, require returns the final value of package.loaded [modname]. Effectively this lets various modules "require" a package, and it will only be loaded once. Also see the description for "module" for ways of effectively setting up a module to work in conjunction with "require". select (index, ...) If index is a number, returns all items in the list from that number onwards. Otherwise index must be the string "#", in which case it returns the number of items in the list. This can be used to simulate the behaviour of the old "arg" feature in Lua 5.0, for use with variable numbers of arguments passed to a function. setfenv (f) Sets the current environment to be used by f, which can be a function, userdata, thread or stack level. Level 1 is the current function. Level 0 is the global environment of the current thread. The return value is the function whose environment was changed, unless the argument was 0. This can be used as a form of "sandbox", so that functions can run in an environment where they do not have access to normal global variables. For example, in the above code, you could not call "print" from inside function f, as print is not in the environment. To make it accessible you might do this: A nice use of the setfenv function is to limit the damage that can be done when reading an external file. An example is to let the user of your script provide a configuration file, that you want to read in. An example might be: A quick way of processing that file would be to: dofile ("config.txt") However if the "config.txt" file contained malicious code (like: os.remove "myapplication.exe") then it could have undesired side-effects. Even a simple assignment like: 'print = nil' could cause problems. The solution is to use setfenv to limit the global environment for this file, like this: What this does is change the global environment for the function returned from loadfile to be the empty config table. This means that all "global" variables will be relative to config, not _G. It also means that all the standard functions (like os.remove) are not visible. setmetatable (table, metatable) Sets the metatable for the nominated table. If metatable is nil, removes the metatable. If the original metatable has a "__metatable" entry an error is raised. Metatables let you add special entries that cause certain operations to behave in a different way. These operations are (each one starts with 2 underscore characters):
If there is no __le metamethod, Lua tries the __lt metamethod, assuming that: Examples: tonumber (n, base) Converts n to a number using the optional base (default 10). Base can be from 2 to 36. For bases > 10 the letters a-z (not case sensitive) represent the digits. (eg. F is 15). For decimal numbers you can supply fractions and exponents. Others should be unsigned. Returns nil if the number cannot be converted. You can use tonumber as a quick check if a variable contains something convertable to a number. To see if the variable actually is already a number type, use the "type" function: tostring (a) Converts its argument to a string in a reasonable format. If a __tostring metatable field is found, that is used for the conversion. type (v) Returns a string, which is the type of the supplied variable:
unpack (t) Returns all elements from the given list (table) as individual values. This is equivalent to: return t [1], t [2], t [3] ..., t [n] An example of using unpack is the case of a variable number of arguments to a function, where you want to pass those to another function. For example, to make an error function that takes a formatted string: However in Lua 5.1 this is more simply written as: _VERSION A global variable that is a string containing the current Lua interpreter version. xpcall (f, err) Calls function f with err as the custom error handler. If an error occurs in f it is caught and the error-handler 'err' is called. Then xpcall returns false, and whatever the error handler returned. If there is no error in f, then xpcall returns true, followed by the function results from f. Note that the supplied error function is called before the stack is unwound (in case of error) so this is a good time to find what functions were on the stack leading up to the error. In the example below we use the debug.traceback function, which shows a stack trace as at the time of the error. See Also ... Topics
Lua coroutine functions
Lua debug functions
Lua io functions
Lua math functions
Lua os functions
Lua package functions
Lua script extensions
Lua string functions
Lua table functions(Help topic: general=lua_base)
Documentation contents page |