Core Functions Tutorial

lua-users home
wiki

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 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,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 January 30, 2013 8:25 pm GMT (diff)