Core Functions Tutorial

lua-users home
wiki

Difference (from prior major revision) (minor diff, author diff)

Changed: 1c1
This page covers section 5.1 of the Reference Manual. These functions provide access to the core functionality of Lua. We will not go into detail about all of the topics here, but links will be mentioned to other parts of the tutorial for more detail.
This page covers section 5.1 of the Reference Manual.[1] These functions provide access to the core functionality of Lua. We will not go into detail about all of the topics here, but links will be mentioned to other parts of the tutorial for more detail.

Changed: 3c3
== assert(test [, message]) ==
== assert(test, [message]) ==

Changed: 5c5
Similar to the assert() function in C. If the test condition is false or nil an error is raised; otherwise test is returned. An optional message is returned instead of a system message. Also, see the error() function. E.g.,
assert [1] is similar to the assert() function in C. If the test condition is false or nil an error is raised; otherwise test is returned. An optional user-defined message is included in the error raised. Also, see the error() function. E.g.,

Changed: 22c22
Many Lua functions, such as io.open, return a value on success, or return nil and an error message on failure. This works well with assert:
Many Lua functions, such as io.open, return a value on success, or return nil and an error message on failure. This works well with assert:

Removed: 29d28
== collectgarbage([limit]) ==

Changed: 31,47c30,32
Sets the memory allocation limit at which the garbage collector will be called. If the new limit is less than the current amount of Lua memory allocation, or no argument is given, the collector is called immediately. See the GarbageCollectionTutorial for more information on.

> = gcinfo() -- find current memory stats, i.e. 21kb used
21 35
> bigalloc = string.rep('a', 100000) -- create a big string
> = gcinfo() -- 164kb allocated now
164 327
> collectgarbage() -- force collection
> = gcinfo() -- we did free some memory on collection
139 278
> bigalloc = nil -- release the string we created
> = gcinfo() -- it's not deleted until its collected
140 278
> collectgarbage() -- collect
> = gcinfo() -- it's deleted
29 59

== collectgarbage(opt [, arg]) ==

TODO: [1]

Changed: 51c36
TO DO: Opens the named file and executes its contents as a Lua chunk. When called without arguments, dofile executes the contents of the standard input (stdin). Returns any value returned by the chunk. In case of errors, dofile propagates the error to its caller (that is, it does not run in protected mode).
TODO: [1]

Changed: 55,56c40
TO DO: Terminates the last protected function called, and returns message as the error message. Function error never returns. The level argument specifies where the error message points the error. 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.

TODO: [1]

Changed: 60c44
_G is a global variable which points to the global environment. For example to display all of the globals variables we might do the following:
_G [1] is a global variable which points to the global environment. For example to display all of the globals variables we might do the following:

Removed: 88d71


Changed: 91c74
TODO: Returns the current environment in use by the function. f can be a Lua function or a number, which specifies the function at that stack level: Level 1 is the function calling getfenv. 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. if the environment has a "__fenv" field, returns the associated value, instead of the environment.
TODO: [1]

Changed: 95,99c78
TO DO: If the object does not have a metatable, returns nil. Otherwise, if the object's metatable has a "__metatable" field, returns the associated value. Otherwise, returns the metatable of the given object.

== gcinfo() ==

TO DO: Returns two results: the number of Kbytes of dynamic memory that Lua is using and the current garbage collector threshold (also in Kbytes).
TODO: [1]

Changed: 103,126c82
TODO: Returns an iterator function, the table t, and 0, so that the construction for i,v in ipairs(t) do ... end will iterate over the pairs (1,t[1]), (2,t[2]), ..., up to the first integer key with a nil value in the table.

== loadfile(filename) ==

TODO: Loads a file as a Lua chunk (without running it). 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.

== loadlib(libname, funcname) ==

This function links the program with the dynamic C library "libname". Inside this library, it looks for a function "funcname" and returns this function as a C function. libname must be the complete file name of the C library, including any eventual path and extension. This function is not supported by ANSI C. As such, it is only available on some platforms (Windows, Linux, Solaris, BSD, plus other Unix systems that support the dlfcn standard).

loadlib gives you the ability to enhance your lua scripts with self written C functions. The following example should give you some hints if you want to implement your own stuff. This was tested in Linux but should work on other platforms too. You should know how to create shared object libraries. All files in the example should be in the same directory.

{{{
/* mylib.c might look like this: */

#include "lua.h"
#include "stdio.h"

/* This function will be exported to lua */
static int lua_myfunc(lua_State* l)
{
printf("blabla");
return 0;
}
TODO: [1]

Changed: 128,133c84
/* This function is our Initialization */
int init(lua_State* l)
{
printf("Registering personal functions");

lua_register(l, "myfunc", lua_myfunc);
== load(func [, chunkname]) ==

Changed: 135,153c86
printf("Done registering");
return 0;
}
}}}

Now compile it as a library (in *nix or Cygwin):


gcc -Wall -g -O2 -shared `lua-config --include` -c mylib.c -o mylib.o
gcc mylib.o -Wall -g -O2 -shared `lua-config --include` `lua-config --libs` -o mylib.a


After this you should have a file called mylib.a, this is our library. Now lets write a simple test script in lua:

{{{
luainit = loadlib("./mylib.a", "init")

-- now call the initialization routine
luainit()
TODO: [1]

Changed: 155c88
print("New registered function: " .. myfunc)
== loadfile(filename) ==

Changed: 157,158c90
-- start the new function
myfunc()
TODO: [1]

Changed: 160,161c92
print("well done.")
}}}
== loadstring(string [, chunkname]) ==

Changed: 163c94
Email support is available from the author of this example @ reflex-2000 <aat> gmx < dottt> net
TODO: [1]

Changed: 165c96
== loadstring(string [, chunkname]) ==
== module(name [, ···])==

Changed: 167c98
TODO: Loads a string as a Lua chunk (without running it). 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. The optional parameter chunkname is the name to be used in error messages and debug information.
TODO: [1]

Changed: 171c102
TO DO: Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. next returns the next index of the table and the value associated with the index. When called with nil as its second argument, next returns the first index of the table and its associated value. When called with the last index, or with nil in an empty table, next returns nil. If the second argument is absent, then it is interpreted as nil. Lua has no declaration of fields; There is no difference between a field not present in a table or a field with value nil. Therefore, next only considers fields with non-nil values. The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numeric order, use a numerical for or the ipairs function.)
TODO: [1]

Changed: 175c106
TO DO: Returns the next function and the table t (plus a nil), so that the construction for k,v in pairs(t) do ... end
TODO: [1]

Changed: 177c108
== pcall(f, arg1, arg2, ...) ==
== pcall(f, arg1, ...) ==

Changed: 179c110
TO DO: Calls function f with the given arguments in protected mode. That 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 is true 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 returns false plus the error message.
TODO: [1]

Changed: 183c114
print can be passed any number of comma seperated arguments which it prints the values of to stdout. print uses tostring to convert the arguments into string form to be printed. E.g.
print [1] can be passed any number of comma-separated arguments which it prints the values of to stdout. print uses tostring to convert the arguments into string form to be printed. E.g.

Changed: 203c134
TO DO: Checks whether v1 is equal to v2, without invoking any metamethod. Returns a boolean.
TODO: [1]

Changed: 207c138
TO DO: Gets the real value of table[index], without invoking any metamethod. table must be a table; index is any value different from nil.
TODO: [1]

Changed: 211c142
TO DO: Sets the real value of table[index] to value, without invoking any metamethod. table must be a table, index is any value different from nil, and value is any Lua value.
TODO: [1]

Changed: 215c146,150
TO DO: Loads the given package. The function starts by looking into the table _LOADED to determine whether packagename is already loaded. If it is, then require returns the value that the package returned when it was first loaded. Otherwise, it searches a path looking for a file to load.
TODO: [1]

== select(index, ...) ==

TODO: [2]

Changed: 219c154
TO DO: Sets the current environment to be used by the given function. f can be a Lua function or a number, which specifies the function at that stack level: Level 1 is the function calling setfenv.
TODO: [1]

Changed: 223c158
TO DO: Sets the metatable for the given table. (You cannot change the metatable of a userdata from Lua.) If metatable is nil, removes the metatable of the given table. If the original metatable has a "__metatable" field, raises an error.
TODO: [1]

Changed: 227c162
TO DO: Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber returns that number; otherwise, it returns nil. An optional argument specifies the base to interpret the numeral. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter `A´ (in either upper or lower case) represents 10, `B´ represents 11, and so forth, with `Z´ representing 35. In base 10 (the default), the number may have a decimal part, as well as an optional exponent part (see 2.2.1). In other bases, only unsigned integers are accepted.
TODO: [1]

Changed: 231,233c166
Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, use format (see 5.3). If the metatable of e has a "__tostring" field, tostring calls the corresponding value with e as argument, and uses the result of the call as its result.

tostring converts its argument (just its first argument if there is more than one) to a string and returns that string. print is implemented using tostring so you are probably already familiar with the output format. Simple values (numbers, strings, booleans, and nil) are converted as you probably expect. Tables, Userdata, and Threads, are printed as `table:', `userdata:', or `thread:', followed by the address of an internal interpreter object (which should on no account be relied upon).
tostring [1] converts its argument (just its first argument if there is more than one) to a string and returns that string. print is implemented using tostring so you are probably already familiar with the output format. Simple values (numbers, strings, booleans, and nil) are converted as you probably expect. Tables, Userdata, and Threads, are printed as `table:', `userdata:', or `thread:', followed by the address of an internal interpreter object (which should on no account be relied upon).

Removed: 239d171


Changed: 242c174
type returns a string describing the type of the object passed to it.
type [1] returns a string describing the type of the object passed to it.

Changed: 259c191
unpack takes the elements of a list and returns them, e.g.:
unpack [1] takes the elements of a list and returns them, e.g.:

Changed: 279c211
Straight from from the manual, _VERSION is "a global variable (not a function) that holds a string containing the current interpreter version."
Straight from the manual, _VERSION [1] is "a global variable (not a function) that holds a string containing the current interpreter version."

Changed: 282c214
Lua 5.0
Lua 5.1

Changed: 287c219
TO DO: This function is similar to pcall, 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 such case, xpcall also returns all results from the call, after this first result. In case of any error, xpcall returns false plus the result from err.
TODO: [1]

This page covers section 5.1 of the Reference Manual.[1] These functions provide access to the core functionality of Lua. We will not go into detail about all of the topics here, but links will be mentioned to other parts of the tutorial for more detail.

assert(test, [message])

assert [2] is similar to the assert() function in C. If the test condition is false or nil an error is raised; otherwise test is returned. An optional user-defined message is included in the error raised. Also, see the error() function. E.g.,

> assert(1==1)          -- no error as test was true
> assert(1==0)
stdin:1: assertion failed!
stack traceback:
        [C]: in function `assert'
        stdin:1: in main chunk
        [C]: ?
> assert("green"=="blue", "Colours not equal")
stdin:1: Colours not equal
stack traceback:
        [C]: in function `assert'
        stdin:1: in main chunk
        [C]: ?

Many Lua functions, such as io.open, return a value on success, or return nil and an error message on failure. This works well with assert:

file = assert(io.open(filename))

This either opens filename for reading and assigns it to file, or it raises an error with the message in the second return value from io.open.

collectgarbage(opt [, arg])

TODO: [3]

dofile(filename)

TODO: [4]

error(message [, level])

TODO: [5]

_G

_G [6] is a global variable which points to the global environment. For example to display all of the globals variables we might do the following:

> table.foreach(_G,print)
string  table: 00357098
xpcall  function: 00354E10
tostring        function: 00354708
gcinfo  function: 00354E90
loadlib function: 00358B40
os      table: 00355AE0
unpack  function: 003547C8
level   2
require function: 00354F90
getfenv function: 00354548
... -- etc.

_G is also recursive as _G lives in _G! I.e. the following all point to the same table (which holds the global variables):

> = _G
table: 00353710
> = _G._G
table: 00353710
> = _G._G._G
table: 00353710

Lua itself does not use this variable, so changing its value does not affect any environment. You should use setfenv() to change environments.

getfenv(f)

TODO: [7]

getmetatable(object)

TODO: [8]

ipairs(t)

TODO: [9]

load(func [, chunkname])

TODO: [10]

loadfile(filename)

TODO: [11]

loadstring(string [, chunkname])

TODO: [12]

module(name [, ···])

TODO: [13]

next(table [, index])

TODO: [14]

pairs(t)

TODO: [15]

pcall(f, arg1, ...)

TODO: [16]

print(e1, e2, ...)

print [17] can be passed any number of comma-separated arguments which it prints the values of to stdout. print uses tostring to convert the arguments into string form to be printed. E.g.

> print(1,2,"buckle my shoe", 22/7)
1       2       buckle my shoe  3.1428571428571

print is very simple and will not recurse into tables printing the content, it will just print the type and a unique id.

> print({1,2,3})
table: 002FE9C8

print does not format text. In order to do this you should use the string.format() function in conjunction with print (see StringLibraryTutorial) E.g.,

> print(string.format("Pi is approximately %.4f", 22/7))
Pi is approximately 3.1429

rawequal(v1, v2)

TODO: [18]

rawget(table, index)

TODO: [19]

rawset(table, index, value)

TODO: [20]

require(packagename)

TODO: [21]

select(index, ...)

TODO: [22]

setfenv(f, table)

TODO: [23]

setmetatable(table, metatable)

TODO: [24]

tonumber(e [, base])

TODO: [25]

tostring(e)

tostring [26] converts its argument (just its first argument if there is more than one) to a string and returns that string. print is implemented using tostring so you are probably already familiar with the output format. Simple values (numbers, strings, booleans, and nil) are converted as you probably expect. Tables, Userdata, and Threads, are printed as `table:', `userdata:', or `thread:', followed by the address of an internal interpreter object (which should on no account be relied upon).

Note that unlike print, tostring doesn't print anything, it just converts its argument to a string and returns it.

tostring's behaviour is extensible. If the value to be converted has a metatable with a __tostring entry then that entry is called with the value to be converted and the result of that call is returned. This allows you to change how tostring works on (certain) tables, by giving them a metatable with a __tostring function that performs the conversion that you want.

type(v)

type [27] returns a string describing the type of the object passed to it.

> = type(1), type(true), type("hello"), type({}), type(function() end)
number  boolean string  table   function

Note, the type of nil is "nil".

> =type(nil)
nil

The possible types returned in Lua 5.0 are: "number", "string", "boolean, "table", "function", "thread", and "userdata". A "thread" is a coroutine, and "userdata" is a C data type with a reference to it in Lua.

unpack(list)

unpack [28] takes the elements of a list and returns them, e.g.:

> = unpack( {1,2,3} )
1       2       3
> = unpack( {"one",2,6*7} )
one     2       42

The number of elements unpacked is defined by the size of the table, which is not necessarily the number of elements in the table! See the TableLibraryTutorial for more details on this.

> t = {"one",2,6*7}
> t.n = 2
> = table.getn(t)
2
> = unpack(t)
one     2

_VERSION

Straight from the manual, _VERSION [29] is "a global variable (not a function) that holds a string containing the current interpreter version."

> = _VERSION
Lua 5.1

xpcall(f, err)

TODO: [30]

RecentChanges · preferences
edit · history
Last edited August 11, 2016 8:48 pm GMT (diff)