Lua’s learning notes (5) — basic library functions


The basic library provides Lua with some core functions. If this library is not included, you may need to implement some Lua language features yourself.

assert (v [, message])

If its parametersvThe value of is false(nilorfalse)It callserrorOtherwise, all parameters are returned. In the case of an error,messageRefers to the error object; if this parameter is not provided, the parameter defaults to “assertion failed!”.


Assert (5 = = 4, "number not equal!") >, error number not equal!
Assert (NIL) -- > error assertion failed!

collectgarbage (opt [, arg])

There are two parameters controlling the garbage collector, pause and step multipier.

The parameter pause controls how long the collector waits before starting a new collection cycle. As the number increases, the collector becomes less active. A value less than 1 means that the collector no longer waits at the start of a new cycle. A value of 2 means that a new cycle is opened when the total amount of memory used has doubled.

The parameter step multiplier controls the speed of the collector relative to memory allocation. A larger number will lead to a more active collector and increase the size of each step. A value less than 1 makes the collector work very slowly, which may cause the collector to never end the current cycle. The default value is 2, which means that the collector will run at twice the speed of the memory allocator.

This function is the general interface of the garbage collector according tooptDifferent parameters realize different functions.

  • “Stop”: stop garbage collection.
  • “Restart”: restart garbage collection.
  • “Collect”: performs a complete cycle of garbage collection.
  • “Count”: returns the total memory currently used by Lua (in KB).
  • “Step”: perform one step (one step can consist of multiple steps) garbage collection. The number of steps can be determined by the parameterargControl (the higher the value, the more steps, 0 means to perform one step (the smallest step)). If the recycle cycle is completed after execution, return totrue
  • “Setpause”: take Arg / 100 as the new value of garbage collection parameter pause.
  • “Set stepmuir”: take Arg / 100 as the new value of the garbage collection parameter step multiplier.


Memory usage before and after garbage collection:

x = collectgarbage("count")
print(x)            --> 27.5615234375
x = collectgarbage("count")
print(x)            --> 26.7490234375

dofile (filename)

Open the file with that name and execute the Lua code block in the file. When called without parameters, the dofile executes the contents of standard input (stdin). Returns all the return values of the code block. In case of an error, the dofile feeds the error back to the caller (that is, the dofile is not running in protected mode).


Create two Lua files in the same directory, code and output:

-- another.lua
return "Message from another file!"

-- sample.lua
x = dofile("./another.lua")
print(x)    --> Message from another file!

Dofile is equivalent here to

function dofile()
    function func()
        return "Message from another file!"

    return func()

So the equivalent output is

print(dofile()) --> Message from another file!

error (message [, level])

Terminate the protected function, throw a message, no longer return.

Usually, this function will prefix the thrown message with the address of the error. The stack level determines which address to add. If the stack level is 0, the address information is not returned; if it is 1, the location of the Error statement is returned; if it is 2, the location of the function where the error is called; and so on.


Error ([error message], [stack level] = 1)


function division(a,b)
    If B = = 0 then error ("division cannot be 0!", 2) end -- when the value of level is 1, the error message points here
    return a / b

Print (division (5,0)) -- when the level value is 2, the error message points here


_GLua does not use the variable that holds the global environment, and changing the variable will not affect the global environment; vice versa.

getfenv (f)

Returns the environment of the function. F can be a Lua function or the level of the function on the stack. Level 1 represents the function that calls getfenv(). If the function passed in is not Lua, or F is 0, then getfenv returns the global environment.

~~[to be added] I don’t quite understand. I didn’t give the proper code~~
reference resourcesThe concept of environment in Lua


Getfenv ([objective function] = 1)


Get global environment:

for k,v in pairs(_G) do

--string            table: 0x7ff200f02330
--xpcall            function: 0x7ff200d03cc0
--package           table: 0x7ff200e00000
--tostring          function: 0x7ff200d04560
--print             function: 0x7ff200d046a0
--os                table: 0x7ff200f01cb0
--unpack            function: 0x7ff200d04610
--require           function: 0x7ff200f006f0
--getfenv           function: 0x7ff200d042f0
--setmetatable      function: 0x7ff200d044a0
--next              function: 0x7ff200d04260
--assert            function: 0x7ff200d03fc0
--tonumber          function: 0x7ff200d04500
--io                table: 0x7ff200f014a0
--rawequal          function: 0x7ff200d046f0
--collectgarbage    function: 0x7ff200d04010
--arg               table: 0x7ff200e01360
--getmetatable      function: 0x7ff200d04340
--module            function: 0x7ff200f006a0
--rawset            function: 0x7ff200d047a0
--math              table: 0x7ff200e00040
--debug             table: 0x7ff200e00a00
--pcall             function: 0x7ff200d042b0
--table             table: 0x7ff200f00790
--newproxy          function: 0x7ff200d04820
--type              function: 0x7ff200d045c0
--coroutine         table: 0x7ff200d048c0
--_G                table: 0x7ff200d02fc0
--select            function: 0x7ff200d04400
--gcinfo            function: 0x7ff200d03000
--pairs             function: 0x7ff200d03e00
--rawget            function: 0x7ff200d04750
--loadstring        function: 0x7ff200d04200
--ipairs            function: 0x7ff200d03d70
--_VERSION          Lua 5.1
--dofile            function: 0x7ff200d04110
--setfenv           function: 0x7ff200d04450
--load              function: 0x7ff200d041b0
--error             function: 0x7ff200d04160
--loadfile          function: 0x7ff200d043a0

getmetatable (object)

If the object has no meta table, null is returned; if the object has__metatableField, return the corresponding value; otherwise, return the meta table of the object.


The objects are__metatableDomain:

t = {num = "a table"}

mt = {__index = {x = 1,y = 2},__metatable = {__index = {x = 5,y = 6}}}
setmetatable(t, mt)

print(getmetatable(t).__index.x)  --> 5
print(t.x)                        --> 1

~~The meta table of the operation is still the one directly associated with the value. I don’t know what the effect of this processing is? ~ ~

ipairs (t)

Three values are returned: iterator, table t passed in, and value 0. The iterator can get the values of I + 1 and T [i + 1] Based on the table T and index I passed in.

Its implementation is similar to this:

function ipairs(t)

    function iterator(t,i)
        i = i + 1
        I = t [i] and I -- if t [i] = = nil, then I = nil; otherwise I = I
        return i,t[i]

    return iterator,t,0



Using ipairs to traverse the table, it will traverse backward from the key value of 1 until the value is nil.

t = {"1","2",nil,[4]="4"}
--The output will be the same as "{4"}

for i,v in ipairs(t) do

--> 1   1
--> 2   2

load (func [, chunkname])

Get the code block fragment by passing in the return value of func. The string returned by the next call of func function should be able to join with the string returned from the previous call to get the complete code block. Function returns nil or no return value, indicating the end of the code block.

The load function returns the resulting block of code as a function. The environment of the return function is the global environment. If an error occurs, load returns nil and an error message.

Chunkname, as the name of the code block, is used in error and debug messages.


[to be added]

loadfile ([filename])

The usage is similar to dofile, and the function content is similar to load. Gets the code block from a file, or from standard input if no file is specified.

The LoadFile compiles the file code into the middle code, takes the file code as a code block (chunk), and returns the function containing the code block.
Compile the code into the middle code, and return the compiled chunk as a function. If an error occurs, nil and the error message are returned.

With LoadFile, you can compile and run multiple times at a time, and each time you use dofile, you will perform a compilation.


Create two Lua files in the same directory, code and output:

-- sample.lua
f = loadfile("./sample.lua")
--> Message from another file!
--> 0

-- another.lua
function fun()
 print("Message from another file!")
 return 0
res = fun()
return res

LoadFile is equivalent here to

function loadfile()
    function fun()
     print("Message from another file!")
     return 0
    res = fun()
    return res

loadstring (string [, chunkname])

Similar to load, it just takes a block of code from a string.

To load and run the given string, use the following idiomatic form:


next (table [, index])

Returns the next key value pair in the passed in table.


Next ([table], [key] = Nil)

The first parameter is the table to operate on, and the second parameter is a key in the table. If the key value passed in is nil, the function returns the first key value pair. If a valid key value is passed in, the next pair is output. Nil if there is no next key value pair.

By definition, you can use next to determine whether a table is empty.

be careful:

The traversal order of key value pairs is not certain, even for numeric indexes. If you want to get key value pairs in numerical index order, seeipairs (t)Function.


t = {"table",["a"] = 5, ["c"] = 6}

--The index is nil
print(next(t, nil))         --> 1   table

--Index is not a valid key
Print (next (T, "d"), compiler error

--Index is a numerical index
print(next(t,1))            --> a   5

--Index is the general key
print(next(t, "a"))         --> c   6

--Index is the last key
print(next(t,"c"))          --> nil

Examples of inconsistency between traversal order and definition order:

t = {[1]="table",b = 4,["a"] = 5, ["c"] = 6, func}

t.func = function (...)
    return true

for k,v in pairs(t) do
--> a   5
--> func    function: 0x7f7f63c0ad50
--> c   6
--> b   4

And you can see from the example abovename = expThe key value pair form of

pairs (t)

Return three values: next function, table t, nil. It is usually used to traverse all key value pairs in a table.
If t has a metamethod__ Pairs, passing t as an argument to the function and returning the first three return values.

In the process of traversing the table with the pairs function, you can delete fields or modify existing fields, but if you add new fields, unexpected problems may occur.


t = {"table",["a"] = 5, ["c"] = 6}
for k,v in pairs(t) do
--> 1   table
--> a   5
--> c   6

When adding a new field during traversal of the table causes problems:

t = {"table",["a"] = 5, ["c"] = 6}

for k,v in pairs(t) do
    --Add a new domain
    if k == 'a' then
        t[2] = 8
--> 1   table
--> a   5

pcall (f [, arg1, …])

The incoming function is called in protected mode, which means no error is thrown. If a thrown error is caught, the first parameter returns false, and the second parameter returns error information; if no error occurs, the first parameter returns true, and the subsequent parameter returns the return value of the passed in function.


function fun(a,b)

    assert(not(b == 0), "divisor can't be 0 !")

    return a / b    

success, res = pcall(fun,5,0) --> false .../sample.lua:3: divisor can't be 0 !
success, res = pcall(fun,5,1) --> true  5

print (…)

It is only used as a tool to quickly view a certain value without formatting the output. For formal formatted output, see string.format And io.write 。

rawequal (v1, v2)

withrawThe prefixed function means that the method is called without triggering any meta methods.

Rawequal checks whether V1 is equal to V2 and returns the comparison result.


t = {"value"}
s = "value"
s2 = "value"
print(rawequal(t, s))     --> false
print(rawequal(s, s2))    --> true

rawget (table, index)

Get the associated value of the key index in table. The table parameter must be a table. Nil is returned if it is not found.


t = {"value",x = 5}

print(rawget(t, 1))     --> value
print(rawget(t, "x"))   --> 5
print(rawget(t, 2))     --> nil
print(rawget("value",1))--> bad argument #1 to 'rawget' (table expected, got string)

rawset (table, index, value)

Set the value of table [index] to value. Table must be a table, and index cannot be nil or Nan. Value can be any value. Return the modified table.


t = {"value",x = 5}
t2 = {"sub table"}
rawset(t, 1,"new value")
rawset(t, "y", 6)
rawset(t, t2,"sub table")
rawset(t,NaN,"NaN")         --> table index is nil

print(t[1])                 --> new value
print(t.y)                  --> 6
print(t[t2])                --> sub table

select (index, …)

The index can be a number or a character ‘ා. When the index is a number, the first parameter + 1 and the following parameters are returned (index in the form of negative number is supported); when index is’ ා ‘, the number of parameters (excluding the first parameter) is returned.


t = {"table",x = 5}
t2 = {"table2"}

print(select(  1, 1, t, t2))    --> 1  table: 0x7fad7bc0a830 table: 0x7fad7bc0ac20
print(select( -3, 1, t, t2))    --> 1  table: 0x7fad7bc0a830 table: 0x7fad7bc0ac20
print(select("#", 1, t, t2))    --> 3

setfenv (f, table)

Set the environment table of function f to table. F can be a function or a number representing the stack level. The function at stack level 1 is the function that calls setfenv, and the function at stack level 2 is the function above. Setfenv returns F.

In particular, if f is 0, setfenv sets the global environment to table. And do nothing back.

Later versions of lua removed the setfenv and getfenv functions.


An example of using the stack level to operate setfenv:

function foobar(...)

    --Setting up the environment for foobar
    t = {}
    setmetatable(t, {__index = _G })
    a = 1
    b = 2

    --Output foobar environment
    for k,v in pairs(getfenv(1)) do

    function foo(...)
        --Set the environment of Foo and inherit the environment of foobar
        local t = {}
        setmetatable(t, {__index = _G})
        x = 3
        y = 4

        --Environment for foo output
        for k,v in pairs(getfenv(1)) do

        --Set foobar's environment again
        setfenv(2, t)


    --Output foobar's environment again
    for k,v in pairs(getfenv(1)) do


--> a   1
--> b   2
--> y   4
--> x   3
--> y   4
--> x   3

Setfenv is used to load the module:

-- sample.lua  file
Local funcenv = {} -- as environment
setmetatable(FuncEnv, {__ index = _ G} ) -- to access the values of the original global environment, set the global environment table (_ G) Put in meta table

local func=loadfile(" other.lua ") -- returns a function that takes the contents of the other file as a code block
Func () -- execute the code block to get the defined message function, which will exist in the environment
FuncEnv.message () -- funcenv is equivalent to a stand-alone module by calling the function through the environment
-- other.lua  file
function message()
    print("Message from another file!")

This section refers toSphinxOfSetting function environment — setfenvicydayOfThe use of setfenv in lua5.1Two blogs.

setmetatable (table, metatable)

Associate table with metatable. Return the parameter table.

If the meta table defines__metatableDomain, an error is thrown.

If the metatable parameter is nil, it means to disassociate the associated meta table.


--Associate a meta table that defines the addition operation
t = setmetatable({}, {__add = function(a,b)
    if type(a) == "table" and type(b) == "table" then
        return a.num + b.num

t.num = 5
t2 = {num = 6}
Print (T + T2) -- > 11 -- operations can be performed as long as one table is associated

setmetatable(t, nil)            

--Adding after disassociation will report an error
print(t+t2)         --> attempt to perform arithmetic on global 't' (a table value)

tonumber (e [, base])

ToNumber ([value], [cardinality] = 10)

Attempts to convert e to a decimal value and return. Nil if unable to convert.

Base represents the base of the parameter passed in. The default value is decimal. The input range of base [2,36]. Numbers above 10 are represented by letters, and A-Z stands for 11-35.


print(tonumber(123))            --> 123
print(tonumber("123"))          --> 123
print(tonumber("abc"))          --> nil
print(tonumber("abc", 20))      --> 4232
print(tonumber("ABC", 20))      --> 4232

tostring (e)

It can convert any type of value to a suitable string. To control how numbers are converted to strings, use thestring.format(formatstring,…)

If the meta table associated with the value has__tostringField, the meta method of the domain is used to get the string.


function func()
    print("this is a function")
t = {name = "table"}

print(tostring(123))        --> 123
print(tostring("abc"))      --> abc
print(tostring(func))       --> function: 0x7f86348013b0
print(tostring(t))          --> table: 0x7f86348013e0

type (v)

Returns the type of V, which is returned as a string. There are eight return values: “nil”, “number”, “string”, “Boolean”, “table”, “function”, “thread”, “UserData”.


type(nil)                   --> "nil"
type(false)                 --> "boolean"
type(123)                   --> "number"
type("abc")                 --> "string"

print(type(nil) == "nil")   --> true

unpack (list [, i [, j]])

Unpack ([list], [start position] = 1, [returned number] = [list length])

Returns the values of each field in the table, which is equivalent to returning

return list[i], list[i+1], ···, list[j]


t = {1,2,3,a = 4,b = 5}

print(unpack(t, 1, 4))      --> 1   2   3   nil


A global variable containing the version number of the current interpreter. The value of the current version is “Lua 5.1”.

xpcall (f, err [, arg1, …]

Andpcall (f, arg1, …)similar. The difference is that if the F function throws an error, xpcall does not return the error message thrown from F, but uses the error message returned by the err function.


Function fun (a, b) -- the parameters here have no practical effect, just show the usage
    error("something wrong !!", 1)

-- pcall 
local success, res = pcall(fun,1,2)
print(success,res)      --> false   .../sample.lua:2: something wrong !!

-- xpcall
local success, res = xpcall(fun,function()
    return "an error occured !!"
print(success,res)      --> false   an error occured !!

Reference link

Setting function environment — setfenv(explains how to easily set up the environment for a function and why it should be set that way)
The use of setfenv in lua5.1(this paper introduces an application of the environment setting in practice)
Introduction to Lua jelly series(a comprehensive introduction to Lua)