Skip to content

Commit

Permalink
open
Browse files Browse the repository at this point in the history
  • Loading branch information
crazytuzi committed Aug 15, 2020
1 parent 1eaf866 commit 79dd5be
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
19 changes: 15 additions & 4 deletions lbaselib.c
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,9 @@ static int luaB_tostring (lua_State *L) {
}


/*
** 基础库的数组配置,主要定义函数名称和对应方法
*/
static const luaL_Reg base_funcs[] = {
{"assert", luaB_assert},
{"collectgarbage", luaB_collectgarbage},
Expand Down Expand Up @@ -484,16 +487,24 @@ static const luaL_Reg base_funcs[] = {
};


/*
** 基础库的的启动函数,主要有三步:
** 从全局注册表中获取全局环境变量数组LUA_RIDX_GLOBALS,
** 并通过luaL_setfuncs方法将基础库的函数逐个塞进全局环境变量LUA_RIDX_GLOBALS[name] = func
** lua_pushvalue拷贝全局环境变量数组LUA_RIDX_GLOBALS,然后LUA_RIDX_GLOBALS["_G"] = LUA_RIDX_GLOBALS,并将拷贝的数组pop弹出栈顶
** lua_pushliteral在栈顶设置一个字符串常量,用于存放版本信息,
** 并设置LUA_RIDX_GLOBALS["_VERSION"] = LUA_VERSION,然后将栈顶的版本信息pop弹出栈顶
*/
LUAMOD_API int luaopen_base (lua_State *L) {
/* open lib into global table */
lua_pushglobaltable(L);
luaL_setfuncs(L, base_funcs, 0);
lua_pushglobaltable(L); /* 打开全局环境变量数组LUA_RIDX_GLOBALS,放置到栈顶 */
luaL_setfuncs(L, base_funcs, 0); /* 将base_funcs中的函数,逐个设置到LUA_RIDX_GLOBALS数组上 */
/* set global _G */
lua_pushvalue(L, -1);
lua_setfield(L, -2, "_G");
lua_setfield(L, -2, "_G"); /* LUA_RIDX_GLOBALS["_G"] = LUA_RIDX_GLOBALS */
/* set global _VERSION */
lua_pushliteral(L, LUA_VERSION);
lua_setfield(L, -2, "_VERSION");
lua_setfield(L, -2, "_VERSION"); /* LUA_RIDX_GLOBALS["_VERSION"] = LUA_VERSION */
return 1;
}

18 changes: 16 additions & 2 deletions linit.c
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@
#include "lualib.h"
#include "lauxlib.h"

/*
** 扩展库实现重点需要分三个部分:
** 函数配置数组:主要定义了函数名称和对应的C语言函数,
** 数组最后一个对象为{NULL,NULL},因为数组遍历的时候会根据NULL做判断进行跳出
** 扩展库加载方法:入参为L,对当前的线程栈,方法内容必须实现luaL_newlib,
** 该函数主要将配置数组中的方法,遍历注册到一个module[funcname] = func 数组上,
** 该mudule数组,作为加载方法openf的结果放入栈上
** 函数实现:每个函数的入参都为lua_State* L,为当前线程栈
**
** 为啥每个函数入参都为L,那么在Lua中调用的时候如何进行多个参数入参?
** 实际上,Lua语言还会解析语法本身,对于多个参数入参,也都会通过lua_push*方法,放入栈上,
** 所以当调用函数的时候,往栈上取参即可
*/


/*
** these libs are loaded by lua.c and are readily available to any Lua
Expand All @@ -43,7 +57,7 @@
** 定义标准库名称和启动方法
*/
static const luaL_Reg loadedlibs[] = {
{"_G", luaopen_base},
{"_G", luaopen_base}, /* 全局基础方法聚合,常见的loadfile等函数都在这上面配置,在lua语言中,直接使用函数即可,无需使用库名字.方法名称方式 */
{LUA_LOADLIBNAME, luaopen_package},
{LUA_COLIBNAME, luaopen_coroutine},
{LUA_TABLIBNAME, luaopen_table},
Expand All @@ -56,7 +70,7 @@ static const luaL_Reg loadedlibs[] = {
#if defined(LUA_COMPAT_BITLIB)
{LUA_BITLIBNAME, luaopen_bit32},
#endif
{NULL, NULL}
{NULL, NULL} /* 主要用于在循环的时候遍历退出 */
};


Expand Down

0 comments on commit 79dd5be

Please sign in to comment.