luasocket中socket.lua文件中
local socket = require("socket.core") // socket.core?
luasocket中luasocket.c文件中
/*-------------------------------------------------------------------------*\
* Initializes all library modules.
\*-------------------------------------------------------------------------*/
LUASOCKET_API int luaopen_socket_core(lua_State *L) {
int i;
base_open(L);
for (i = 0; mod[i].name; i++) mod[i].func(L);
return 1;
}
base_open(lua_State *L)的函数源码如下:
static int base_open(lua_State *L) {
if (socket_open()) {
/* export functions (and leave namespace table on top of stack) */
luaL_openlib(L, "socket", func, 0);
#ifdef LUASOCKET_DEBUG
lua_pushstring(L, "_DEBUG");
lua_pushboolean(L, 1);
lua_rawset(L, -3);
#endif
/* make version string available to scripts */
lua_pushstring(L, "_VERSION");
lua_pushstring(L, LUASOCKET_VERSION);
lua_rawset(L, -3);
return 1;
} else {
lua_pushstring(L, "unable to initialize library");
lua_error(L);
return 0;
}
}
其中,需要注意的是luaL_openlib函数的功能(ps:注意,不是luaL_openlibs函数,在lua官网上面可能找不到该函数的API解释.)
这样就调用到了C层面的socket的方法,socket的c实现在C_library下面
另外,lua官网有文档说明,如何注册C库.详细的文档请去参考:http://www.lua.org/pil/26.2.html
1 When you extend Lua with C functions, it is a good idea to design your code as a C library, even when you want to register only one C function: Sooner or later (usually sooner) you will need other functions. As usual, the auxiliary library offers a helper function for this job. The luaL_openlib function receives a list of C functions and their respective names and registers all of them inside a table with the library name.
现在已经弄明白在使用C扩展lua的时候,应该将我们的代码设计成为C库.
另外,我这里有一个简单的实例程序:
1 #include2 #include "./src/lua.h" 3 #include "./src/lualib.h" 4 #include "./src/lauxlib.h" 5 6 static int add(lua_State *L) 7 { 8 int a,b,c; 9 a = lua_tonumber(L,1); 10 b = lua_tonumber(L,2); 11 c = a+b; 12 lua_pushnumber(L,c); 13 printf("test hello!!!\r\n"); 14 return 1; 15 } 16 static const struct luaL_Reg lib[] = 17 { 18 {"testadd",add}, 19 {NULL,NULL} 20 }; 21 int luaopen_testlib_core(lua_State *L) // 注意这里的函数写法 22 { 23 //luaL_register(L,"testlib",lib); // 1 24 luaL_openlib(L,"testlib",lib,0); // 2 25 return 1; 26 } 27 28 ~
下面给出一个lua脚本:
1 #!/usr/bin/env lua 2 require("testlib.core") // 注意这里的调用,和上面的函数写法是相关联的 3 c = testlib.testadd(15,25) 4 print("The result is ",c); 5 ~
到这里就很明白了,如果我在上面的C源码中使用的是luaopen_testlib(lua_State *L),那么在下面的lua脚本中直接require("testlib")就可以了.
但是如果是像我上面的这种命名方式,那么就需要像我这么做.而luasocket中出现的require("socket.core"),就是这么出现的.