跟着 Lua 5.1 官方参考文档学习 Lua (9)

news/2025/2/27 11:07:49

文章目录

  • 5 – Standard Libraries
    • 5.1 – Basic Functions
      • 错误处理
        • `error (message [, level])`
          • 例子:error 函数的使用
          • 例子:error 函数 level 参数
          • 例子:使用 pcall 函数捕获错误
        • `assert (v [, message])`
          • 例子:assert 函数的使用
      • chunk
        • `load (func [, chunkname])`
          • 例子:load 函数的使用
        • `loadfile ([filename])`
          • 例子:loadfile 函数的使用
        • `loadstring (string [, chunkname])`
          • 例子:loadstring 函数的使用
        • `dofile ([filename])`
          • 例子:dofile 函数的使用
      • 全局变量表
        • `_G`
          • 例子:_G 的使用
        • `_VERSION`
      • 函数环境
        • `getfenv ([f])`
        • `setfenv (f, table)`
          • 例子:setfenv 函数的使用
      • 元表
        • `getmetatable (object)`
        • `setmetatable (table, metatable)`
          • 例子:重载 __index 元方法
          • 例子:重载 __newindex 元方法
          • 例子:重载算术操作符
          • 例子:重载 __call 元方法
      • table 操作
        • `ipairs (t)`
        • `pairs (t)`
        • `next (table [, index])`
          • 例子:next 函数的使用
        • `unpack (list [, i [, j]])`
          • 例子:unpack 函数的使用
          • 例子:unpack 函数的使用
        • `rawget (table, index)`
          • 例子:rawget 函数的使用
        • `rawset(table, index, value)`
          • 例子:rawset 函数的使用
      • 函数调用
        • `pcall (f, arg1, ···)`
          • 例子:pcall 函数的使用
        • `xpcall (f, err)`
          • 例子:xpcall 函数的使用
      • 输出
        • `print (···)`
      • 数字字符串转换
        • `tonumber (e [, base])`
        • `tostring (e)`
      • 垃圾回收
        • `collectgarbage ([opt [, arg]])`
      • 其他
        • `type (v)`
        • `rawequal (v1, v2)`
        • `select (index, ···)`
          • 例子:获取参数的个数
          • 例子:获取指定位置开始的所有参数

5 – Standard Libraries

The standard Lua libraries provide useful functions that are implemented directly through the C API. Some of these functions provide essential services to the language (e.g., type and getmetatable); others provide access to “outside” services (e.g., I/O); and others could be implemented in Lua itself, but are quite useful or have critical performance requirements that deserve an implementation in C (e.g., table.sort).

All libraries are implemented through the official C API and are provided as separate C modules. Currently, Lua has the following standard libraries:

  • basic library, which includes the coroutine sub-library;
  • package library;
  • string manipulation;
  • table manipulation;
  • mathematical functions (sin, log, etc.);
  • input and output;
  • operating system facilities;
  • debug facilities.

Except for the basic and package libraries, each library provides all its functions as fields of a global table or as methods of its objects.

To have access to these libraries, the C host program should call the luaL_openlibs function, which opens all standard libraries. Alternatively, it can open them individually by calling luaopen_base (for the basic library), luaopen_package (for the package library), luaopen_string (for the string library), luaopen_table (for the table library), luaopen_math (for the mathematical library), luaopen_io (for the I/O library), luaopen_os (for the Operating System library), and luaopen_debug (for the debug library). These functions are declared in lualib.h and should not be called directly: you must call them like any other Lua C function, e.g., by using lua_call.

5.1 – Basic Functions

The basic library provides some core functions to Lua. If you do not include this library in your application, you should check carefully whether you need to provide implementations for some of its facilities.

错误处理

error (message [, level])

Terminates the last protected function called and returns message as the error message. Function error never returns.

Usually, error adds some information about the error position at the beginning of the message. The level argument specifies how to get the error position. 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. Passing a level 0 avoids the addition of error position information to the message.

例子:error 函数的使用
function divide(a, b)
    if b == 0 then
        error("Division by zero is not allowed!")
    else
        return a / b
    end
end

print(divide(10, 2))  -- 输出: 5
print(divide(10, 0))  -- 抛出错误: Division by zero is not allowed!

例子:error 函数 level 参数
function func1()
    error("Something went wrong!", 2)
end

function func2()
    func1()
end

func2()


输出:

luajit: test.lua:6: Something went wrong!
stack traceback:
        [C]: in function 'error'
        test.lua:2: in function 'func1'
        test.lua:6: in function 'func2'
        test.lua:9: in main chunk
        [C]: at 0x00404b20

level参数值为2,报告错误的位置指向调用 func1 的 func2 函数

例子:使用 pcall 函数捕获错误
function divide(a, b)
    if b == 0 then
        error("Division by zero is not allowed!")
    else
        return a / b
    end
end

local success, message = pcall(function()
    return divide(10, 0)
end)

if not success then
    print("Error caught: " .. message)
end

assert (v [, message])

Issues an error when the value of its argument v is false (i.e., nil or false); otherwise, returns all its arguments. message is an error message; when absent, it defaults to “assertion failed!”

例子:assert 函数的使用
function divide(a, b)
    assert(b ~= 0, "Division by zero is not allowed!")
    return a / b
end

print(divide(10, 2))  -- 输出: 5
print(divide(10, 0))  -- 抛出错误: Division by zero is not allowed!

chunk

load (func [, chunkname])

Loads a chunk using function func to get its pieces. Each call to func must return a string that concatenates with previous results. A return of an empty string, 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.

chunkname is used as the chunk name for error messages and debug information. When absent, it defaults to “=(load)”.

例子:load 函数的使用
-- 模拟从一个源(比如文件、网络等)加载 Lua 代码
local code = {
    "local a = 5\n",
    "local b = 10\n",
    "return a + b\n"
}

-- 创建一个函数来逐步返回代码片段
local i = 1
local func = function()
    if i <= #code then
        local res = code[i]  -- 返回代码片段
        i = i + 1
        return res
    end
end

-- 使用 load 函数来加载这些代码片段
local chunk, err = load(func, "example_chunk")

-- 检查是否加载成功
if chunk then
    print(chunk())  -- 执行并输出: 15
else
    print("Error:", err)
end

loadfile ([filename])

Similar to load, but gets the chunk from file filename or from the standard input, if no file name is given.

例子:loadfile 函数的使用

example.lua

-- example.lua
return 3 + 4

test.lua

-- 加载文件
local func, err = loadfile("example.lua")

-- 检查是否加载成功
if func then
    print(func())  -- 输出: 7
else
    print("Error:", err)
end

loadstring (string [, chunkname])

Similar to load, but gets the chunk from the given string.

To load and run a given string, use the idiom

     assert(loadstring(s))()

When absent, chunkname defaults to the given string.

例子:loadstring 函数的使用
local code = "return 3 + 4"
local func, err = loadstring(code)

if func then
    print(func())  -- 输出: 7
else
    print("Error:", err)
end

dofile ([filename])

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 all values returned by the chunk. In case of errors, dofile propagates the error to its caller (that is, dofile does not run in protected mode).

例子:dofile 函数的使用

config.lua

-- config.lua
return "Hello from config file"

test.lua

local result = dofile("config.lua")
print(result)  -- 输出:Hello from config file

全局变量表

_G

A global variable (not a function) that holds the global environment (that is, _G._G = _G). Lua itself does not use this variable; changing its value does not affect any environment, nor vice-versa. (Use setfenv to change environments.)

例子:_G 的使用
_G["a"] = 1

print(a) -- 输出 1
_VERSION

A global variable (not a function) that holds a string containing the current interpreter version. The current contents of this variable is “Lua 5.1”.

函数环境

getfenv ([f])

Returns the current environment in use by the function. f can be a Lua function or a number that 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.

setfenv (f, table)

Sets the environment to be used by the given function. f can be a Lua function or a number that specifies the function at that stack level: Level 1 is the function calling setfenv. setfenv returns the given function.

As a special case, when f is 0 setfenv changes the environment of the running thread. In this case, setfenv returns no values.

例子:setfenv 函数的使用
function test()
    print(x)  -- 这里打印的是 x 的值
end

-- 默认环境
setfenv(test, { x = 42 })
test()  -- 输出:42

元表

getmetatable (object)

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

setmetatable (table, metatable)

Sets the metatable for the given table. (You cannot change the metatable of other types from Lua, only from C.) If metatable is nil, removes the metatable of the given table. If the original metatable has a "__metatable" field, raises an error.

This function returns table.

例子:重载 __index 元方法
-- 定义一个表
local t = {1, 2, 3}

-- 定义一个元表,重载 __index 元方法
local mt = {
    __index = function(table, key)
        return "Key " .. key .. " not found!"
    end
}

-- 设置元表
setmetatable(t, mt)

-- 测试
print(t[1])  -- 输出:1,因为原表有这个键
print(t[5])  -- 输出:Key 5 not found!,因为原表没有这个键

例子:重载 __newindex 元方法
-- 定义一个表
local t = {}

-- 定义元表,重载 __newindex 元方法
local mt = {
    __newindex = function(table, key, value)
        print("Setting " .. key .. " to " .. value)
        rawset(table, key, value)  -- 使用 rawset 来设置值
    end
}

-- 设置元表
setmetatable(t, mt)

-- 测试
t.foo = 42  -- 输出:Setting foo to 42
print(t.foo)  -- 输出:42

例子:重载算术操作符
-- 定义两个表
local a = {x = 1, y = 2}
local b = {x = 2, y = 3}

-- 定义元表,重载 __add 元方法
local mt = {
    __add = function(t1, t2)
        return {x = t1.x + t2.x, y = t1.y + t2.y}
    end
}

-- 设置元表
setmetatable(a, mt)
setmetatable(b, mt)

-- 使用加法操作符
local c = a + b
print(c.x, c.y)  -- 输出:3 5,因为 a.x + b.x = 3,a.y + b.y = 5

例子:重载 __call 元方法
-- 定义一个表
local t = {}

-- 定义元表,重载 __call 元方法
local mt = {
    __call = function(table, arg)
        return "You called the table with argument " .. arg
    end
}

-- 设置元表
setmetatable(t, mt)

-- 测试:将表当做函数调用
print(t("Hello"))  -- 输出:You called the table with argument Hello

table 操作

ipairs (t)

Returns three values: an iterator function, the table t, and 0, so that the construction

     for i,v in ipairs(t) do body end

will iterate over the pairs (1,t[1]), (2,t[2]), ···, up to the first integer key absent from the table.

pairs (t)

Returns three values: the next function, the table t, and nil, so that the construction

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

will iterate over all key–value pairs of table t.

See function next for the caveats of modifying the table during its traversal.

next (table [, index])

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 its associated value. When called with nil as its second argument, next returns an initial index 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. In particular, you can use next(t) to check whether a table is empty.

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

The behavior of next is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields.

例子:next 函数的使用
local t = {name = "John", age = 25, job = "developer"}

local key, value = next(t)
while key do
    print(key, value)
    key, value = next(t, key)
end

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

Returns the elements from the given table. This function is equivalent to

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

except that the above code can be written only for a fixed number of elements. By default, i is 1 and j is the length of the list, as defined by the length operator (see §2.5.5).

例子:unpack 函数的使用
local t = {10, 20, 30, 40, 50}

-- 拆分第 2 到第 4 个元素
local b, c, d = unpack(t, 2, 4)

print(b, c, d)  -- 输出:20 30 40

例子:unpack 函数的使用
local function sum(a, b, c, d)
    return a + b + c + d
end

local t = {10, 20, 30, 40}

-- 使用 unpack 将表传递给函数
local result = sum(unpack(t))

print(result)  -- 输出:100

rawget (table, index)

Gets the real value of table[index], without invoking any metamethod. table must be a table; index may be any value.

例子:rawget 函数的使用
local t = {a = 1, b = 2}

-- 设置元表,定义 __index 元方法
local mt = {
    __index = function(table, key)
        return "key not found"
    end
}

-- 设置元表
setmetatable(t, mt)

-- 使用普通索引操作,会触发 __index 元方法
print(t.c)  -- 输出:key not found

-- 使用 rawget 不会触发 __index 元方法
print(rawget(t, "c"))  -- 输出:nil (没有 c 键)

rawset(table, index, value)

Sets the real value of table[index] to value, without invoking any metamethod. table must be a table, index any value different from nil, and value any Lua value.

This function returns table.

例子:rawset 函数的使用
local t = {a = 1, b = 2}

-- 设置元表,定义 __newindex 元方法
local mt = {
    __newindex = function(table, key, value)
        print("Setting " .. key .. " to " .. value .. " via __newindex")
    end
}

-- 设置元表
setmetatable(t, mt)

-- 使用普通索引操作,会触发 __newindex 元方法
t.c = 3  -- 输出:Setting c to 3 via __newindex

-- 使用 rawset 设置值,不会触发 __newindex
rawset(t, "d", 4)

-- 输出表 t 中的所有键值
for key, value in pairs(t) do
    print(key, value)
end

函数调用

pcall (f, arg1, ···)

Calls function f with the given arguments in protected mode. This 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.

例子:pcall 函数的使用
function divide(a, b)
    if b == 0 then
        error("Division by zero is not allowed!")
    else
        return a / b
    end
end

local success, message = pcall(function()
    return divide(10, 0)
end)

if not success then
    print("Error caught: " .. message)
end

xpcall (f, err)

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

例子:xpcall 函数的使用
local function divide(a, b)
    if b == 0 then
        error("Division by zero")
    end
    return a / b
end

local function error_handler(err)
    return "Handled error: " .. err
end

local function safe_divide(a, b)
    local status, result = xpcall(divide, error_handler, a, b)
    if status then
        return result
    else
        print("Custom Error Handler: " .. result)  -- 自定义错误处理
        return nil
    end
end

print(safe_divide(10, 2))  -- 输出:5
print(safe_divide(10, 0))  -- 输出:Custom Error Handler: Handled error: Division by zero

输出

print (···)

Receives any number of arguments, and prints their values to stdout, using the tostring function to convert them to strings. print is not intended for formatted output, but only as a quick way to show a value, typically for debugging. For formatted output, use string.format.

数字字符串转换

tonumber (e [, base])

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 this 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 can have a decimal part, as well as an optional exponent part (see §2.1). In other bases, only unsigned integers are accepted.

tostring (e)

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 string.format.

If the metatable of e has a "__tostring" field, then tostring calls the corresponding value with e as argument, and uses the result of the call as its result.

垃圾回收

collectgarbage ([opt [, arg]])

This function is a generic interface to the garbage collector. It performs different functions according to its first argument, opt:

  • “collect”: performs a full garbage-collection cycle. This is the default option.
  • “stop”: stops the garbage collector.
  • “restart”: restarts the garbage collector.
  • “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 as the new value for the pause of the collector (see §2.10). Returns the previous value for pause.
  • “setstepmul”: sets arg as the new value for the step multiplier of the collector (see §2.10). Returns the previous value for step.

其他

type (v)

Returns the type of its only argument, coded as a string. The possible results of this function are “nil” (a string, not the value nil), “number”, “string”, “boolean”, “table”, “function”, “thread”, and “userdata”.

rawequal (v1, v2)

Checks whether v1 is equal to v2, without invoking any metamethod. Returns a boolean.

select (index, ···)

If index is a number, returns all arguments after argument number index. Otherwise, index must be the string "#", and select returns the total number of extra arguments it received.

例子:获取参数的个数
local function example(...)
    local num_args = select("#", ...)
    print("Number of arguments:", num_args)
end

example(1, 2, 3, 4)  -- 输出:Number of arguments: 4
example("a", "b")    -- 输出:Number of arguments: 2

例子:获取指定位置开始的所有参数
local function example(...)
    local first = select(1, ...)
    local second = select(2, ...)
    print("First:", first)
    print("Second:", second)
    print("Rest:", select(3, ...))
end

example(1, 2, 3, 4)  -- 输出:First: 1, Second: 2, Rest: 3  4


http://www.niftyadmin.cn/n/5870011.html

相关文章

电脑键盘知识

1、键盘四大功能区 1. 功能区 2. 主要信息输入区 3. 编辑区 4. 数字键盘区 笔记本电脑键盘的功能区&#xff0c;使用前需先按Fn键 1.1、功能区 ESC&#xff1a;退出 F1&#xff1a;显示帮助信息 F2&#xff1a;重命名 F4&#xff1a;重复上一步操作 F5&#xff1a;刷新网页 …

python 程序

gif调整尺寸.py import sys from PIL import Image,ImageSequence import os ##print(sys.argv[0]) ##print(sys.argv[1]) def gifresize(file_name): gf Image.open(file_name) ## lifetime gf.info[duration] imglist [] imgnew [] for i in ImageSequence.…

AI工具箱最新使用教程

先克隆项目 电脑需要先安装 git &#xff0c;安装的画看这个 Git安装教程&#xff08;超详细&#xff09;。 git镜像 git clone https://github.com/Escaflowne1985/MyToolsWebBackendUser.gitgitee镜像 git clone https://gitee.com/escaflowne/MyToolsWebBackendUser.git…

华为机试牛客刷题之HJ75 公共子串计算

HJ75 公共子串计算 描述 对于给定的两个字符串s和t&#xff0c;你需要找出它们的最长公共子串的长度。 子串为从原字符串中&#xff0c;连续的选择一段字符(可以全选、可以不选)得到的新字符串。 如果字符串 α 的一个子串 a’与字符串b的一个子串b 完全相等&#xff0c;那…

QILSTE H6-C210FO/5M高亮橙光LED灯珠 发光二极管LED

### H6-C210FO/5M&#xff1a;高亮橙光LED的技术参数与复杂特性 在电子设备的精密制造领域&#xff0c;H6-C210FO/5M型号的高亮橙光LED凭借其独特的设计和复杂的参数规格脱颖而出。这款由QILSTE&#xff08;Hong Kong&#xff09;Technology Co., Ltd生产的LED&#xff0c;尺寸…

004 Kafka异常处理

6.异常处理 文章目录 6.异常处理1.异常分类与处理原则2.生产者异常处理1. 同步发送捕获异常2. 异步发送回调处理 3.消费者异常处理1.全局异常处理器2.方法级处理3.重试yml配置 4.死信队列&#xff08;DLQ&#xff09;配置1. 启用死信队列2. 手动发送到DLQ 5.事务场景异常处理1.…

「拼好帧」小黄鸭 Lossless Scaling 软件介绍与下载

「拼好帧」小黄鸭 Lossless Scaling 软件介绍与下载 在游戏和视频播放时&#xff0c;你是否遇到过分辨率不匹配、画质模糊的问题&#xff1f;今天给大家介绍一款神器——Lossless Scaling&#xff08;拼好帧&#xff09;&#xff0c;也被玩家们亲切地称为“小黄鸭”&#xff0…

磁场定向控制 (FOC)模型的C语言实现(STM32G4)

目录 概述 1 磁场定向控制 (FOC)介绍 1.1 FOC控制模型介绍 1.2 模型功能 2 FOC模型的几个重要的转换关系 2.1 Clarke Transform 2.2 Inverse Clarke Transform 2.3 Park Transform 2.4 Inverse Park Transform 3 STM32模拟实现FOC 3.1 FOC算法的C语言实现 3.2…