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.


assert (5 == 6, "oh no!") --> error: oh no!


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:


assert (loadstring ("print 'hello, world'")) ()


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.


  • "stop": stops the garbage collector.
  • "restart": restarts the garbage collector.
  • "collect": performs a full garbage-collection cycle (this is the default if no option supplied)
  • "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. Returns true if the step finished a collection cycle.
  • "setpause": sets arg/100 as the new value for the pause of the collector (see below).
  • "setstepmul": sets arg/100 as the new value for the step multiplier of the collector (see below).


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).


collectgarbage ("collect") --> forces garbage collection



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.


dofile ("myfile.lua") 


Same as:


function dofile (filename)
  local f = assert (loadfile (filename))
  return f ()
end -- dofile



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.


error ("Insufficient funds") --> error raised: "Insufficient funds"


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.


print (gcinfo ()) --> 103



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.


print (getfenv (1)) --> table: 02072780
print (_G) --> table: 02072780


The default for f is 1 (the current function).


getmetatable (t)

Returns metatable for the nominated object, which can be:


  • nil if no metatable
  • the value of the __metatable field of the metatable, if any
  • the metatable of the object



getmetatable (_G) --> nil


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.



for i, v in ipairs (t) do
  -- process loop here
end -- for


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.


function getcode (t)
local pos = 0
  local function iterator (s)
    pos = pos + 1
    return t [pos]
  end -- iterator
  return iterator
end -- getcode


code = {
  "local a = 1 ",
  "print ('a =', a) ",
  "print 'done.'"
  }
  
assert (load (getcode (code))) ()


loadfile (filename)

Opens the named file, parses it and returns the compiled chunk as a function. Does not execute it.


f = assert (loadfile ("myfile.lua"))
f () -- execute function now



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.


f = assert (loadstring ("print 'hello, world'"))
f ()   --> hello, world


You can avoid the intermediate variable "f" in this example by simply putting the brackets on the same line:


assert (loadstring ("print 'hello, world'")) () --> hello, world


If the string was produced by string.dump, loadstring converts it back into the original function.


function f () print "hello, world" end
s = string.dump (f)
assert (loadstring (s)) () --> hello, world


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.


function test ()
  local print = print  --> we need access to this global variable
  
  module "foo"  --> create the module now
  
  function add (a, b)
    return a + b
  end -- add
  
  function subtract (a, b)
    return a - b
  end -- subtract

  function hello (s)
    print ("hello", s)
  end -- hello

end -- function test

test ()  -- install module

foo.hello ("world")   --> hello	world
print (foo.add (2, 3))  --> 5
print (foo.subtract (7, 8))  --> -1

print (package.loaded["foo"]) --> table: 003055F0
print (foo)  --> table: 003055F0

for k, v in pairs (foo) do
  print (k, v)
end -- for 

-->

_M	table: 003055F0
_NAME	foo
_PACKAGE	

hello	function: 00305810
subtract	function: 00305760
add	function: 00305780


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.


t = { "hello", "world" }

for k, v in next, t do
  print (k, v)
end 

-->

1 hello
2 world



pairs (t)

Returns the 'next' function, the table t, and nil, for use in a for loop.


t = { "hello", "world" }

for k, v in pairs (t) do
  print (k, v)
end 



pcall (f, arg1, arg2, ...)

Calls function f with the supplied arguments in protected mode. Catches errors and returns:

On success:


  • true
  • function result(s)


On failure:


  • false
  • error message




function f (v)
  return v + 2
end -- f

a, b = pcall (f, 1)
print (a, b) --> true 3

a, b = pcall (f, "a")
print (a, b)  --> false   stdin:2: attempt to perform arithmetic on local `v' (a string value)




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.


print ("Hello", "world", 123, assert) --> Hello world 123 function: 02071C00



rawequal (v1, v2)

Returns a boolean depending on v1 == v2 without invoking any table metamethods.


print (rawequal (3, 3))) --> true



rawget (table, index)

Gets the real value of table [index] without invoking metamethods. Index should not be nil.


print (rawget (_G, "Note")) --> nil
print (rawget (world, "Note"))  --> function: 02058190
print (Note) --> function: 02058190 


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.


rawset (_G, "test", 42) 
print (test) --> 42



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:


  • If the table item package.preload [modname] is a function, that is called as the module loader.

  • Process the variable package.path, substituting modname where it has a "?" (that is, ? becomes the name) and then repeatedly attempting to open the files in the list (paths separated by semicolons) as Lua source files. The first attempt in the default configuration is in the current directory, for modname.lua, then in the executable directory (that is, where MUSHclient executable is, if you are running from MUSHclient), various combinations of subdirectories and file names. To see exactly what tests are being done, just type 'require "foo"' and the error message will show you.

  • Process the variable package.cpath, substituting modname where it has a "?" (that is, ? becomes the name) and then repeatedly attempting to open the files in the list (paths separated by semicolons) as DLLs. This attempts to load various DLLs, again see the package.cpath variable to see which ones exactly, or try a dummy require, as described above. If a DLL is found it attempts to call the function "luaopen_" concatenated with the module name, where dots are replaced by underscores.

  • Finally if all else fails try to load the all-in-one loader (executable-path/loadall.dll) and look for an appropriate function.


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].


f = require ("test")  --> loads module "test" 


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.


function f (...)
  print (select ("#", ...))  --> 4
  print (select (2, ...))    --> 20  30  40
end -- f

f (10, 20, 30, 40)


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.


function f (v)
  test = v  -- assign to global variable test
end -- function f

local myenv = {}  -- my local environment table
setfenv (f, myenv)  -- change environment for function f
f (42)  -- call f with new environment

print (test) --> nil  (global test was not changed)
print (myenv.test)  --> 42  (test inside myenv was changed)


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:


myenv.print = print -- copy print function into environment table


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 = 42
b = "nick"
c = { "the", "quick", "brown", "fox" }


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:


config = {} -- empty environment table
-- load the file, get a function to execute  
local f = assert (loadfile ("config.txt"))
-- want to load file into the config table
setfenv (f, config)
-- load it
f ()
print (config.a)  --> 42 


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):


  • __add - the + operation
  • __sub - the - operation
  • __mul - the * operation
  • __div - the / operation
  • __pow - the ^ (exponentiation) operation
  • __unm - the unary minus operation

  • __concat - the .. (concatenate) operation

  • __eq - the == operation
  • __lt - the < operation (a > b is the same as b < a)
  • __le - the <= operation (a >= b is the same as b <= a)

  • __index - called if an antry is not in the table
  • __newindex - called when adding an entry to the table
  • __call - called if you attempt to "call" the table
  • __gc - called after garbage collection
  • __mode - if it contains "k", keys are weak, if it contains "v", values are weak
  • __metatable - if present metatable cannot be changed, and this is the error message
  • __tostring - called to convert the table to a string


If there is no __le metamethod, Lua tries the __lt metamethod, assuming that:


a <= b  is equivalent to:  not (b < a)


Examples:


-- define adding to the table
t = { age = 42, height = 102 }
m = { __add = function (tbl, n) return t.age + n end }
setmetatable (t, m)
print (t + 1)  --> 43

-- define calling the table
t = { age = 42, height = 102 }
m = { __call = function (t) table.foreach (t, print) end }
setmetatable (t, m)
t ()  -- "call" the table (this prints each entry)

-->

height 102
age 42



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.


print (tonumber ("100100", 2)) --> 36
print (tonumber ("1e5")) --> 100000
print (tonumber ("1EF", 16)) --> 495 


You can use tonumber as a quick check if a variable contains something convertable to a number.


print (tonumber ("abc")) --> nil
print (tonumber ("-43")) --> -43
print (tonumber (-43))   --> -43


To see if the variable actually is already a number type, use the "type" function:


print (type ("-43")) --> string
print (type (-43))   --> number



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.


print (tostring (print)) --> function: 0205A980
print (tostring (_G)) --> table: 02072780
print (tostring (1.23e10)) --> 12300000000

-- use __tostring to print a table

t = { age = 42, height = 102 }

setmetatable (t, 
  { 
  __tostring = function (t) 
    return "person of age " .. t.age
    end -- __tostring 
  }
 )

print (t) --> person of age 42




type (v)

Returns a string, which is the type of the supplied variable:


  • nil
  • number
  • string
  • boolean
  • table
  • function
  • thread
  • userdata



print (type (42)) --> number
print (type ("42")) --> string
print (type (string)) --> table
print (type (tonumber)) --> function




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]


t = { "the", "quick", "brown" }

print (unpack (t)) --> the quick brown


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:


function ferror (fmt, ...)
  error (string.format (fmt, unpack (arg)), 2)
end -- ferror


However in Lua 5.1 this is more simply written as:


function ferror (fmt, ...)
  error (string.format (fmt, ...), 2)
end -- ferror


_VERSION

A global variable that is a string containing the current Lua interpreter version.


print (_VERSION) --> Lua 5.1



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.


function f ()
  return "a" + 2  -- will cause error
end -- f

function err (x)
  print ("err called", x)
  return "oh no!"
end -- err

print (xpcall (f, err))

 -->
 
err called [string "Immediate"]:2: attempt to perform arithmetic on a string value
false oh no!

function f2 ()
  return 2 + 2
end -- f

print (xpcall (f, err))  --> true 4

function f ()
return "a" + 2
end -- f

print (xpcall (f, debug.traceback))

 -->

false   stdin:2: attempt to perform arithmetic on a string value
stack traceback:
        stdin:2: in function `f'
        [C]: in function `xpcall'
        stdin:1: in main chunk
        [C]: ?




See Also ...

Topics

DOC_lua_coroutines Lua coroutine functions
DOC_lua_debug Lua debug functions
DOC_lua_io Lua io functions
DOC_lua_math Lua math functions
DOC_lua_os Lua os functions
DOC_lua_package Lua package functions
DOC_lua Lua script extensions
DOC_lua_string Lua string functions
DOC_lua_tables Lua table functions

(Help topic: general=lua_base)

DOC_contents Documentation contents page