diff options
author | Natanael Copa <ncopa@alpinelinux.org> | 2011-11-24 15:59:52 +0100 |
---|---|---|
committer | Natanael Copa <ncopa@alpinelinux.org> | 2011-11-24 15:59:52 +0100 |
commit | eb202135397e457baa58423faec4d8d0441c2292 (patch) | |
tree | b918852eeb27e53f5b928c2bde3ef37b9d0a2e89 | |
parent | 19c58fff82a1c8e7f10b4ccc09711594d594e4a7 (diff) | |
download | libuniso-eb202135397e457baa58423faec4d8d0441c2292.tar.bz2 libuniso-eb202135397e457baa58423faec4d8d0441c2292.tar.xz |
lua: accept both file descriptor or filename as parameter
-rw-r--r-- | README | 8 | ||||
-rw-r--r-- | lua-uniso.c | 26 |
2 files changed, 32 insertions, 2 deletions
@@ -18,4 +18,12 @@ To install: make install +Example how to use Lua module: + +require("uniso") + +-- Use 0 for stdin +print(uniso.uniso(arg[1] or 0, function(current, total, filename) + print(current, total, filename) +end)) diff --git a/lua-uniso.c b/lua-uniso.c index 97a1e8c..ec1cb91 100644 --- a/lua-uniso.c +++ b/lua-uniso.c @@ -1,4 +1,9 @@ +#include <fcntl.h> +#include <errno.h> +#include <string.h> +#include <unistd.h> + #include <lua.h> #include <lualib.h> #include <lauxlib.h> @@ -33,9 +38,23 @@ static void l_callback(size_t current, size_t total, const char *filename, static int l_uniso(lua_State *L) { - int fd = luaL_checkinteger(L, 1); - int result; + int fd, result; struct l_uniso_context ctx; + const char *filename = NULL; + + if (lua_isnumber(L, 1)) { + fd =luaL_checkinteger(L, 1); + } else if (lua_isstring(L, 1)) { + filename = luaL_checkstring(L, 1); + fd = open(filename, O_RDONLY); + if (fd < 0) { + lua_pushnil(L); + lua_pushstring(L, strerror(errno)); + return 2; + } + } else { + luaL_typerror(L, 1, "integer or string"); + } if (!lua_isnil(L, 2)) luaL_checktype(L, 2, LUA_TFUNCTION); @@ -43,6 +62,9 @@ static int l_uniso(lua_State *L) ctx.L = L; result = uniso(fd, &l_callback, &ctx); + if (filename != NULL) + close(fd); + lua_pushinteger(L, result); return 1; } |