2 * nixio - Linux I/O library for lua
4 * Copyright (C) 2009 Steven Barth <steven@midlink.org>
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
30 /* pushes nil, error number and errstring on the stack */
31 int nixio__perror(lua_State
*L
) {
33 lua_pushinteger(L
, errno
);
34 lua_pushstring(L
, strerror(errno
));
38 /* pushes true, if operation succeeded, otherwise call nixio__perror */
39 int nixio__pstatus(lua_State
*L
, int condition
) {
41 lua_pushboolean(L
, 1);
44 return nixio__perror(L
);
48 /* checks whether the first argument is a socket and returns it */
49 nixio_sock
* nixio__checksock(lua_State
*L
) {
50 nixio_sock
*sock
= (nixio_sock
*)luaL_checkudata(L
, 1, NIXIO_META
);
51 luaL_argcheck(L
, sock
->fd
!= -1, 1, "invalid socket object");
55 /* read fd from nixio_sock object */
56 int nixio__checksockfd(lua_State
*L
) {
57 return nixio__checksock(L
)->fd
;
60 /* return any possible fd, otherwise error out */
61 int nixio__checkfd(lua_State
*L
, int ud
) {
62 int fd
= nixio__tofd(L
, ud
);
63 return (fd
!= -1) ? fd
: luaL_argerror(L
, ud
, "invalid file descriptor");
66 /* return any possible fd */
67 int nixio__tofd(lua_State
*L
, int ud
) {
68 void *udata
= lua_touserdata(L
, ud
);
70 if (udata
&& lua_getmetatable(L
, ud
)) {
71 luaL_getmetatable(L
, NIXIO_META
);
72 luaL_getmetatable(L
, LUA_FILEHANDLE
);
73 if (lua_rawequal(L
, -2, -3)) {
74 fd
= ((nixio_sock
*)udata
)->fd
;
75 } else if (lua_rawequal(L
, -1, -3)) {
76 fd
= fileno(*((FILE **)udata
));
84 static const luaL_reg R
[] = {
89 LUALIB_API
int luaopen_nixio(lua_State
*L
) {
90 /* create metatable */
91 luaL_newmetatable(L
, NIXIO_META
);
97 /* metatable.__index = M */
98 lua_setfield(L
, -3, "__index");
101 /* register module */
102 luaL_register(L
, "nixio", R
);
104 /* register methods */
105 nixio_open_socket(L
);
106 nixio_open_sockopt(L
);
108 nixio_open_address(L
);
113 lua_pushnumber(L
, VERSION
);
114 lua_setfield(L
, -2, "version");
116 /* remove meta table */