Lua Standard Library
8 methodsLua 标准库核心函数集合。
print(...)打印参数到标准输出,以制表符分隔并换行。
Parameters
| Name | Type | Description |
|---|---|---|
| args | ... | 任意数量参数 |
Returns
无
Example
lua
print("hello", "world") -- hello world
print(1, 2, 3) -- 1 2 3string.format(fmt, ...)按 C 风格格式字符串格式化参数。
Parameters
| Name | Type | Description |
|---|---|---|
| format | string | 格式字符串,如 '%d' |
| args | ... | 参数 |
Returns
string,格式化结果
Example
lua
string.format("%s = %d", "answer", 42)
-- "answer = 42"
string.format("%.2f", 3.14159) -- "3.14"string.len(s) / #s返回字符串字节长度。
Parameters
| Name | Type | Description |
|---|---|---|
| s | string | 字符串 |
Returns
number,字节长度
Example
lua
string.len("hello") -- 5
local s = "lua"
print(#s) -- 3string.sub(s, i, j)返回从 i 到 j 的子串(索引从 1 开始,负数表示倒数)。
Parameters
| Name | Type | Description |
|---|---|---|
| s | string | 源字符串 |
| i | number | 起始索引 |
| j | number | 结束索引(默认 -1) |
Returns
string,子串
Example
lua
string.sub("hello", 2, 4) -- "ell"
string.sub("hello", -3) -- "llo"table.insert(t, [pos,] v)向表中插入元素,默认追加到末尾。
Parameters
| Name | Type | Description |
|---|---|---|
| table | table | 目标表(序列部分) |
| pos | number | 插入位置(可选) |
| value | any | 插入的值 |
Returns
无,表被修改
Example
lua
local t = {1, 2, 3}
table.insert(t, 4) -- {1,2,3,4}
table.insert(t, 1, 0) -- {0,1,2,3,4}table.concat(t, sep)将表的序列部分用分隔符拼接为字符串。
Parameters
| Name | Type | Description |
|---|---|---|
| table | table | 字符串序列 |
| separator | string | 分隔符(默认空串) |
Returns
string,拼接结果
Example
lua
local t = {"a", "b", "c"}
table.concat(t, ", ") -- "a, b, c"
table.concat(t, "-") -- "a-b-c"pairs(t) / ipairs(t)pairs 遍历所有键值对,ipairs 遍历序列部分(1,2,3...)。
Parameters
| Name | Type | Description |
|---|---|---|
| table | table | 目标表 |
Returns
迭代器函数,用于 for 循环
Example
lua
local t = {10, 20, 30, name="x"}
for i, v in ipairs(t) do print(i, v) end -- 1 10 / 2 20 / 3 30
for k, v in pairs(t) do print(k, v) end -- 所有键值对require(modname)加载并缓存模块,返回模块返回值。
Parameters
| Name | Type | Description |
|---|---|---|
| modname | string | 模块名 |
Returns
any,模块返回值
Example
lua
local json = require("dkjson")
local m = require("math")
print(m.pi)