| 1 |
/*=========================================================================*\ |
| 2 |
* Unix domain socket |
| 3 |
* LuaSocket toolkit |
| 4 |
\*=========================================================================*/ |
| 5 |
#include "lua.h" |
| 6 |
#include "lauxlib.h" |
| 7 |
|
| 8 |
#include "unixstream.h" |
| 9 |
#include "unixdgram.h" |
| 10 |
|
| 11 |
/*-------------------------------------------------------------------------*\ |
| 12 |
* Modules and functions |
| 13 |
\*-------------------------------------------------------------------------*/ |
| 14 |
static const luaL_Reg mod[] = { |
| 15 |
{"stream", unixstream_open}, |
| 16 |
{"dgram", unixdgram_open}, |
| 17 |
{NULL, NULL} |
| 18 |
}; |
| 19 |
|
| 20 |
static void add_alias(lua_State *L, int index, const char *name, const char *target) |
| 21 |
{ |
| 22 |
lua_getfield(L, index, target); |
| 23 |
lua_setfield(L, index, name); |
| 24 |
} |
| 25 |
|
| 26 |
static int compat_socket_unix_call(lua_State *L) |
| 27 |
{ |
| 28 |
/* Look up socket.unix.stream in the socket.unix table (which is the first |
| 29 |
* argument). */ |
| 30 |
lua_getfield(L, 1, "stream"); |
| 31 |
|
| 32 |
/* Replace the stack entry for the socket.unix table with the |
| 33 |
* socket.unix.stream function. */ |
| 34 |
lua_replace(L, 1); |
| 35 |
|
| 36 |
/* Call socket.unix.stream, passing along any arguments. */ |
| 37 |
int n = lua_gettop(L); |
| 38 |
lua_call(L, n-1, LUA_MULTRET); |
| 39 |
|
| 40 |
/* Pass along the return values from socket.unix.stream. */ |
| 41 |
n = lua_gettop(L); |
| 42 |
return n; |
| 43 |
} |
| 44 |
|
| 45 |
/*-------------------------------------------------------------------------*\ |
| 46 |
* Initializes module |
| 47 |
\*-------------------------------------------------------------------------*/ |
| 48 |
int luaopen_socket_unix(lua_State *L) |
| 49 |
{ |
| 50 |
int i; |
| 51 |
lua_newtable(L); |
| 52 |
int socket_unix_table = lua_gettop(L); |
| 53 |
|
| 54 |
for (i = 0; mod[i].name; i++) |
| 55 |
mod[i].func(L); |
| 56 |
|
| 57 |
/* Add backwards compatibility aliases "tcp" and "udp" for the "stream" and |
| 58 |
* "dgram" functions. */ |
| 59 |
add_alias(L, socket_unix_table, "tcp", "stream"); |
| 60 |
add_alias(L, socket_unix_table, "udp", "dgram"); |
| 61 |
|
| 62 |
/* Add a backwards compatibility function and a metatable setup to call it |
| 63 |
* for the old socket.unix() interface. */ |
| 64 |
lua_pushcfunction(L, compat_socket_unix_call); |
| 65 |
lua_setfield(L, socket_unix_table, "__call"); |
| 66 |
lua_pushvalue(L, socket_unix_table); |
| 67 |
lua_setmetatable(L, socket_unix_table); |
| 68 |
|
| 69 |
return 1; |
| 70 |
} |