跟着 Lua 5.1 官方参考文档学习 Lua (8)
文章目录
- 4 – The Auxiliary Library
- 4.1 – Functions and Types
- 字符串缓冲区
- `luaL_Buffer`
- `luaL_buffinit`
- `luaL_addchar`
- `luaL_addstring`
- `luaL_addlstring`
- `luaL_addvalue`
- `luaL_prepbuffer`
- `luaL_addsize`
- `luaL_pushresult`
- 例子:luaL_Buffer 的使用
- 函数参数检查
- `luaL_argcheck`
- `luaL_argerror`
- `luaL_typerror`
- `luaL_checkint`
- `luaL_checkinteger`
- `luaL_checklong`
- `luaL_checknumber`
- `luaL_checkstring`
- `luaL_checklstring`
- `luaL_checkoption`
- `luaL_checkany`
- `luaL_checkstack`
- `luaL_checktype`
- `luaL_checkudata`
- `luaL_optint`
- `luaL_optinteger`
- `luaL_optlong`
- `luaL_optnumber`
- `luaL_optstring`
- `luaL_optlstring`
- chunk
- `luaL_loadbuffer`
- `luaL_loadfile`
- `luaL_loadstring`
- `luaL_dofile`
- `luaL_dostring`
- 元表
- `luaL_newmetatable`
- `luaL_getmetatable`
- `luaL_getmetafield`
- `luaL_callmeta`
- 例子:创建 userdata
- 引用
- `luaL_ref`
- `luaL_unref`
- 注册 C 函数
- `luaL_Reg`
- `luaL_register`
- 其他
- `luaL_newstate`
- `luaL_openlibs`
- `luaL_typename`
- `luaL_where`
- `luaL_error`
- `luaL_gsub`
4 – The Auxiliary Library
The auxiliary library provides several convenient functions to interface C with Lua. While the basic API provides the primitive functions for all interactions between C and Lua, the auxiliary library provides higher-level functions for some common tasks.
All functions from the auxiliary library are defined in header file lauxlib.h
and have a prefix luaL_
.
All functions in the auxiliary library are built on top of the basic API, and so they provide nothing that cannot be done with this API.
Several functions in the auxiliary library are used to check C function arguments. Their names are always luaL_check*
or luaL_opt*
. All of these functions throw an error if the check is not satisfied. Because the error message is formatted for arguments (e.g., “bad argument #1
”), you should not use these functions for other stack values.
4.1 – Functions and Types
Here we list all functions and types from the auxiliary library in alphabetical order.
字符串缓冲区
luaL_Buffer
typedef struct luaL_Buffer luaL_Buffer;
Type for a string buffer.
A string buffer allows C code to build Lua strings piecemeal. Its pattern of use is as follows:
- First you declare a variable
b
of typeluaL_Buffer
. - Then you initialize it with a call
luaL_buffinit(L, &b)
. - Then you add string pieces to the buffer calling any of the
luaL_add*
functions. - You finish by calling
luaL_pushresult(&b)
. This call leaves the final string on the top of the stack.
During its normal operation, a string buffer uses a variable number of stack slots. So, while using a buffer, you cannot assume that you know where the top of the stack is. You can use the stack between successive calls to buffer operations as long as that use is balanced; that is, when you call a buffer operation, the stack is at the same level it was immediately after the previous buffer operation. (The only exception to this rule is luaL_addvalue
.) After calling luaL_pushresult
the stack is back to its level when the buffer was initialized, plus the final string on its top.
luaL_buffinit
[-0, +0, -]
void luaL_buffinit (lua_State *L, luaL_Buffer *B);
Initializes a buffer B
. This function does not allocate any space; the buffer must be declared as a variable (see luaL_Buffer
).
luaL_addchar
[-0, +0, m]
void luaL_addchar (luaL_Buffer *B, char c);
Adds the character c
to the buffer B
(see luaL_Buffer
).
luaL_addstring
[-0, +0, m]
void luaL_addstring (luaL_Buffer *B, const char *s);
Adds the zero-terminated string pointed to by s
to the buffer B
(see luaL_Buffer
). The string may not contain embedded zeros.
luaL_addlstring
[-0, +0, m]
void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);
Adds the string pointed to by s
with length l
to the buffer B
(see luaL_Buffer
). The string may contain embedded zeros.
luaL_addvalue
[-1, +0, m]
void luaL_addvalue (luaL_Buffer *B);
Adds the value at the top of the stack to the buffer B
(see luaL_Buffer
). Pops the value.
This is the only function on string buffers that can (and must) be called with an extra element on the stack, which is the value to be added to the buffer.
luaL_prepbuffer
[-0, +0, -]
char *luaL_prepbuffer (luaL_Buffer *B);
Returns an address to a space of size LUAL_BUFFERSIZE
where you can copy a string to be added to buffer B
(see luaL_Buffer
). After copying the string into this space you must call luaL_addsize
with the size of the string to actually add it to the buffer.
luaL_addsize
[-0, +0, m]
void luaL_addsize (luaL_Buffer *B, size_t n);
Adds to the buffer B
(see luaL_Buffer
) a string of length n
previously copied to the buffer area (see luaL_prepbuffer
).
luaL_pushresult
[-?, +1, m]
void luaL_pushresult (luaL_Buffer *B);
Finishes the use of buffer B
leaving the final string on the top of the stack.
例子:luaL_Buffer 的使用
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <string.h>
int my_buffer_example(lua_State *L) {
// 声明 luaL_Buffer 变量
luaL_Buffer b;
// 初始化缓冲区
luaL_buffinit(L, &b);
// 获取预分配的缓冲区地址
char *buf = luaL_prepbuffer(&b);
// 复制字符串到该缓冲区
strcpy(buf, "Hello, ");
// 更新缓冲区,表明已经添加了一个字符串片段
luaL_addsize(&b, strlen("Hello, "));
// 继续添加更多的字符串
buf = luaL_prepbuffer(&b);
strcpy(buf, "Lua!");
luaL_addsize(&b, strlen("Lua!"));
// 继续添加更多的字符串
luaL_addstring(&b, "this is a test.");
// 完成缓冲区的构建,将最终结果压入栈
luaL_pushresult(&b);
// 输出最终字符串
const char *result = lua_tostring(L, -1);
printf("Final string: %s\n", result); // 打印最终字符串
return 1; // 返回 1,表示我们将一个值(最终的字符串)推入栈中
}
int main(void) {
// 创建一个 Lua 状态
lua_State *L = luaL_newstate();
// 打开标准库
luaL_openlibs(L);
// 注册自定义的 C 函数
lua_register(L, "my_buffer_example", my_buffer_example);
// 执行 Lua 代码,调用我们的 C 函数
luaL_dostring(L, "my_buffer_example()");
// 关闭 Lua 状态
lua_close(L);
return 0;
}
输出
Final string: Hello, Lua!this is a test.
函数参数检查
luaL_argcheck
[-0, +0, v]
void luaL_argcheck (lua_State *L,
int cond,
int narg,
const char *extramsg);
Checks whether cond
is true. If not, raises an error with the following message, where func
is retrieved from the call stack:
bad argument #<narg> to <func> (<extramsg>)
luaL_argerror
[-0, +0, v]
int luaL_argerror (lua_State *L, int narg, const char *extramsg);
Raises an error with the following message, where func
is retrieved from the call stack:
bad argument #<narg> to <func> (<extramsg>)
This function never returns, but it is an idiom to use it in C functions as return luaL_argerror(*args*)
.
luaL_typerror
[-0, +0, v]
int luaL_typerror (lua_State *L, int narg, const char *tname);
Generates an error with a message like the following:
location: bad argument narg to 'func' (tname expected, got rt)
where *location*
is produced by luaL_where
, *func*
is the name of the current function, and *rt*
is the type name of the actual argument.
luaL_checkint
[-0, +0, v]
int luaL_checkint (lua_State *L, int narg);
Checks whether the function argument narg
is a number and returns this number cast to an int
.
luaL_checkinteger
[-0, +0, v]
lua_Integer luaL_checkinteger (lua_State *L, int narg);
Checks whether the function argument narg
is a number and returns this number cast to a lua_Integer
.
luaL_checklong
[-0, +0, v]
long luaL_checklong (lua_State *L, int narg);
Checks whether the function argument narg
is a number and returns this number cast to a long
.
luaL_checknumber
[-0, +0, v]
lua_Number luaL_checknumber (lua_State *L, int narg);
Checks whether the function argument narg
is a number and returns this number.
luaL_checkstring
[-0, +0, v]
const char *luaL_checkstring (lua_State *L, int narg);
Checks whether the function argument narg
is a string and returns this string.
This function uses lua_tolstring
to get its result, so all conversions and caveats of that function apply here.
luaL_checklstring
[-0, +0, v]
const char *luaL_checklstring (lua_State *L, int narg, size_t *l);
Checks whether the function argument narg
is a string and returns this string; if l
is not NULL
fills *l
with the string’s length.
This function uses lua_tolstring
to get its result, so all conversions and caveats of that function apply here.
luaL_checkoption
[-0, +0, v]
int luaL_checkoption (lua_State *L,
int narg,
const char *def,
const char *const lst[]);
Checks whether the function argument narg
is a string and searches for this string in the array lst
(which must be NULL-terminated). Returns the index in the array where the string was found. Raises an error if the argument is not a string or if the string cannot be found.
If def
is not NULL
, the function uses def
as a default value when there is no argument narg
or if this argument is nil.
This is a useful function for mapping strings to C enums. (The usual convention in Lua libraries is to use strings instead of numbers to select options.)
luaL_checkany
[-0, +0, v]
void luaL_checkany (lua_State *L, int narg);
Checks whether the function has an argument of any type (including nil) at position narg
.
luaL_checkstack
[-0, +0, v]
void luaL_checkstack (lua_State *L, int sz, const char *msg);
Grows the stack size to top + sz
elements, raising an error if the stack cannot grow to that size. msg
is an additional text to go into the error message.
luaL_checktype
[-0, +0, v]
void luaL_checktype (lua_State *L, int narg, int t);
Checks whether the function argument narg
has type t
. See lua_type
for the encoding of types for t
.
luaL_checkudata
[-0, +0, v]
void *luaL_checkudata (lua_State *L, int narg, const char *tname);
Checks whether the function argument narg
is a userdata of the type tname
(see luaL_newmetatable
).
luaL_optint
[-0, +0, v]
int luaL_optint (lua_State *L, int narg, int d);
If the function argument narg
is a number, returns this number cast to an int
. If this argument is absent or is nil, returns d
. Otherwise, raises an error.
luaL_optinteger
[-0, +0, v]
lua_Integer luaL_optinteger (lua_State *L,
int narg,
lua_Integer d);
If the function argument narg
is a number, returns this number cast to a lua_Integer
. If this argument is absent or is nil, returns d
. Otherwise, raises an error.
luaL_optlong
[-0, +0, v]
long luaL_optlong (lua_State *L, int narg, long d);
If the function argument narg
is a number, returns this number cast to a long
. If this argument is absent or is nil, returns d
. Otherwise, raises an error.
luaL_optnumber
[-0, +0, v]
lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);
If the function argument narg
is a number, returns this number. If this argument is absent or is nil, returns d
. Otherwise, raises an error.
luaL_optstring
[-0, +0, v]
const char *luaL_optstring (lua_State *L,
int narg,
const char *d);
If the function argument narg
is a string, returns this string. If this argument is absent or is nil, returns d
. Otherwise, raises an error.
luaL_optlstring
[-0, +0, v]
const char *luaL_optlstring (lua_State *L,
int narg,
const char *d,
size_t *l);
If the function argument narg
is a string, returns this string. If this argument is absent or is nil, returns d
. Otherwise, raises an error.
If l
is not NULL
, fills the position *l
with the results’s length.
chunk
luaL_loadbuffer
[-0, +1, m]
int luaL_loadbuffer (lua_State *L,
const char *buff,
size_t sz,
const char *name);
Loads a buffer as a Lua chunk. This function uses lua_load
to load the chunk in the buffer pointed to by buff
with size sz
.
This function returns the same results as lua_load
. name
is the chunk name, used for debug information and error messages.
luaL_loadfile
[-0, +1, m]
int luaL_loadfile (lua_State *L, const char *filename);
Loads a file as a Lua chunk. This function uses lua_load
to load the chunk in the file named filename
. If filename
is NULL
, then it loads from the standard input. The first line in the file is ignored if it starts with a #
.
This function returns the same results as lua_load
, but it has an extra error code LUA_ERRFILE
if it cannot open/read the file.
As lua_load
, this function only loads the chunk; it does not run it.
luaL_loadstring
[-0, +1, m]
int luaL_loadstring (lua_State *L, const char *s);
Loads a string as a Lua chunk. This function uses lua_load
to load the chunk in the zero-terminated string s
.
This function returns the same results as lua_load
.
Also as lua_load
, this function only loads the chunk; it does not run it.
luaL_dofile
[-0, +?, m]
int luaL_dofile (lua_State *L, const char *filename);
Loads and runs the given file. It is defined as the following macro:
(luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
It returns 0 if there are no errors or 1 in case of errors.
luaL_dostring
[-0, +?, m]
int luaL_dostring (lua_State *L, const char *str);
Loads and runs the given string. It is defined as the following macro:
(luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
It returns 0 if there are no errors or 1 in case of errors.
元表
luaL_newmetatable
[-0, +1, m]
int luaL_newmetatable (lua_State *L, const char *tname);
If the registry already has the key tname
, returns 0. Otherwise, creates a new table to be used as a metatable for userdata, adds it to the registry with key tname
, and returns 1.
In both cases pushes onto the stack the final value associated with tname
in the registry.
参考 luaL_checkudata
luaL_getmetatable
[-0, +1, -]
void luaL_getmetatable (lua_State *L, const char *tname);
Pushes onto the stack the metatable associated with name tname
in the registry (see luaL_newmetatable
).
luaL_getmetafield
[-0, +(0|1), m]
int luaL_getmetafield (lua_State *L, int obj, const char *e);
Pushes onto the stack the field e
from the metatable of the object at index obj
. If the object does not have a metatable, or if the metatable does not have this field, returns 0 and pushes nothing.
luaL_callmeta
[-0, +(0|1), e]
int luaL_callmeta (lua_State *L, int obj, const char *e);
Calls a metamethod.
If the object at index obj
has a metatable and this metatable has a field e
, this function calls this field and passes the object as its only argument. In this case this function returns 1 and pushes onto the stack the value returned by the call. If there is no metatable or no metamethod, this function returns 0 (without pushing any value on the stack).
例子:创建 userdata
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <stdio.h>
// 如何创建并使用 userdata
// gcc -o 1 1.c -I/usr/local/include/luajit-2.1 -lluajit-5.1
// 定义一个简单的结构体,用作 userdata
typedef struct {
int x, y;
} Point;
// 元方法:打印 Point 的内容
int point_tostring(lua_State *L) {
Point *p = (Point*)luaL_checkudata(L, 1, "PointMetaTable");
lua_pushfstring(L, "Point(%d, %d)", p->x, p->y);
return 1; // 返回一个字符串
}
// 定义一个元表
void create_metatable(lua_State *L) {
luaL_newmetatable(L, "PointMetaTable"); // 创建元表,并压入栈[1]
lua_pushcfunction(L, point_tostring); // point_tostring 函数压入栈[2]
lua_setfield(L, -2, "__tostring"); // 将 tostring 函数绑定到 __tostring 元方法
// 会将函数弹出栈
lua_pop(L, 1); // 弹出元表
}
int main() {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
// 创建元表
create_metatable(L);
// 创建一个 Point 结构体的实例
Point *p = (Point*)lua_newuserdata(L, sizeof(Point)); // 分配 userdata 空间,入栈[1]
p->x = 10; // 设置数据
p->y = 20;
// 设置 userdata 的元表
luaL_getmetatable(L, "PointMetaTable"); // 获取元表,入栈[2]
lua_setmetatable(L, -2); // 设置当前的 userdata 的元表。元表会出栈
// 调用 tostring 元方法打印
lua_getglobal(L, "tostring"); // tostring函数入栈[2]
lua_pushvalue(L, -2); // 将 userdata 作为参数传入 tostring[3]
lua_call(L, 1, 1); // 调用 tostring
const char* result = lua_tostring(L, -1); // 获取结果
printf("Result: %s\n", result); // 输出 "Result: Point(10, 20)"
lua_close(L);
return 0;
}
引用
luaL_ref
[-1, +0, m]
int luaL_ref (lua_State *L, int t);
Creates and returns a reference, in the table at index t
, for the object at the top of the stack (and pops the object).
A reference is a unique integer key. As long as you do not manually add integer keys into table t
, luaL_ref
ensures the uniqueness of the key it returns. You can retrieve an object referred by reference r
by calling lua_rawgeti(L, t, r)
. Function luaL_unref
frees a reference and its associated object.
If the object at the top of the stack is nil, luaL_ref
returns the constant LUA_REFNIL
. The constant LUA_NOREF
is guaranteed to be different from any reference returned by luaL_ref
.
luaL_unref
[-0, +0, -]
void luaL_unref (lua_State *L, int t, int ref);
Releases reference ref
from the table at index t
(see luaL_ref
). The entry is removed from the table, so that the referred object can be collected. The reference ref
is also freed to be used again.
If ref
is LUA_NOREF
or LUA_REFNIL
, luaL_unref
does nothing.
注册 C 函数
luaL_Reg
typedef struct luaL_Reg {
const char *name;
lua_CFunction func;
} luaL_Reg;
Type for arrays of functions to be registered by luaL_register
. name
is the function name and func
is a pointer to the function. Any array of luaL_Reg
must end with an sentinel entry in which both name
and func
are NULL
.
luaL_register
[-(0|1), +1, m]
void luaL_register (lua_State *L,
const char *libname,
const luaL_Reg *l);
Opens a library.
When called with libname
equal to NULL
, it simply registers all functions in the list l
(see luaL_Reg
) into the table on the top of the stack.
When called with a non-null libname
, luaL_register
creates a new table t
, sets it as the value of the global variable libname
, sets it as the value of package.loaded[libname]
, and registers on it all functions in the list l
. If there is a table in package.loaded[libname]
or in variable libname
, reuses this table instead of creating a new one.
In any case the function leaves the table on the top of the stack.
其他
luaL_newstate
[-0, +0, -]
lua_State *luaL_newstate (void);
Creates a new Lua state. It calls lua_newstate
with an allocator based on the standard C realloc
function and then sets a panic function (see lua_atpanic
) that prints an error message to the standard error output in case of fatal errors.
Returns the new state, or NULL
if there is a memory allocation error.
luaL_openlibs
[-0, +0, m]
void luaL_openlibs (lua_State *L);
Opens all standard Lua libraries into the given state.
luaL_typename
[-0, +0, -]
const char *luaL_typename (lua_State *L, int index);
Returns the name of the type of the value at the given index.
luaL_where
[-0, +1, m]
void luaL_where (lua_State *L, int lvl);
Pushes onto the stack a string identifying the current position of the control at level lvl
in the call stack. Typically this string has the following format:
chunkname:currentline:
Level 0 is the running function, level 1 is the function that called the running function, etc.
This function is used to build a prefix for error messages.
luaL_error
[-0, +0, v]
int luaL_error (lua_State *L, const char *fmt, ...);
Raises an error. The error message format is given by fmt
plus any extra arguments, following the same rules of lua_pushfstring
. It also adds at the beginning of the message the file name and the line number where the error occurred, if this information is available.
This function never returns, but it is an idiom to use it in C functions as return luaL_error(*args*)
.
luaL_gsub
[-0, +1, m]
const char *luaL_gsub (lua_State *L,
const char *s,
const char *p,
const char *r);
Creates a copy of string s
by replacing any occurrence of the string p
with the string r
. Pushes the resulting string on the stack and returns it.