unix.c 2.1 KB

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