+static int nixio_open_flags(lua_State *L) {
+ int mode = 0;
+ const int j = lua_gettop(L);
+ for (int i=1; i<=j; i++) {
+ const char *flag = luaL_checkstring(L, i);
+ if (!strcmp(flag, "append")) {
+ mode |= O_APPEND;
+ } else if (!strcmp(flag, "creat")) {
+ mode |= O_CREAT;
+ } else if (!strcmp(flag, "excl")) {
+ mode |= O_EXCL;
+ } else if (!strcmp(flag, "nonblock") || !strcmp(flag, "ndelay")) {
+ mode |= O_NONBLOCK;
+ } else if (!strcmp(flag, "sync")) {
+ mode |= O_SYNC;
+ } else if (!strcmp(flag, "trunc")) {
+ mode |= O_TRUNC;
+ } else if (!strcmp(flag, "rdonly")) {
+ mode |= O_RDONLY;
+ } else if (!strcmp(flag, "wronly")) {
+ mode |= O_WRONLY;
+ } else if (!strcmp(flag, "rdwr")) {
+ mode |= O_RDWR;
+ } else {
+ return luaL_argerror(L, i, "supported values: append, creat, "
+ "excl, nonblock, ndelay, sync, trunc");
+ }
+ }
+ lua_pushinteger(L, mode);
+ return 1;
+}
+
+static int nixio_dup(lua_State *L) {
+ int oldfd = nixio__checkfd(L, 1);
+ int newfd = (lua_gettop(L) > 1) ? nixio__checkfd(L, 2) : -1;
+ int stat = (newfd == -1) ? dup(oldfd) : dup2(oldfd, newfd);
+
+ if (stat == -1) {
+ return nixio__perror(L);
+ } else {
+ int *udata = lua_newuserdata(L, sizeof(int));
+ if (!udata) {
+ return luaL_error(L, "out of memory");
+ }
+
+ *udata = stat;
+ luaL_getmetatable(L, NIXIO_FILE_META);
+ lua_setmetatable(L, -2);
+ return 1;
+ }
+}
+