1
0

unix.c 2.1 KB

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