File: unix.c

package info (click to toggle)
luasocket 3.0~rc1+git+ac3201d-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 2,216 kB
  • sloc: ansic: 4,487; makefile: 320; sh: 116
file content (70 lines) | stat: -rw-r--r-- 2,153 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*=========================================================================*\
* Unix domain socket
* LuaSocket toolkit
\*=========================================================================*/
#include "lua.h"
#include "lauxlib.h"

#include "unixtcp.h"
#include "unixudp.h"

/*-------------------------------------------------------------------------*\
* Modules and functions
\*-------------------------------------------------------------------------*/
static const luaL_Reg mod[] = {
    {"tcp", unixtcp_open},
    {"udp", unixudp_open},
    {NULL, NULL}
};

static void add_alias(lua_State *L, int index, const char *name, const char *target)
{
    lua_getfield(L, index, target);
    lua_setfield(L, index, name);
}

static int compat_socket_unix_call(lua_State *L)
{
    /* Look up socket.unix.tcp in the socket.unix table (which is the first
     * argument). */
    lua_getfield(L, 1, "tcp");

    /* Replace the stack entry for the socket.unix table with the
     * socket.unix.tcp function. */
    lua_replace(L, 1);

    /* Call socket.unix.tcp, passing along any arguments. */
    int n = lua_gettop(L);
    lua_call(L, n-1, LUA_MULTRET);

    /* Pass along the return values from socket.unix.tcp. */
    n = lua_gettop(L);
    return n;
}

/*-------------------------------------------------------------------------*\
* Initializes module
\*-------------------------------------------------------------------------*/
int luaopen_socket_unix(lua_State *L)
{
    int i;
    lua_newtable(L);
    int socket_unix_table = lua_gettop(L);

    for (i = 0; mod[i].name; i++)
        mod[i].func(L);

    /* Add forward compatibility aliases "stream" and "dgram" for the "tcp" and
     * "udp" functions. */
    add_alias(L, socket_unix_table, "stream", "tcp");
    add_alias(L, socket_unix_table, "dgram", "udp");

    /* Add a backwards compatibility function and a metatable setup to call it
     * for the old socket.unix() interface. */
    lua_pushcfunction(L, compat_socket_unix_call);
    lua_setfield(L, socket_unix_table, "__call");
    lua_pushvalue(L, socket_unix_table);
    lua_setmetatable(L, socket_unix_table);

    return 1;
}