pax_global_header00006660000000000000000000000064124706065440014522gustar00rootroot0000000000000052 comment=10c7d40943601eb1f80caa9e909688bb203edc4d lua-bit32-5.3.0/000077500000000000000000000000001247060654400132315ustar00rootroot00000000000000lua-bit32-5.3.0/LICENSE000066400000000000000000000020721247060654400142370ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2013 Hisham Muhammad Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. lua-bit32-5.3.0/README.md000066400000000000000000000122511247060654400145110ustar00rootroot00000000000000# lua-compat-5.2 Lua-5.2-style APIs for Lua 5.1. ## What is it This is a small module that aims to make it easier to write code in a Lua-5.2-style that is compatible with both Lua 5.1 and Lua 5.2. This does *not* make Lua 5.1 entirely compatible with Lua 5.2, but it brings the API closer to that of Lua 5.2. It includes: * _For writing Lua_: Lua modules, `compat52` and `compat52.strict`, which can be require'd from Lua scripts and run in both Lua 5.1 and 5.2, plus a backport of `bit32` straight from the Lua 5.2 sources, adapted to build as a Lua 5.1 module. * _For writing C_: A C header and file which can be linked to your Lua module written in C, providing some functions from the C API of Lua 5.2 that do not exist in Lua 5.1, making it easier to write C code that compiles with both versions of liblua. ## How to use it ### Lua module ```lua require("compat52") ``` You have to launch it like this (instead of the usual idiom of storing the return of `require` in a local variable) because compat52 needs to make changes to your global environment. When run under Lua 5.2, this module does nothing. When run under Lua 5.1, it replaces some of your standard functions and adds new ones to bring your environment closer to that of Lua 5.2. You may also use the "strict mode" which removes from Lua 5.1 functions that were deprecated in 5.2; that is the equivalent of running Lua 5.2 with the LUA_COMPAT_ALL flag disabled: ```lua require("compat52.strict") ``` The "strict mode" changes the global environment, so it affects all loaded modules and chunks. If this is undesirable, you can use the "modular strict mode" which only replaces the environment of the current file. The usage is slightly different (you have to call the return value of `require`): ```lua require("compat52.mstrict")() ``` The effects of `compat52` are still in effect for all chunks, though. ### C code Add the files `compat-5.2.c` and `compat-5.2.h` to your project and link it with the rest of your code as usual. ## What's implemented ### Lua * `load` and `loadfile` * `table.pack` and `table.unpack` * `string` patterns may contain embedded zeros * `string.rep` accepts sep argument * `string.format` calls `tostring` on arguments for `%s` * `math.log` accepts base argument * `xpcall` takes additional arguments * `pcall` and `xpcall` can execute functions that yield * metamethods for `pairs` and `ipairs` * `rawlen` (but `#` still doesn't respect `__len` for tables) * `collectgarbage` * `package.searchers` * `package.searchpath` * `coroutine` functions dealing with the main coroutine * `coroutine.create` accepts functions written in C * return code of `os.execute` * `io.write` and `file:write` return file handle * `io.lines` and `file:lines` accept format arguments (like `io.read`) * `bit32` (actual backport from the `bit32` library from Lua 5.2, also available as a stand-alone rock in the LuaRocks repository) * `debug.setmetatable` returns object * `debug.getuservalue` and `debug.setuservalue` * optional strict mode which removes functions removed or deprecated in Lua 5.2, such as `setfenv` and `getfenv` ### C * `luaL_Reg` (for Lua 5.0) * `luaL_Unsigned` * `LUA_FILEHANDLE` (via `lualib.h`) and `luaL_Stream` * `luaL_addchar` (for Lua 5.0) * `lua_absindex` * `lua_arith` * `lua_compare` * `lua_tonumberx` and `lua_tointegerx` * `lua_tounsignedx` and `lua_tounsigned` * `luaL_checkunsigned` and `luaL_optunsigned` * `lua_len`, `lua_rawlen`, and `luaL_len` * `lua_rawgetp` and `lua_rawsetp` * `lua_copy` * `lua_getuservalue` and `lua_setuservalue` * `lua_pushglobaltable` * `lua_pushunsigned` * `luaL_testudata` * `luaL_setfuncs` and `luaL_newlib` * `luaL_setmetatable` * `luaL_getsubtable` * `luaL_traceback` * `luaL_fileresult` * `luaL_checkversion` (with empty body, only to avoid compile errors) * `luaL_tolstring` * `luaL_requiref` * `luaL_buffinitsize`, `luaL_prepbuffsize`, and `luaL_pushresultsize` ## What's not implemented * `_ENV` * obviously, this does not turn Lua 5.1 into Lua 5.2: syntactic changes to the core language, such as the `goto` statement, and semantic changes such as ephemeron support for weak tables, remain unavailable. * `"*L"` format flag for `io.read`, `io.lines`, `file:read`, `file:lines` * second argument for `os.exit` * return values of `pipe:close` if `pipe` has been opened by `io.popen` * `"*"` as second argument for `package.loadlib` * some functions in the debug library * anything else missing in the Lua libraries? ## See also * For more information about compatibility between Lua versions, see [Compatibility With Lua Five](http://lua-users.org/wiki/CompatibilityWithLuaFive) at the Lua-Users wiki * For Lua-5.1-style APIs under Lua 5.0, see [Compat-5.1](http://keplerproject.org/compat/) * for C support in the opposite direction (ie, loading C code using Lua-5.1-style APIs under Lua 5.2), see [Twoface](http://corsix.github.io/twoface/) ## Credits This package contains code written by: * [The Lua Team](http://www.lua.org) * Philipp Janda ([@siffiejoe](http://github.com/siffiejoe)) * Tomás Guisasola Gorham ([@tomasguisasola](http://github.com/tomasguisasola)) * Hisham Muhammad ([@hishamhm](http://github.com/hishamhm)) * Renato Maia ([@renatomaia](http://github.com/renatomaia)) lua-bit32-5.3.0/bit32-scm-1.rockspec000066400000000000000000000012031247060654400166210ustar00rootroot00000000000000package = "bit32" version = "scm-1" source = { url = "git://github.com/keplerproject/lua-compat-5.2.git", branch = "master", } description = { summary = "Lua 5.2 bit manipulation library", detailed = [[ bit32 is the native Lua 5.2 bit manipulation library, in the version from Lua 5.3; it is compatible with Lua 5.1, 5.2 and 5.3. ]], license = "MIT/X11", homepage = "http://www.lua.org/manual/5.2/manual.html#6.7", } dependencies = { "lua >= 5.1, <= 5.3" } build = { type = "builtin", modules = { bit32 = { sources = { "lbitlib.c" }, incdirs = { "c-api" }, } } } lua-bit32-5.3.0/c-api/000077500000000000000000000000001247060654400142225ustar00rootroot00000000000000lua-bit32-5.3.0/c-api/compat-5.2.c000066400000000000000000000463501247060654400161630ustar00rootroot00000000000000#include #include #include "lua.h" #include "lauxlib.h" #include "compat-5.2.h" #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM == 501 int lua_absindex (lua_State *L, int i) { if (i < 0 && i > LUA_REGISTRYINDEX) i += lua_gettop(L) + 1; return i; } void lua_copy (lua_State *L, int from, int to) { int abs_to = lua_absindex(L, to); luaL_checkstack(L, 1, "not enough stack slots"); lua_pushvalue(L, from); lua_replace(L, abs_to); } void lua_rawgetp (lua_State *L, int i, const void *p) { int abs_i = lua_absindex(L, i); lua_pushlightuserdata(L, (void*)p); lua_rawget(L, abs_i); } void lua_rawsetp (lua_State *L, int i, const void *p) { int abs_i = lua_absindex(L, i); luaL_checkstack(L, 1, "not enough stack slots"); lua_pushlightuserdata(L, (void*)p); lua_insert(L, -2); lua_rawset(L, abs_i); } void *luaL_testudata (lua_State *L, int i, const char *tname) { void *p = lua_touserdata(L, i); luaL_checkstack(L, 2, "not enough stack slots"); if (p == NULL || !lua_getmetatable(L, i)) return NULL; else { int res = 0; luaL_getmetatable(L, tname); res = lua_rawequal(L, -1, -2); lua_pop(L, 2); if (!res) p = NULL; } return p; } lua_Number lua_tonumberx (lua_State *L, int i, int *isnum) { lua_Number n = lua_tonumber(L, i); if (isnum != NULL) { *isnum = (n != 0 || lua_isnumber(L, i)); } return n; } #define PACKAGE_KEY "_COMPAT52_PACKAGE" static void push_package_table (lua_State *L) { lua_pushliteral(L, PACKAGE_KEY); lua_rawget(L, LUA_REGISTRYINDEX); if (!lua_istable(L, -1)) { lua_pop(L, 1); /* try to get package table from globals */ lua_pushliteral(L, "package"); lua_rawget(L, LUA_GLOBALSINDEX); if (lua_istable(L, -1)) { lua_pushliteral(L, PACKAGE_KEY); lua_pushvalue(L, -2); lua_rawset(L, LUA_REGISTRYINDEX); } } } void lua_getuservalue (lua_State *L, int i) { luaL_checktype(L, i, LUA_TUSERDATA); luaL_checkstack(L, 2, "not enough stack slots"); lua_getfenv(L, i); lua_pushvalue(L, LUA_GLOBALSINDEX); if (lua_rawequal(L, -1, -2)) { lua_pop(L, 1); lua_pushnil(L); lua_replace(L, -2); } else { lua_pop(L, 1); push_package_table(L); if (lua_rawequal(L, -1, -2)) { lua_pop(L, 1); lua_pushnil(L); lua_replace(L, -2); } else lua_pop(L, 1); } } void lua_setuservalue (lua_State *L, int i) { luaL_checktype(L, i, LUA_TUSERDATA); if (lua_isnil(L, -1)) { luaL_checkstack(L, 1, "not enough stack slots"); lua_pushvalue(L, LUA_GLOBALSINDEX); lua_replace(L, -2); } lua_setfenv(L, i); } /* ** Adapted from Lua 5.2.0 */ void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) { luaL_checkstack(L, nup+1, "too many upvalues"); for (; l->name != NULL; l++) { /* fill the table with given functions */ int i; lua_pushstring(L, l->name); for (i = 0; i < nup; i++) /* copy upvalues to the top */ lua_pushvalue(L, -(nup + 1)); lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */ lua_settable(L, -(nup + 3)); /* table must be below the upvalues, the name and the closure */ } lua_pop(L, nup); /* remove upvalues */ } void luaL_setmetatable (lua_State *L, const char *tname) { luaL_checkstack(L, 1, "not enough stack slots"); luaL_getmetatable(L, tname); lua_setmetatable(L, -2); } int luaL_getsubtable (lua_State *L, int i, const char *name) { int abs_i = lua_absindex(L, i); luaL_checkstack(L, 3, "not enough stack slots"); lua_pushstring(L, name); lua_gettable(L, abs_i); if (lua_istable(L, -1)) return 1; lua_pop(L, 1); lua_newtable(L); lua_pushstring(L, name); lua_pushvalue(L, -2); lua_settable(L, abs_i); return 0; } #if !defined(COMPAT52_IS_LUAJIT) static int countlevels (lua_State *L) { lua_Debug ar; int li = 1, le = 1; /* find an upper bound */ while (lua_getstack(L, le, &ar)) { li = le; le *= 2; } /* do a binary search */ while (li < le) { int m = (li + le)/2; if (lua_getstack(L, m, &ar)) li = m + 1; else le = m; } return le - 1; } static int findfield (lua_State *L, int objidx, int level) { if (level == 0 || !lua_istable(L, -1)) return 0; /* not found */ lua_pushnil(L); /* start 'next' loop */ while (lua_next(L, -2)) { /* for each pair in table */ if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */ if (lua_rawequal(L, objidx, -1)) { /* found object? */ lua_pop(L, 1); /* remove value (but keep name) */ return 1; } else if (findfield(L, objidx, level - 1)) { /* try recursively */ lua_remove(L, -2); /* remove table (but keep name) */ lua_pushliteral(L, "."); lua_insert(L, -2); /* place '.' between the two names */ lua_concat(L, 3); return 1; } } lua_pop(L, 1); /* remove value */ } return 0; /* not found */ } static int pushglobalfuncname (lua_State *L, lua_Debug *ar) { int top = lua_gettop(L); lua_getinfo(L, "f", ar); /* push function */ lua_pushvalue(L, LUA_GLOBALSINDEX); if (findfield(L, top + 1, 2)) { lua_copy(L, -1, top + 1); /* move name to proper place */ lua_pop(L, 2); /* remove pushed values */ return 1; } else { lua_settop(L, top); /* remove function and global table */ return 0; } } static void pushfuncname (lua_State *L, lua_Debug *ar) { if (*ar->namewhat != '\0') /* is there a name? */ lua_pushfstring(L, "function " LUA_QS, ar->name); else if (*ar->what == 'm') /* main? */ lua_pushliteral(L, "main chunk"); else if (*ar->what == 'C') { if (pushglobalfuncname(L, ar)) { lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1)); lua_remove(L, -2); /* remove name */ } else lua_pushliteral(L, "?"); } else lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined); } #define LEVELS1 12 /* size of the first part of the stack */ #define LEVELS2 10 /* size of the second part of the stack */ void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, int level) { lua_Debug ar; int top = lua_gettop(L); int numlevels = countlevels(L1); int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0; if (msg) lua_pushfstring(L, "%s\n", msg); lua_pushliteral(L, "stack traceback:"); while (lua_getstack(L1, level++, &ar)) { if (level == mark) { /* too many levels? */ lua_pushliteral(L, "\n\t..."); /* add a '...' */ level = numlevels - LEVELS2; /* and skip to last ones */ } else { lua_getinfo(L1, "Slnt", &ar); lua_pushfstring(L, "\n\t%s:", ar.short_src); if (ar.currentline > 0) lua_pushfstring(L, "%d:", ar.currentline); lua_pushliteral(L, " in "); pushfuncname(L, &ar); lua_concat(L, lua_gettop(L) - top); } } lua_concat(L, lua_gettop(L) - top); } #endif void luaL_checkversion (lua_State *L) { (void)L; } #if !defined(COMPAT52_IS_LUAJIT) int luaL_fileresult (lua_State *L, int stat, const char *fname) { int en = errno; /* calls to Lua API may change this value */ if (stat) { lua_pushboolean(L, 1); return 1; } else { lua_pushnil(L); if (fname) lua_pushfstring(L, "%s: %s", fname, strerror(en)); else lua_pushstring(L, strerror(en)); lua_pushnumber(L, (lua_Number)en); return 3; } } #endif #endif /* Lua 5.0 or Lua 5.1 */ #if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM == 501 #include typedef LUAI_INT32 LUA_INT32; /********************************************************************/ /* extract of 5.2's luaconf.h */ /* detects proper defines for faster unsigned<->number conversion */ /* see copyright notice at the end of this file */ /********************************************************************/ #if !defined(LUA_ANSI) && defined(_WIN32) && !defined(_WIN32_WCE) #define LUA_WIN /* enable goodies for regular Windows platforms */ #endif #if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) /* { */ /* Microsoft compiler on a Pentium (32 bit) ? */ #if defined(LUA_WIN) && defined(_MSC_VER) && defined(_M_IX86) /* { */ #define LUA_MSASMTRICK #define LUA_IEEEENDIAN 0 #define LUA_NANTRICK /* pentium 32 bits? */ #elif defined(__i386__) || defined(__i386) || defined(__X86__) /* }{ */ #define LUA_IEEE754TRICK #define LUA_IEEELL #define LUA_IEEEENDIAN 0 #define LUA_NANTRICK /* pentium 64 bits? */ #elif defined(__x86_64) /* }{ */ #define LUA_IEEE754TRICK #define LUA_IEEEENDIAN 0 #elif defined(__POWERPC__) || defined(__ppc__) /* }{ */ #define LUA_IEEE754TRICK #define LUA_IEEEENDIAN 1 #else /* }{ */ /* assume IEEE754 and a 32-bit integer type */ #define LUA_IEEE754TRICK #endif /* } */ #endif /* } */ /********************************************************************/ /* extract of 5.2's llimits.h */ /* gives us lua_number2unsigned and lua_unsigned2number */ /* see copyright notice at the end of this file */ /********************************************************************/ #if defined(MS_ASMTRICK) || defined(LUA_MSASMTRICK) /* { */ /* trick with Microsoft assembler for X86 */ #define lua_number2unsigned(i,n) \ {__int64 l; __asm {__asm fld n __asm fistp l} i = (unsigned int)l;} #elif defined(LUA_IEEE754TRICK) /* }{ */ /* the next trick should work on any machine using IEEE754 with a 32-bit int type */ union compat52_luai_Cast { double l_d; LUA_INT32 l_p[2]; }; #if !defined(LUA_IEEEENDIAN) /* { */ #define LUAI_EXTRAIEEE \ static const union compat52_luai_Cast ieeeendian = {-(33.0 + 6755399441055744.0)}; #define LUA_IEEEENDIANLOC (ieeeendian.l_p[1] == 33) #else #define LUA_IEEEENDIANLOC LUA_IEEEENDIAN #define LUAI_EXTRAIEEE /* empty */ #endif /* } */ #define lua_number2int32(i,n,t) \ { LUAI_EXTRAIEEE \ volatile union compat52_luai_Cast u; u.l_d = (n) + 6755399441055744.0; \ (i) = (t)u.l_p[LUA_IEEEENDIANLOC]; } #define lua_number2unsigned(i,n) lua_number2int32(i, n, lua_Unsigned) #endif /* } */ /* the following definitions always work, but may be slow */ #if !defined(lua_number2unsigned) /* { */ /* the following definition assures proper modulo behavior */ #if defined(LUA_NUMBER_DOUBLE) || defined(LUA_NUMBER_FLOAT) #include #define SUPUNSIGNED ((lua_Number)(~(lua_Unsigned)0) + 1) #define lua_number2unsigned(i,n) \ ((i)=(lua_Unsigned)((n) - floor((n)/SUPUNSIGNED)*SUPUNSIGNED)) #else #define lua_number2unsigned(i,n) ((i)=(lua_Unsigned)(n)) #endif #endif /* } */ #if !defined(lua_unsigned2number) /* on several machines, coercion from unsigned to double is slow, so it may be worth to avoid */ #define lua_unsigned2number(u) \ (((u) <= (lua_Unsigned)INT_MAX) ? (lua_Number)(int)(u) : (lua_Number)(u)) #endif /********************************************************************/ static void compat52_call_lua (lua_State *L, char const code[], size_t len, int nargs, int nret) { lua_rawgetp(L, LUA_REGISTRYINDEX, (void*)code); if (lua_type(L, -1) != LUA_TFUNCTION) { lua_pop(L, 1); if (luaL_loadbuffer(L, code, len, "=none")) lua_error(L); lua_pushvalue(L, -1); lua_rawsetp(L, LUA_REGISTRYINDEX, (void*)code); } lua_insert(L, -nargs-1); lua_call(L, nargs, nret); } static const char compat52_arith_code[] = { 'l', 'o', 'c', 'a', 'l', ' ', 'o', 'p', ',', 'a', ',', 'b', '=', '.', '.', '.', '\n', 'i', 'f', ' ', 'o', 'p', '=', '=', '0', ' ', 't', 'h', 'e', 'n', '\n', 'r', 'e', 't', 'u', 'r', 'n', ' ', 'a', '+', 'b', '\n', 'e', 'l', 's', 'e', 'i', 'f', ' ', 'o', 'p', '=', '=', '1', ' ', 't', 'h', 'e', 'n', '\n', 'r', 'e', 't', 'u', 'r', 'n', ' ', 'a', '-', 'b', '\n', 'e', 'l', 's', 'e', 'i', 'f', ' ', 'o', 'p', '=', '=', '2', ' ', 't', 'h', 'e', 'n', '\n', 'r', 'e', 't', 'u', 'r', 'n', ' ', 'a', '*', 'b', '\n', 'e', 'l', 's', 'e', 'i', 'f', ' ', 'o', 'p', '=', '=', '3', ' ', 't', 'h', 'e', 'n', '\n', 'r', 'e', 't', 'u', 'r', 'n', ' ', 'a', '/', 'b', '\n', 'e', 'l', 's', 'e', 'i', 'f', ' ', 'o', 'p', '=', '=', '4', ' ', 't', 'h', 'e', 'n', '\n', 'r', 'e', 't', 'u', 'r', 'n', ' ', 'a', '%', 'b', '\n', 'e', 'l', 's', 'e', 'i', 'f', ' ', 'o', 'p', '=', '=', '5', ' ', 't', 'h', 'e', 'n', '\n', 'r', 'e', 't', 'u', 'r', 'n', ' ', 'a', '^', 'b', '\n', 'e', 'l', 's', 'e', 'i', 'f', ' ', 'o', 'p', '=', '=', '6', ' ', 't', 'h', 'e', 'n', '\n', 'r', 'e', 't', 'u', 'r', 'n', ' ', '-', 'a', '\n', 'e', 'n', 'd', '\n', '\0' }; void lua_arith (lua_State *L, int op) { if (op < LUA_OPADD && op > LUA_OPUNM) luaL_error(L, "invalid 'op' argument for lua_arith"); luaL_checkstack(L, 5, "not enough stack slots"); if (op == LUA_OPUNM) lua_pushvalue(L, -1); lua_pushnumber(L, op); lua_insert(L, -3); compat52_call_lua(L, compat52_arith_code, sizeof(compat52_arith_code)-1, 3, 1); } static const char compat52_compare_code[] = { 'l', 'o', 'c', 'a', 'l', ' ', 'a', ',', 'b', '=', '.', '.', '.', '\n', 'r', 'e', 't', 'u', 'r', 'n', ' ', 'a', '<', '=', 'b', '\n', '\0' }; int lua_compare (lua_State *L, int idx1, int idx2, int op) { int result = 0; switch (op) { case LUA_OPEQ: return lua_equal(L, idx1, idx2); case LUA_OPLT: return lua_lessthan(L, idx1, idx2); case LUA_OPLE: luaL_checkstack(L, 5, "not enough stack slots"); idx1 = lua_absindex(L, idx1); idx2 = lua_absindex(L, idx2); lua_pushvalue(L, idx1); lua_pushvalue(L, idx2); compat52_call_lua(L, compat52_compare_code, sizeof(compat52_compare_code)-1, 2, 1); result = lua_toboolean(L, -1); lua_pop(L, 1); return result; default: luaL_error(L, "invalid 'op' argument for lua_compare"); } return 0; } void lua_pushunsigned (lua_State *L, lua_Unsigned n) { lua_pushnumber(L, lua_unsigned2number(n)); } lua_Unsigned luaL_checkunsigned (lua_State *L, int i) { lua_Unsigned result; lua_Number n = lua_tonumber(L, i); if (n == 0 && !lua_isnumber(L, i)) luaL_checktype(L, i, LUA_TNUMBER); lua_number2unsigned(result, n); return result; } lua_Unsigned lua_tounsignedx (lua_State *L, int i, int *isnum) { lua_Unsigned result; lua_Number n = lua_tonumberx(L, i, isnum); lua_number2unsigned(result, n); return result; } lua_Unsigned luaL_optunsigned (lua_State *L, int i, lua_Unsigned def) { return luaL_opt(L, luaL_checkunsigned, i, def); } lua_Integer lua_tointegerx (lua_State *L, int i, int *isnum) { lua_Integer n = lua_tointeger(L, i); if (isnum != NULL) { *isnum = (n != 0 || lua_isnumber(L, i)); } return n; } void lua_len (lua_State *L, int i) { switch (lua_type(L, i)) { case LUA_TSTRING: /* fall through */ case LUA_TTABLE: if (!luaL_callmeta(L, i, "__len")) lua_pushnumber(L, (int)lua_objlen(L, i)); break; case LUA_TUSERDATA: if (luaL_callmeta(L, i, "__len")) break; /* maybe fall through */ default: luaL_error(L, "attempt to get length of a %s value", lua_typename(L, lua_type(L, i))); } } int luaL_len (lua_State *L, int i) { int res = 0, isnum = 0; luaL_checkstack(L, 1, "not enough stack slots"); lua_len(L, i); res = (int)lua_tointegerx(L, -1, &isnum); lua_pop(L, 1); if (!isnum) luaL_error(L, "object length is not a number"); return res; } const char *luaL_tolstring (lua_State *L, int idx, size_t *len) { if (!luaL_callmeta(L, idx, "__tostring")) { int t = lua_type(L, idx); switch (t) { case LUA_TNIL: lua_pushliteral(L, "nil"); break; case LUA_TSTRING: case LUA_TNUMBER: lua_pushvalue(L, idx); break; case LUA_TBOOLEAN: if (lua_toboolean(L, idx)) lua_pushliteral(L, "true"); else lua_pushliteral(L, "false"); break; default: lua_pushfstring(L, "%s: %p", lua_typename(L, t), lua_topointer(L, idx)); break; } } return lua_tolstring(L, -1, len); } void luaL_requiref (lua_State *L, char const* modname, lua_CFunction openf, int glb) { luaL_checkstack(L, 3, "not enough stack slots"); lua_pushcfunction(L, openf); lua_pushstring(L, modname); lua_call(L, 1, 1); lua_getglobal(L, "package"); lua_getfield(L, -1, "loaded"); lua_replace(L, -2); lua_pushvalue(L, -2); lua_setfield(L, -2, modname); lua_pop(L, 1); if (glb) { lua_pushvalue(L, -1); lua_setglobal(L, modname); } } void luaL_buffinit (lua_State *L, luaL_Buffer_52 *B) { /* make it crash if used via pointer to a 5.1-style luaL_Buffer */ B->b.p = NULL; B->b.L = NULL; B->b.lvl = 0; /* reuse the buffer from the 5.1-style luaL_Buffer though! */ B->ptr = B->b.buffer; B->capacity = LUAL_BUFFERSIZE; B->nelems = 0; B->L2 = L; } char *luaL_prepbuffsize (luaL_Buffer_52 *B, size_t s) { if (B->capacity - B->nelems < s) { /* needs to grow */ char* newptr = NULL; size_t newcap = B->capacity * 2; if (newcap - B->nelems < s) newcap = B->nelems + s; if (newcap < B->capacity) /* overflow */ luaL_error(B->L2, "buffer too large"); newptr = lua_newuserdata(B->L2, newcap); memcpy(newptr, B->ptr, B->nelems); if (B->ptr != B->b.buffer) lua_replace(B->L2, -2); /* remove old buffer */ B->ptr = newptr; B->capacity = newcap; } return B->ptr+B->nelems; } void luaL_addlstring (luaL_Buffer_52 *B, const char *s, size_t l) { memcpy(luaL_prepbuffsize(B, l), s, l); luaL_addsize(B, l); } void luaL_addvalue (luaL_Buffer_52 *B) { size_t len = 0; const char *s = lua_tolstring(B->L2, -1, &len); if (!s) luaL_error(B->L2, "cannot convert value to string"); if (B->ptr != B->b.buffer) lua_insert(B->L2, -2); /* userdata buffer must be at stack top */ luaL_addlstring(B, s, len); lua_remove(B->L2, B->ptr != B->b.buffer ? -2 : -1); } void luaL_pushresult (luaL_Buffer_52 *B) { lua_pushlstring(B->L2, B->ptr, B->nelems); if (B->ptr != B->b.buffer) lua_replace(B->L2, -2); /* remove userdata buffer */ } #endif /* LUA_VERSION_NUM == 501 */ /********************************************************************* * This file contains parts of Lua 5.2's source code: * * Copyright (C) 1994-2013 Lua.org, PUC-Rio. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ lua-bit32-5.3.0/c-api/compat-5.2.h000066400000000000000000000112051247060654400161570ustar00rootroot00000000000000#include #include #include #include "lua.h" #include "lauxlib.h" #include "lualib.h" #if !defined(LUA_VERSION_NUM) /* Lua 5.0 */ #define LUA_QL(x) "'" x "'" #define LUA_QS LUA_QL("%s") #define luaL_Reg luaL_reg #define luaL_opt(L, f, n, d) \ (lua_isnoneornil(L, n) ? (d) : f(L, n)) #define luaL_addchar(B,c) \ ((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \ (*(B)->p++ = (char)(c))) #endif /* Lua 5.0 */ #if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM == 501 /* Lua 5.1 */ /* PUC-Rio Lua uses lconfig_h as include guard for luaconf.h, * LuaJIT uses luaconf_h. If you use PUC-Rio's include files * but LuaJIT's library, you will need to define the macro * COMPAT52_IS_LUAJIT yourself! */ #if !defined(COMPAT52_IS_LUAJIT) && defined(luaconf_h) #define COMPAT52_IS_LUAJIT #endif /* LuaJIT doesn't define these unofficial macros ... */ #if !defined(LUAI_INT32) #include #if INT_MAX-20 < 32760 #define LUAI_INT32 long #define LUAI_UINT32 unsigned long #elif INT_MAX > 2147483640L #define LUAI_INT32 int #define LUAI_UINT32 unsigned int #else #error "could not detect suitable lua_Unsigned datatype" #endif #endif #define LUA_OPADD 0 #define LUA_OPSUB 1 #define LUA_OPMUL 2 #define LUA_OPDIV 3 #define LUA_OPMOD 4 #define LUA_OPPOW 5 #define LUA_OPUNM 6 #define LUA_OPEQ 0 #define LUA_OPLT 1 #define LUA_OPLE 2 typedef LUAI_UINT32 lua_Unsigned; typedef struct luaL_Buffer_52 { luaL_Buffer b; /* make incorrect code crash! */ char *ptr; size_t nelems; size_t capacity; lua_State *L2; } luaL_Buffer_52; #define luaL_Buffer luaL_Buffer_52 typedef struct luaL_Stream { FILE *f; /* The following field is for LuaJIT which adds a uint32_t field * to file handles. */ lua_Unsigned type; lua_CFunction closef; } luaL_Stream; #define lua_tounsigned(L, i) lua_tounsignedx(L, i, NULL) #define lua_rawlen(L, i) lua_objlen(L, i) void lua_arith (lua_State *L, int op); int lua_compare (lua_State *L, int idx1, int idx2, int op); void lua_pushunsigned (lua_State *L, lua_Unsigned n); lua_Unsigned luaL_checkunsigned (lua_State *L, int i); lua_Unsigned lua_tounsignedx (lua_State *L, int i, int *isnum); lua_Unsigned luaL_optunsigned (lua_State *L, int i, lua_Unsigned def); lua_Integer lua_tointegerx (lua_State *L, int i, int *isnum); void lua_len (lua_State *L, int i); int luaL_len (lua_State *L, int i); const char *luaL_tolstring (lua_State *L, int idx, size_t *len); void luaL_requiref (lua_State *L, char const* modname, lua_CFunction openf, int glb); #define luaL_buffinit luaL_buffinit_52 void luaL_buffinit (lua_State *L, luaL_Buffer_52 *B); #define luaL_prepbuffsize luaL_prepbuffsize_52 char *luaL_prepbuffsize (luaL_Buffer_52 *B, size_t s); #define luaL_addlstring luaL_addlstring_52 void luaL_addlstring (luaL_Buffer_52 *B, const char *s, size_t l); #define luaL_addvalue luaL_addvalue_52 void luaL_addvalue (luaL_Buffer_52 *B); #define luaL_pushresult luaL_pushresult_52 void luaL_pushresult (luaL_Buffer_52 *B); #undef luaL_buffinitsize #define luaL_buffinitsize(L, B, s) \ (luaL_buffinit(L, B), luaL_prepbuffsize(B, s)) #undef luaL_prepbuffer #define luaL_prepbuffer(B) \ luaL_prepbuffsize(B, LUAL_BUFFERSIZE) #undef luaL_addchar #define luaL_addchar(B, c) \ ((void)((B)->nelems < (B)->capacity || luaL_prepbuffsize(B, 1)), \ ((B)->ptr[(B)->nelems++] = (c))) #undef luaL_addsize #define luaL_addsize(B, s) \ ((B)->nelems += (s)) #undef luaL_addstring #define luaL_addstring(B, s) \ luaL_addlstring(B, s, strlen(s)) #undef luaL_pushresultsize #define luaL_pushresultsize(B, s) \ (luaL_addsize(B, s), luaL_pushresult(B)) #endif /* Lua 5.1 */ #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM == 501 /* Lua 5.0 *or* 5.1 */ #define LUA_OK 0 #define lua_pushglobaltable(L) \ lua_pushvalue(L, LUA_GLOBALSINDEX) #define luaL_newlib(L, l) \ (lua_newtable((L)),luaL_setfuncs((L), (l), 0)) void luaL_checkversion (lua_State *L); #endif /* Lua 5.0 *or* 5.1 */ int lua_absindex (lua_State *L, int i); void lua_copy (lua_State *L, int from, int to); void lua_rawgetp (lua_State *L, int i, const void *p); void lua_rawsetp (lua_State *L, int i, const void *p); void *luaL_testudata (lua_State *L, int i, const char *tname); lua_Number lua_tonumberx (lua_State *L, int i, int *isnum); void lua_getuservalue (lua_State *L, int i); void lua_setuservalue (lua_State *L, int i); void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup); void luaL_setmetatable (lua_State *L, const char *tname); int luaL_getsubtable (lua_State *L, int i, const char *name); void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, int level); int luaL_fileresult (lua_State *L, int stat, const char *fname); lua-bit32-5.3.0/compat52-scm-1.rockspec000066400000000000000000000015541247060654400173410ustar00rootroot00000000000000package = "compat52" version = "scm-1" source = { url = "https://github.com/hishamhm/lua-compat-5.2/archive/master.zip", dir = "lua-compat-5.2-master", } description = { summary = "Compatibility module providing Lua-5.2-style APIs for Lua 5.1", detailed = [[ This is a small module that aims to make it easier to write Lua code in a Lua-5.2-style that runs on both Lua 5.1 and Lua 5.2. This does *not* make Lua 5.1 entirely compatible with Lua 5.2, but it brings the API closer to that of Lua 5.2. ]], homepage = "https://github.com/hishamhm/lua-compat-5.2", license = "MIT/X11", } dependencies = { "lua >= 5.1, < 5.3", "bit32", } build = { type = "builtin", modules = { ["compat52"] = "compat52.lua", ["compat52.strict"] = "compat52/strict.lua", ["compat52.mstrict"] = "compat52/mstrict.lua", } } lua-bit32-5.3.0/compat52.lua000066400000000000000000000443501247060654400153740ustar00rootroot00000000000000-- utility module to make the Lua 5.1 standard libraries behave more like Lua 5.2 if _VERSION == "Lua 5.1" then bit32 = require("bit32") -- table that maps each running coroutine to the coroutine that resumed it -- this is used to build complete tracebacks when "coroutine-friendly" pcall -- is used. local pcall_previous local pcall_callOf local xpcall_running local coroutine_running = coroutine.running -- the most powerful getmetatable we can get (preferably from debug) local sudo_getmetatable = getmetatable local _error = error local _type = type if type(debug) == "table" then local _G, package = _G, package local debug_setfenv = debug.setfenv debug.setuservalue = function(obj, value) if _type(obj) ~= "userdata" then _error("bad argument #1 to 'setuservalue' (userdata expected, got ".. _type(obj)..")", 2) end if value == nil then value = _G end if _type(value) ~= "table" then _error("bad argument #2 to 'setuservalue' (table expected, got ".. _type(value)..")", 2) end return debug_setfenv(obj, value) end local debug_getfenv = debug.getfenv debug.getuservalue = function(obj) if _type(obj) ~= "userdata" then return nil else local v = debug_getfenv(obj) if v == _G or v == package then return nil end return v end end if _type(debug.getmetatable) == "function" then sudo_getmetatable = debug.getmetatable end local debug_setmetatable = debug.setmetatable if _type(debug_setmetatable) == "function" then debug.setmetatable = function(value, tab) debug_setmetatable(value, tab) return value end end local debug_getinfo = debug.getinfo local function calculate_trace_level(co, level) if level ~= nil then for out = 1, 1/0 do local info = (co==nil) and debug_getinfo(out, "") or debug_getinfo(co, out, "") if info == nil then local max = out-1 if level <= max then return level end return nil, level-max end end end return 1 end pcall_previous = {} pcall_callOf = {} xpcall_running = {} local stack_pattern = "\nstack traceback:" local stack_replace = "" local debug_traceback = debug.traceback debug.traceback = function (co, msg, level) local lvl local nilmsg if _type(co) ~= "thread" then co, msg, level = coroutine_running(), co, msg end if msg == nil then msg = "" nilmsg = true elseif _type(msg) ~= "string" then return msg end if co == nil then msg = debug_traceback(msg, level or 1) else local xpco = xpcall_running[co] if xpco ~= nil then lvl, level = calculate_trace_level(xpco, level) if lvl then msg = debug_traceback(xpco, msg, lvl) else msg = msg..stack_pattern end lvl, level = calculate_trace_level(co, level) if lvl then local trace = debug_traceback(co, "", lvl) msg = msg..trace:gsub(stack_pattern, stack_replace) end else co = pcall_callOf[co] or co lvl, level = calculate_trace_level(co, level) if lvl then msg = debug_traceback(co, msg, lvl) else msg = msg..stack_pattern end end co = pcall_previous[co] while co ~= nil do lvl, level = calculate_trace_level(co, level) if lvl then local trace = debug_traceback(co, "", lvl) msg = msg..trace:gsub(stack_pattern, stack_replace) end co = pcall_previous[co] end end if nilmsg then msg = msg:gsub("^\n", "") end msg = msg:gsub("\n\t%(tail call%): %?", "\000") msg = msg:gsub("\n\t%.%.%.\n", "\001\n") msg = msg:gsub("\n\t%.%.%.$", "\001") msg = msg:gsub("(%z+)\001(%z+)", function(some, other) return "\n\t(..."..#some+#other.."+ tail call(s)...)" end) msg = msg:gsub("\001(%z+)", function(zeros) return "\n\t(..."..#zeros.."+ tail call(s)...)" end) msg = msg:gsub("(%z+)\001", function(zeros) return "\n\t(..."..#zeros.."+ tail call(s)...)" end) msg = msg:gsub("%z+", function(zeros) return "\n\t(..."..#zeros.." tail call(s)...)" end) msg = msg:gsub("\001", function(zeros) return "\n\t..." end) return msg end end local _pairs = pairs pairs = function(t) local mt = sudo_getmetatable(t) if _type(mt) == "table" and _type(mt.__pairs) == "function" then return mt.__pairs(t) else return _pairs(t) end end local _ipairs = ipairs ipairs = function(t) local mt = sudo_getmetatable(t) if _type(mt) == "table" and _type(mt.__ipairs) == "function" then return mt.__ipairs(t) else return _ipairs(t) end end local _setfenv = setfenv local function check_mode(mode, prefix) local has = { text = false, binary = false } for i = 1,#mode do local c = mode:sub(i, i) if c == "t" then has.text = true end if c == "b" then has.binary = true end end local t = prefix:sub(1, 1) == "\27" and "binary" or "text" if not has[t] then return "attempt to load a "..t.." chunk (mode is '"..mode.."')" end end local _load, _loadstring = load, loadstring load = function(ld, source, mode, env) mode = mode or "bt" local chunk, msg if _type( ld ) == "string" then if mode ~= "bt" then local merr = check_mode(mode, ld) if merr then return nil, merr end end chunk, msg = _loadstring(ld, source) else local ld_type = _type(ld) if ld_type ~= "function" then _error("bad argument #1 to 'load' (function expected, got "..ld_type..")", 2) end if mode ~= "bt" then local checked, merr = false, nil local function checked_ld() if checked then return ld() else checked = true local v = ld() merr = check_mode(mode, v or "") if merr then return nil end return v end end chunk, msg = _load(checked_ld, source) if merr then return nil, merr end else chunk, msg = _load(ld, source) end end if not chunk then return chunk, msg end if env ~= nil then _setfenv(chunk, env) end return chunk end loadstring = load local _loadfile = loadfile local io_open = io.open loadfile = function(file, mode, env) mode = mode or "bt" if mode ~= "bt" then local f = io_open(file, "rb") if f then local prefix = f:read(1) f:close() if prefix then local merr = check_mode(mode, prefix) if merr then return nil, merr end end end end local chunk, msg = _loadfile(file) if not chunk then return chunk, msg end if env ~= nil then _setfenv(chunk, env) end return chunk end function rawlen(v) local t = _type(v) if t ~= "string" and t ~= "table" then _error("bad argument #1 to 'rawlen' (table or string expected)", 2) end return #v end local gc_isrunning = true local _collectgarbage = collectgarbage local math_floor = math.floor collectgarbage = function(opt, ...) opt = opt or "collect" local v = 0 if opt == "collect" then v = _collectgarbage(opt, ...) if not gc_isrunning then _collectgarbage("stop") end elseif opt == "stop" then gc_isrunning = false return _collectgarbage(opt, ...) elseif opt == "restart" then gc_isrunning = true return _collectgarbage(opt, ...) elseif opt == "count" then v = _collectgarbage(opt, ...) return v, (v-math_floor(v))*1024 elseif opt == "step" then v = _collectgarbage(opt, ...) if not gc_isrunning then _collectgarbage("stop") end elseif opt == "isrunning" then return gc_isrunning elseif opt ~= "generational" and opt ~= "incremental" then return _collectgarbage(opt, ...) end return v end local os_execute = os.execute local bit32_rshift = bit32.rshift os.execute = function(cmd) local code = os_execute(cmd) -- Lua 5.1 does not report exit by signal. if code == 0 then return true, "exit", code else return nil, "exit", bit32_rshift(code, 8) end end local _select = select table.pack = function(...) return { n = _select('#', ...), ... } end table.unpack = unpack local main_coroutine = coroutine.create(function() end) local _assert = assert local _pcall = pcall local coroutine_create = coroutine.create coroutine.create = function (func) local success, result = _pcall(coroutine_create, func) if not success then _assert(_type(func) == "function", "bad argument #1 (function expected)") result = coroutine_create(function(...) return func(...) end) end return result end local pcall_mainOf = {} coroutine.running = function() local co = coroutine_running() if co then return pcall_mainOf[co] or co, false else return main_coroutine, true end end local coroutine_yield = coroutine.yield coroutine.yield = function(...) local co = coroutine_running() if co then return coroutine_yield(...) else _error("attempt to yield from outside a coroutine", 0) end end local coroutine_resume = coroutine.resume coroutine.resume = function(co, ...) if co == main_coroutine then return false, "cannot resume non-suspended coroutine" else return coroutine_resume(co, ...) end end local coroutine_status = coroutine.status coroutine.status = function(co) local notmain = coroutine_running() if co == main_coroutine then return notmain and "normal" or "running" else return coroutine_status(co) end end local function pcall_results(current, call, success, ...) if coroutine_status(call) == "suspended" then return pcall_results(current, call, coroutine_resume(call, coroutine_yield(...))) end if pcall_previous then pcall_previous[call] = nil local main = pcall_mainOf[call] if main == current then current = nil end pcall_callOf[main] = current end pcall_mainOf[call] = nil return success, ... end local function pcall_exec(current, call, ...) local main = pcall_mainOf[current] or current pcall_mainOf[call] = main if pcall_previous then pcall_previous[call] = current pcall_callOf[main] = call end return pcall_results(current, call, coroutine_resume(call, ...)) end local coroutine_create52 = coroutine.create local function pcall_coroutine(func) if _type(func) ~= "function" then local callable = func func = function (...) return callable(...) end end return coroutine_create52(func) end pcall = function (func, ...) local current = coroutine_running() if not current then return _pcall(func, ...) end return pcall_exec(current, pcall_coroutine(func), ...) end local _tostring = tostring local function xpcall_catch(current, call, msgh, success, ...) if not success then xpcall_running[current] = call local ok, result = _pcall(msgh, ...) xpcall_running[current] = nil if not ok then return false, "error in error handling (".._tostring(result)..")" end return false, result end return true, ... end local _xpcall = xpcall local _unpack = unpack xpcall = function(f, msgh, ...) local current = coroutine_running() if not current then local args, n = { ... }, _select('#', ...) return _xpcall(function() return f(_unpack(args, 1, n)) end, msgh) end local call = pcall_coroutine(f) return xpcall_catch(current, call, msgh, pcall_exec(current, call, ...)) end local math_log = math.log math.log = function(x, base) if base ~= nil then return math_log(x)/math_log(base) else return math_log(x) end end local table_concat = table.concat package.searchpath = function(name, path, sep, rep) sep = (sep or "."):gsub("(%p)", "%%%1") rep = (rep or package.config:sub(1, 1)):gsub("(%%)", "%%%1") local pname = name:gsub(sep, rep):gsub("(%%)", "%%%1") local msg = {} for subpath in path:gmatch("[^;]+") do local fpath = subpath:gsub("%?", pname) local f = io_open(fpath, "r") if f then f:close() return fpath end msg[#msg+1] = "\n\tno file '" .. fpath .. "'" end return nil, table_concat(msg) end local p_index = { searchers = package.loaders } local _rawset = rawset setmetatable(package, { __index = p_index, __newindex = function(p, k, v) if k == "searchers" then _rawset(p, "loaders", v) p_index.searchers = v else _rawset(p, k, v) end end }) local string_gsub = string.gsub local function fix_pattern(pattern) return (string_gsub(pattern, "%z", "%%z")) end local string_find = string.find function string.find(s, pattern, ...) return string_find(s, fix_pattern(pattern), ...) end local string_gmatch = string.gmatch function string.gmatch(s, pattern) return string_gmatch(s, fix_pattern(pattern)) end function string.gsub(s, pattern, ...) return string_gsub(s, fix_pattern(pattern), ...) end local string_match = string.match function string.match(s, pattern, ...) return string_match(s, fix_pattern(pattern), ...) end local string_rep = string.rep function string.rep(s, n, sep) if sep ~= nil and sep ~= "" and n >= 2 then return s .. string_rep(sep..s, n-1) else return string_rep(s, n) end end local string_format = string.format do local addqt = { ["\n"] = "\\\n", ["\\"] = "\\\\", ["\""] = "\\\"" } local function addquoted(c) return addqt[c] or string_format("\\%03d", c:byte()) end function string.format(fmt, ...) local args, n = { ... }, _select('#', ...) local i = 0 local function adjust_fmt(lead, mods, kind) if #lead % 2 == 0 then i = i + 1 if kind == "s" then args[i] = _tostring(args[i]) elseif kind == "q" then args[i] = '"'..string_gsub(args[i], "[%z%c\\\"\n]", addquoted)..'"' return lead.."%"..mods.."s" end end end fmt = string_gsub(fmt, "(%%*)%%([%d%.%-%+%# ]*)(%a)", adjust_fmt) return string_format(fmt, _unpack(args, 1, n)) end end local io_write = io.write local io_output = io.output function io.write(...) local res, msg, errno = io_write(...) if res then return io_output() else return nil, msg, errno end end local lines_iterator do local function helper( st, var_1, ... ) if var_1 == nil then if st.doclose then st.f:close() end if (...) ~= nil then _error((...), 2) end end return var_1, ... end function lines_iterator(st) return helper(st, st.f:read(_unpack(st, 1, st.n))) end end local valid_format = { ["*l"] = true, ["*n"] = true, ["*a"] = true } local io_input = io.input function io.lines(fname, ...) local doclose, file, msg if fname ~= nil then doclose, file, msg = true, io_open(fname, "r") if not file then _error(msg, 2) end else doclose, file = false, io_input() end local st = { f=file, doclose=doclose, n=_select('#', ...), ... } for i = 1, st.n do if _type(st[i]) ~= "number" and not valid_format[st[i]] then _error("bad argument #"..(i+1).." to 'for iterator' (invalid format)", 2) end end return lines_iterator, st end do local io_stdout = io.stdout local io_type = io.type local file_meta = sudo_getmetatable(io_stdout) if _type(file_meta) == "table" and _type(file_meta.__index) == "table" then local file_write = file_meta.__index.write file_meta.__index.write = function(self, ...) local res, msg, errno = file_write(self, ...) if res then return self else return nil, msg, errno end end file_meta.__index.lines = function(self, ...) if io_type(self) == "closed file" then _error("attempt to use a closed file", 2) end local st = { f=self, doclose=false, n=_select('#', ...), ... } for i = 1, st.n do if _type(st[i]) ~= "number" and not valid_format[st[i]] then _error("bad argument #"..(i+1).." to 'for iterator' (invalid format)", 2) end end return lines_iterator, st end end end end lua-bit32-5.3.0/compat52/000077500000000000000000000000001247060654400146635ustar00rootroot00000000000000lua-bit32-5.3.0/compat52/mstrict.lua000066400000000000000000000053771247060654400170670ustar00rootroot00000000000000 --- Stricter version of compat52. -- Attempts to emulate Lua 5.2 when built without LUA_COMPAT_ALL. if _VERSION == "Lua 5.1" then require("compat52") local function not_available() error("This function is not available in Lua 5.2!", 2) end local exclude_from_G = { module = not_available, getfenv = not_available, setfenv = not_available, loadstring = not_available, unpack = not_available, loadlib = not_available, math = { log10 = not_available, mod = not_available, }, table = { getn = not_available, setn = not_available, }, string = { gfind = not_available, }, } local next = next local function make_pairs_iterator(lookup) return function(st, var) local k, v = next(st, var) if k ~= nil then local new_v = lookup[k] if new_v ~= nil then v = new_v end return k, v end end end local rawget = rawget local function make_ipairs_iterator(lookup) return function(st, var) var = var + 1 local v = rawget(st, var) if v ~= nil then local new_v = lookup[var] if new_v ~= nil then v = new_v end return var, v end end end local function make_copy(value, excl) local v_type, e_type = type(value), type(excl) if v_type == e_type then if v_type == "table" then local l_table = {} for k, v in pairs(excl) do l_table[k] = make_copy(rawget(value, k), v) end local pairs_iterator = make_pairs_iterator(l_table) local ipairs_iterator = make_ipairs_iterator(l_table) return setmetatable({}, { __index = function(_, k) local v = l_table[k] if v ~= nil then return v else return value[k] end end, __newindex = function(_, k, v) if l_table[k] ~= nil then l_table[k] = nil end value[k] = v end, __pairs = function() return pairs_iterator, value, nil end, __ipairs = function() return ipairs_iterator, value, 0 end, }), l_table elseif v_type == "function" then return excl end end end local new_G, G_lookup = make_copy(_G, exclude_from_G) G_lookup._G = new_G return function() setfenv(2, new_G) end else return function() end end -- vi: set expandtab softtabstop=3 shiftwidth=3 : lua-bit32-5.3.0/compat52/strict.lua000066400000000000000000000006741247060654400167050ustar00rootroot00000000000000 --- Stricter version of compat52. -- Attempts to emulate Lua 5.2 when built without LUA_COMPAT_ALL. require("compat52") if _VERSION == "Lua 5.1" then module = nil setfenv = nil getfenv = nil math.log10 = nil loadstring = nil table.maxn = nil unpack = nil -- functions deprecated in Lua 5.1 are also not available: table.getn = nil table.setn = nil loadlib = nil math.mod = nil string.gfind = nil end lua-bit32-5.3.0/lbitlib.c000066400000000000000000000121241247060654400150160ustar00rootroot00000000000000/* ** $Id: lbitlib.c,v 1.28 2014/11/02 19:19:04 roberto Exp $ ** Standard library for bitwise operations ** See Copyright Notice in lua.h */ #define lbitlib_c #define LUA_LIB #include "lua.h" #include "lauxlib.h" #include "lualib.h" /********************************************************************/ #if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM == 501 #include "compat-5.2.c" #elif defined(LUA_VERSION_NUM) && LUA_VERSION_NUM == 503 #define luaL_checkunsigned(L, n) ((lua_Unsigned)luaL_checkinteger((L), (n))) #define lua_pushunsigned(L, n) (lua_pushinteger(L, (lua_Integer)(n))) #endif #undef LUAMOD_API #define LUAMOD_API extern /********************************************************************/ /* number of bits to consider in a number */ #if !defined(LUA_NBITS) #define LUA_NBITS 32 #endif /* ** a lua_Unsigned with its first LUA_NBITS bits equal to 1. (Shift must ** be made in two parts to avoid problems when LUA_NBITS is equal to the ** number of bits in a lua_Unsigned.) */ #define ALLONES (~(((~(lua_Unsigned)0) << (LUA_NBITS - 1)) << 1)) /* macro to trim extra bits */ #define trim(x) ((x) & ALLONES) /* builds a number with 'n' ones (1 <= n <= LUA_NBITS) */ #define mask(n) (~((ALLONES << 1) << ((n) - 1))) static lua_Unsigned andaux (lua_State *L) { int i, n = lua_gettop(L); lua_Unsigned r = ~(lua_Unsigned)0; for (i = 1; i <= n; i++) r &= luaL_checkunsigned(L, i); return trim(r); } static int b_and (lua_State *L) { lua_Unsigned r = andaux(L); lua_pushunsigned(L, r); return 1; } static int b_test (lua_State *L) { lua_Unsigned r = andaux(L); lua_pushboolean(L, r != 0); return 1; } static int b_or (lua_State *L) { int i, n = lua_gettop(L); lua_Unsigned r = 0; for (i = 1; i <= n; i++) r |= luaL_checkunsigned(L, i); lua_pushunsigned(L, trim(r)); return 1; } static int b_xor (lua_State *L) { int i, n = lua_gettop(L); lua_Unsigned r = 0; for (i = 1; i <= n; i++) r ^= luaL_checkunsigned(L, i); lua_pushunsigned(L, trim(r)); return 1; } static int b_not (lua_State *L) { lua_Unsigned r = ~luaL_checkunsigned(L, 1); lua_pushunsigned(L, trim(r)); return 1; } static int b_shift (lua_State *L, lua_Unsigned r, lua_Integer i) { if (i < 0) { /* shift right? */ i = -i; r = trim(r); if (i >= LUA_NBITS) r = 0; else r >>= i; } else { /* shift left */ if (i >= LUA_NBITS) r = 0; else r <<= i; r = trim(r); } lua_pushunsigned(L, r); return 1; } static int b_lshift (lua_State *L) { return b_shift(L, luaL_checkunsigned(L, 1), luaL_checkinteger(L, 2)); } static int b_rshift (lua_State *L) { return b_shift(L, luaL_checkunsigned(L, 1), -luaL_checkinteger(L, 2)); } static int b_arshift (lua_State *L) { lua_Unsigned r = luaL_checkunsigned(L, 1); lua_Integer i = luaL_checkinteger(L, 2); if (i < 0 || !(r & ((lua_Unsigned)1 << (LUA_NBITS - 1)))) return b_shift(L, r, -i); else { /* arithmetic shift for 'negative' number */ if (i >= LUA_NBITS) r = ALLONES; else r = trim((r >> i) | ~(trim(~(lua_Unsigned)0) >> i)); /* add signal bit */ lua_pushunsigned(L, r); return 1; } } static int b_rot (lua_State *L, lua_Integer d) { lua_Unsigned r = luaL_checkunsigned(L, 1); int i = d & (LUA_NBITS - 1); /* i = d % NBITS */ r = trim(r); if (i != 0) /* avoid undefined shift of LUA_NBITS when i == 0 */ r = (r << i) | (r >> (LUA_NBITS - i)); lua_pushunsigned(L, trim(r)); return 1; } static int b_lrot (lua_State *L) { return b_rot(L, luaL_checkinteger(L, 2)); } static int b_rrot (lua_State *L) { return b_rot(L, -luaL_checkinteger(L, 2)); } /* ** get field and width arguments for field-manipulation functions, ** checking whether they are valid. ** ('luaL_error' called without 'return' to avoid later warnings about ** 'width' being used uninitialized.) */ static int fieldargs (lua_State *L, int farg, int *width) { lua_Integer f = luaL_checkinteger(L, farg); lua_Integer w = luaL_optinteger(L, farg + 1, 1); luaL_argcheck(L, 0 <= f, farg, "field cannot be negative"); luaL_argcheck(L, 0 < w, farg + 1, "width must be positive"); if (f + w > LUA_NBITS) luaL_error(L, "trying to access non-existent bits"); *width = (int)w; return (int)f; } static int b_extract (lua_State *L) { int w; lua_Unsigned r = trim(luaL_checkunsigned(L, 1)); int f = fieldargs(L, 2, &w); r = (r >> f) & mask(w); lua_pushunsigned(L, r); return 1; } static int b_replace (lua_State *L) { int w; lua_Unsigned r = trim(luaL_checkunsigned(L, 1)); lua_Unsigned v = luaL_checkunsigned(L, 2); int f = fieldargs(L, 3, &w); int m = mask(w); v &= m; /* erase bits outside given width */ r = (r & ~(m << f)) | (v << f); lua_pushunsigned(L, r); return 1; } static const luaL_Reg bitlib[] = { {"arshift", b_arshift}, {"band", b_and}, {"bnot", b_not}, {"bor", b_or}, {"bxor", b_xor}, {"btest", b_test}, {"extract", b_extract}, {"lrotate", b_lrot}, {"lshift", b_lshift}, {"replace", b_replace}, {"rrotate", b_rrot}, {"rshift", b_rshift}, {NULL, NULL} }; LUAMOD_API int luaopen_bit32 (lua_State *L) { luaL_newlib(L, bitlib); return 1; } lua-bit32-5.3.0/rockspecs/000077500000000000000000000000001247060654400152255ustar00rootroot00000000000000lua-bit32-5.3.0/rockspecs/bit32-5.2.2-1.rockspec000066400000000000000000000007651247060654400205130ustar00rootroot00000000000000package = "bit32" version = "5.2.2-1" source = { url = "https://raw.github.com/hishamhm/lua-compat-5.2/bitlib-5.2.2/lbitlib.c", } description = { summary = "Lua 5.2 bit manipulation library", detailed = [[ bit32 is the native Lua 5.2 bit manipulation library, backported to Lua 5.1 ]], license = "MIT/X11", homepage = "http://lua.org/work/", } dependencies = { "lua >= 5.1, < 5.2" } build = { type = "builtin", modules = { bit32 = "lbitlib.c", } } lua-bit32-5.3.0/rockspecs/bit32-5.2.3-1.rockspec000066400000000000000000000011451247060654400205050ustar00rootroot00000000000000package = "bit32" version = "5.2.3-1" source = { url = "git://github.com/hishamhm/lua-compat-5.2.git", tag = "bitlib-5.2.3", } description = { summary = "Lua 5.2 bit manipulation library", detailed = [[ bit32 is the native Lua 5.2 bit manipulation library, backported to Lua 5.1 ]], license = "MIT/X11", homepage = "http://www.lua.org/manual/5.2/manual.html#6.7", } dependencies = { "lua >= 5.1, < 5.2" } build = { type = "builtin", modules = { bit32 = { sources = { "lbitlib.c", "c-api/compat-5.2.c" }, incdirs = { "c-api" }, } } } lua-bit32-5.3.0/rockspecs/bit32-5.3.0-1.rockspec000066400000000000000000000012101247060654400204740ustar00rootroot00000000000000package = "bit32" version = "5.3.0-1" source = { url = "git://github.com/keplerproject/lua-compat-5.2.git", tag = "bitlib-5.3.0", } description = { summary = "Lua 5.2 bit manipulation library", detailed = [[ bit32 is the native Lua 5.2 bit manipulation library, in the version from Lua 5.3; it is compatible with Lua 5.1, 5.2 and 5.3. ]], license = "MIT/X11", homepage = "http://www.lua.org/manual/5.2/manual.html#6.7", } dependencies = { "lua >= 5.1, <= 5.3" } build = { type = "builtin", modules = { bit32 = { sources = { "lbitlib.c" }, incdirs = { "c-api" }, } } } lua-bit32-5.3.0/rockspecs/compat52-0.1-1.rockspec000066400000000000000000000013761247060654400210530ustar00rootroot00000000000000package = "compat52" version = "0.1-1" source = { url = "https://github.com/hishamhm/lua-compat-5.2/archive/v0.1.zip", dir = "lua-compat-5.2-0.1", } description = { summary = "Compatibility module providing Lua-5.2-style APIs for Lua 5.1", detailed = [[ This is a small module that aims to make it easier to write Lua code in a Lua-5.2-style that runs on both Lua 5.1 and Lua 5.2. This does *not* make Lua 5.1 entirely compatible with Lua 5.2, but it brings the API closer to that of Lua 5.2. ]], homepage = "https://github.com/hishamhm/lua-compat-5.2", license = "MIT/X11", } dependencies = { "lua >= 5.1, < 5.3", "bit32" } build = { type = "builtin", modules = { ["compat52"] = "compat52.lua", } } lua-bit32-5.3.0/tests/000077500000000000000000000000001247060654400143735ustar00rootroot00000000000000lua-bit32-5.3.0/tests/test.lua000077500000000000000000000426031247060654400160650ustar00rootroot00000000000000#!/usr/bin/lua -- simple test suite that checks all provided compatibilty functions -- and saves their outputs to a file in such a way, that you can -- easily compare results of different Lua versions side by side! local print, F, writefile local ____________________________________________________________ local outfile = "output_" .. _VERSION:gsub("[%s%.]+", "") .. ".txt" do local separator = ("="):rep(70) local out = assert(io.open(outfile, "w")) local select, tostring = select, tostring function print(...) local n = select('#', ...) for i = 1, n-1 do out:write(tostring((select(i, ...))), "\t") end if n > 0 then out:write(tostring((select(n, ...)))) end out:write("\n") out:flush() end function ____________________________________________________________() out:write(separator, "\n") out:flush() end local type, unpack = type, table.unpack or unpack function F(...) local args, n = { ... }, select('#', ...) for i = 1, n do local t = type(args[i]) if t ~= "string" and t ~= "number" and t ~= "boolean" then args[i] = t end end return unpack(args, 1, n) end local assert, io = assert, io function writefile(name, contents, bin) local f = assert(io.open(name, bin and "wb" or "w")) f:write(contents) f:close() end end package.path = "../?.lua;" .. package.path package.cpath = "../?.so;" .. package.cpath -- load compatibility functions (in Lua 5.1) require("compat52") ____________________________________________________________'' print("bit32.arshift()", bit32.arshift and bit32.arshift(2^32-4, 2)) print("bit32.band()", bit32.band and bit32.band(7, 5, 3)) print("bit32.bnot()", bit32.bnot and bit32.bnot(0)) print("bit32.bor()", bit32.bor and bit32.bor(1, 2, 4)) print("bit32.btest()", bit32.btest and bit32.btest(7, 5, 3)) print("bit32.bxor()", bit32.bxor and bit32.bxor(7, 5, 4, 3, 1)) print("bit32.extract()", bit32.extract and bit32.extract(7, 0, 2)) print("bit32.replace()", bit32.replace and bit32.replace(2^32-1, 0, 3, 29)) print("bit32.lrotate()", bit32.lrotate and bit32.lrotate(2^31, 1)) print("bit32.lshift()", bit32.lshift and bit32.lshift(2^31+2^30, 1)) print("bit32.rrotate()", bit32.rrotate and bit32.rrotate(2, 2)) print("bit32.rshift()", bit32.rshift and bit32.rshift(16, 3)) ____________________________________________________________'' print("debug.getuservalue()", F(debug.getuservalue(false))) print("debug.setuservalue()", pcall(function() debug.setuservalue(false, {}) end)) print("debug.setuservalue()", pcall(function() debug.setuservalue(io.stderr, 1) end)) print("debug.setmetatable()", F(debug.setmetatable({}, {}))) ____________________________________________________________'' do local t = setmetatable({}, { __ipairs = function() return ipairs({ 1, 2, 3 }) end, __pairs = function() return pairs({ a = "a" }) end, }) for k,v in pairs(t) do print("pairs()", k, v) end for i,v in ipairs(t) do print("ipairs()", i, v) end end ____________________________________________________________'' do local code = "print('hello world')\n" local badcode = "print('blub\n" print("load()", pcall(function() load(true) end)) print("load()", F(load(badcode))) print("load()", F(load(code))) print("load()", F(load(code, "[L]"))) print("load()", F(load(code, "[L]", "b"))) print("load()", F(load(code, "[L]", "t"))) print("load()", F(load(code, "[L]", "bt"))) local f = load(code, "[L]", "bt", {}) print("load()", pcall(f)) f = load(code, "[L]", "bt", { print = print }) print("load()", pcall(f)) local bytecode = string.dump(f) print("load()", F(load(bytecode))) print("load()", F(load(bytecode, "[L]"))) print("load()", F(load(bytecode, "[L]", "b"))) print("load()", F(load(bytecode, "[L]", "t"))) print("load()", F(load(bytecode, "[L]", "bt"))) f = load(bytecode, "[L]", "bt", {}) print("load()", pcall(f)) f = load(bytecode, "[L]", "bt", { print = print }) print("load()", pcall(f)) local function make_loader(code) local mid = math.floor( #code/2 ) local array = { code:sub(1, mid), code:sub(mid+1) } local i = 0 return function() i = i + 1 return array[i] end end print("load()", F(load(make_loader(badcode)))) print("load()", F(load(make_loader(code)))) print("load()", F(load(make_loader(code), "[L]"))) print("load()", F(load(make_loader(code), "[L]", "b"))) print("load()", F(load(make_loader(code), "[L]", "t"))) print("load()", F(load(make_loader(code), "[L]", "bt"))) f = load(make_loader(code), "[L]", "bt", {}) print("load()", pcall(f)) f = load(make_loader(code), "[L]", "bt", { print = print }) print("load()", pcall(f)) print("load()", F(load(make_loader(bytecode)))) print("load()", F(load(make_loader(bytecode), "[L]"))) print("load()", F(load(make_loader(bytecode), "[L]", "b"))) print("load()", F(load(make_loader(bytecode), "[L]", "t"))) print("load()", F(load(make_loader(bytecode), "[L]", "bt"))) f = load(make_loader(bytecode), "[L]", "bt", {}) print("load()", pcall(f)) f = load(make_loader(bytecode), "[L]", "bt", { print = print }) print("load()", pcall(f)) writefile("good.lua", code) writefile("bad.lua", badcode) writefile("good.luac", bytecode, true) print("loadfile()", F(loadfile("bad.lua"))) print("loadfile()", F(loadfile("good.lua"))) print("loadfile()", F(loadfile("good.lua", "b"))) print("loadfile()", F(loadfile("good.lua", "t"))) print("loadfile()", F(loadfile("good.lua", "bt"))) f = loadfile("good.lua", "bt", {}) print("loadfile()", pcall(f)) f = loadfile("good.lua", "bt", { print = print }) print("loadfile()", pcall(f)) print("loadfile()", F(loadfile("good.luac"))) print("loadfile()", F(loadfile("good.luac", "b"))) print("loadfile()", F(loadfile("good.luac", "t"))) print("loadfile()", F(loadfile("good.luac", "bt"))) f = loadfile("good.luac", "bt", {}) print("loadfile()", pcall(f)) f = loadfile("good.luac", "bt", { print = print }) print("loadfile()", pcall(f)) os.remove("good.lua") os.remove("bad.lua") os.remove("good.luac") end ____________________________________________________________'' do local function func(throw) if throw then error("argh") else return 1, 2, 3 end end local function tb(err) return "|"..err.."|" end print("xpcall()", xpcall(func, debug.traceback, false)) print("xpcall()", xpcall(func, debug.traceback, true)) print("xpcall()", xpcall(func, tb, true)) local function func2(cb) print("xpcall()", xpcall(cb, debug.traceback, "str")) end local function func3(cb) print("pcall()", pcall( cb, "str" )) end local function cb(arg) coroutine.yield( 2 ) return arg end local c = coroutine.wrap( func2 ) print("xpcall()", c(cb)) print("xpcall()", c()) local c = coroutine.wrap( func3 ) print("pcall()", c(cb)) print("pcall()", c()) end ____________________________________________________________'' do local t = setmetatable({ 1 }, { __len = function() return 5 end }) print("rawlen()", rawlen(t), rawlen("123")) end ____________________________________________________________'' print("collectgarbage()", collectgarbage("isrunning")) print("collectgarbage()", collectgarbage("stop")) print("collectgarbage()", collectgarbage("isrunning")) print("collectgarbage()", collectgarbage("collect")) print("collectgarbage()", collectgarbage("isrunning")) print("collectgarbage()", collectgarbage("step", 10)) print("collectgarbage()", collectgarbage("isrunning")) print("collectgarbage()", collectgarbage("restart")) print("collectgarbage()", collectgarbage("isrunning")) print("collectgarbage()", collectgarbage("count")) print("collectgarbage()", collectgarbage("generational")) print("collectgarbage()", collectgarbage("incremental")) ____________________________________________________________'' print("os.execute()", os.execute("exit 1")) print("os.execute()", os.execute("echo 'hello world'")) print("os.execute()", os.execute("no_such_file")) ____________________________________________________________'' do local t = table.pack("a", nil, "b", nil) print("table.(un)pack()", t.n, table.unpack(t, 1, t.n)) end ____________________________________________________________'' do print("coroutine.running()", F(coroutine.wrap(function() return coroutine.running() end)())) print("coroutine.running()", F(coroutine.running())) local main_co, co1, co2 = coroutine.running() -- coroutine.yield print("coroutine.yield()", pcall(function() coroutine.yield(1, 2, 3) end)) print("coroutine.yield()", coroutine.wrap(function() coroutine.yield(1, 2, 3) end)()) print("coroutine.resume()", coroutine.resume(main_co, 1, 2, 3)) co1 = coroutine.create(function(a, b, c) print("coroutine.resume()", a, b, c) return a, b, c end) print("coroutine.resume()", coroutine.resume(co1, 1, 2, 3)) co1 = coroutine.create(function() print("coroutine.status()", "[co1] main is", coroutine.status(main_co)) print("coroutine.status()", "[co1] co2 is", coroutine.status(co2)) end) co2 = coroutine.create(function() print("coroutine.status()", "[co2] main is", coroutine.status(main_co)) print("coroutine.status()", "[co2] co2 is", coroutine.status(co2)) coroutine.yield() coroutine.resume(co1) end) print("coroutine.status()", coroutine.status(main_co)) print("coroutine.status()", coroutine.status(co2)) coroutine.resume(co2) print("coroutine.status()", F(coroutine.status(co2))) coroutine.resume(co2) print("coroutine.status()", F(coroutine.status(co2))) end ____________________________________________________________'' print("math.log()", math.log(1000)) print("math.log()", math.log(1000, 10)) ____________________________________________________________'' do local path, prefix = "./?.lua;?/init.lua;../?.lua", "package.searchpath()" print(prefix, package.searchpath("no.such.module", path)) print(prefix, package.searchpath("no.such.module", "")) print(prefix, package.searchpath("compat52", path)) print(prefix, package.searchpath("no:such:module", path, ":", "|")) end ____________________________________________________________'' do local function mod_func() return {} end local function my_searcher(name) if name == "my.module" then print("package.searchers", "my.module found") return mod_func end end local function my_searcher2(name) if name == "my.module" then print("package.searchers", "my.module found 2") return mod_func end end table.insert(package.searchers, my_searcher) require("my.module") package.loaded["my.module"] = nil local new_s = { my_searcher2 } for i,f in ipairs(package.searchers) do new_s[i+1] = f end package.searchers = new_s require("my.module") end ____________________________________________________________'' do print("string.find()", ("abc\0abc\0abc"):find("[^a\0]+")) print("string.find()", ("abc\0abc\0abc"):find("%w+\0", 5)) for x in ("abc\0def\0ghi"):gmatch("[^\0]+") do print("string.gmatch()", x) end for x in ("abc\0def\0ghi"):gmatch("%w*\0") do print("string.gmatch()", #x) end print("string.gsub()", ("abc\0def\0ghi"):gsub("[\0]", "X")) print("string.gsub()", ("abc\0def\0ghi"):gsub("%w*\0", "X")) print("string.gsub()", ("abc\0def\0ghi"):gsub("%A", "X")) print("string.match()", ("abc\0abc\0abc"):match("([^\0a]+)")) print("string.match()", #("abc\0abc\0abc"):match(".*\0")) print("string.rep()", string.rep("a", 0)) print("string.rep()", string.rep("b", 1)) print("string.rep()", string.rep("c", 4)) print("string.rep()", string.rep("a", 0, "|")) print("string.rep()", string.rep("b", 1, "|")) print("string.rep()", string.rep("c", 4, "|")) local _tostring = tostring function tostring(v) if type(v) == "number" then return "(".._tostring(v)..")" else return _tostring(v) end end print("string.format()", string.format("%q", "\"\\\0000\0010\r0\n0\t0\"")) print("string.format()", string.format("%12.3fx%%sxx%.6s", 3.1, {})) print("string.format()", string.format("%-3f %%%s %%s", 3.1, true)) print("string.format()", string.format("% 3.2g %%d %%%s", 3.1, nil)) print("string.format()", string.format("%+3d %%d %%%%%10.6s", 3.1, io.stdout)) print("string.format()", pcall(function() print("string.format()", string.format("%d %%s", {})) end)) tostring = _tostring end ____________________________________________________________'' do print("io.write()", io.type(io.write("hello world\n"))) local f = assert(io.tmpfile()) print("file:write()", io.type(f:write("hello world\n"))) f:close() end ____________________________________________________________'' do writefile("data.txt", "123 18.8 hello world\ni'm here\n") for a,b in io.lines("test.lua", 2, "*l") do print("io.lines()", a, b) break end for l in io.lines("test.lua") do print("io.lines()", l) break end for n1,n2,rest in io.lines("data.txt", "*n", "*n", "*a") do print("io.lines()", n1, n2, rest) end for l in io.lines("data.txt") do print("io.lines()", l) end print("io.lines()", pcall(function() for l in io.lines("data.txt", "*x") do print(l) end end)) print("io.lines()", pcall(function() for l in io.lines("no_such_file.txt") do print(l) end end)) local f = assert(io.open("test.lua", "r")) for a,b in f:lines(2, "*l") do print("file:lines()", a, b) break end f:close() f = assert(io.open("data.txt", "r")) for n1,n2,rest in f:lines("*n", "*n", "*a") do print("file:lines()", n1, n2, rest) end f:close() f = assert(io.open("data.txt", "r")) for l in f:lines() do print("file:lines()", l) end f:close() print("file:lines()", pcall(function() for l in f:lines() do print(l) end end)) print("file:lines()", pcall(function() local f = assert(io.open("data.txt", "r")) for l in f:lines("*l", "*x") do print(l) end f:close() end)) os.remove("data.txt") end ____________________________________________________________'' do local modname = _VERSION:gsub("^.*(%d+)%.(%d+).-$", "%1%2-testmod") local ok, mod = pcall(require, modname) if not ok then io.write("### no ", modname, ".so or ", modname, ".dll! ###\n") io.write("'require' claimed: ", mod, "\n") io.write("### Skipping C API tests! ###\n") else print("C API", mod.tonumber(12)) print("C API", mod.tonumber("12")) print("C API", mod.tonumber("0")) print("C API", mod.tonumber(false)) print("C API", mod.tonumber("error")) print("C API", mod.tointeger(12)) print("C API", mod.tointeger("12")) print("C API", mod.tointeger("0")) print("C API", mod.tointeger(math.pi)) print("C API", mod.tointeger(false)) print("C API", mod.tointeger("error")) print("C API", mod.unsigned(1)) print("C API", mod.unsigned(2^31+1)) print("C API", mod.unsigned(2^32+1)) print("C API", mod.unsigned(-1)) print("C API", mod.unsigned(2^56)) print("C API", mod.unsigned("17")) print("C API", pcall(mod.unsigned, "0")) print("C API", pcall(mod.unsigned, true)) print("C API", mod.optunsigned()) print("C API", mod.optunsigned(42)) print("C API", pcall(mod.optunsigned, true)) print("C API", mod.len("123")) print("C API", mod.len({ 1, 2, 3})) print("C API", pcall(mod.len, true)) local ud, meta = mod.newproxy() meta.__len = function() return 5 end print("C API", mod.len(ud)) meta.__len = function() return true end print("C API", pcall(mod.len, ud)) print("C API", mod.copy(true, "string", {}, 1)) print("C API", mod.rawxetp()) print("C API", mod.rawxetp("I'm back")) print("C API", F(mod.globals()), mod.globals() == _G) local t = {} print("C API", F(mod.subtable(t))) local x, msg = mod.subtable(t) print("C API", F(x, msg, x == t.xxx)) print("C API", F(mod.udata())) print("C API", mod.udata("nosuchtype")) print("C API", F(mod.uservalue())) print("C API", mod.getupvalues()) print("C API", mod.absindex("hi", true)) print("C API", mod.arith(2, 1)) print("C API", mod.arith(3, 5)) print("C API", mod.compare(1, 1)) print("C API", mod.compare(2, 1)) print("C API", mod.compare(1, 2)) print("C API", mod.tolstring("string")) local t = setmetatable({}, { __tostring = function(v) return "mytable" end }) print("C API", mod.tolstring( t ) ) local t = setmetatable({}, { __tostring = function(v) return nil end }) print("C API", pcall( mod.tolstring, t ) ) local a, b = mod.requiref() print("C API", type(a), type(b), a.boolean, b.boolean, type(requiref1), type(requiref2)) print("C API", mod.buffer()) print("debug.getuservalue()", F(debug.getuservalue(ud))) print("debug.setuservalue()", F(debug.setuservalue(ud, {}))) print("debug.getuservalue()", F(debug.getuservalue(ud))) print("debug.setuservalue()", F(debug.setuservalue(ud, nil))) print("debug.getuservalue()", F(debug.getuservalue(ud))) end end ____________________________________________________________'' io.write("### Output written to ", outfile, "! ###\n") lua-bit32-5.3.0/tests/testmod.c000066400000000000000000000140141247060654400162160ustar00rootroot00000000000000#include #include "lua.h" #include "lauxlib.h" #include "compat-5.2.h" #define NUP 3 static int test_newproxy (lua_State *L) { lua_settop(L, 0); lua_newuserdata(L, 0); lua_newtable(L); lua_pushvalue(L, -1); lua_pushboolean(L, 1); lua_setfield(L, -2, "__gc"); lua_setmetatable(L, -3); return 2; } static int test_absindex (lua_State *L) { int i = 1; for (i = 1; i <= NUP; ++i) lua_pushvalue(L, lua_absindex(L, lua_upvalueindex(i))); lua_pushvalue(L, lua_absindex(L, LUA_REGISTRYINDEX)); lua_pushstring(L, lua_typename(L, lua_type(L, lua_absindex(L, -1)))); lua_replace(L, lua_absindex(L, -2)); lua_pushvalue(L, lua_absindex(L, -2)); lua_pushvalue(L, lua_absindex(L, -4)); lua_pushvalue(L, lua_absindex(L, -6)); i += 3; lua_pushvalue(L, lua_absindex(L, 1)); lua_pushvalue(L, lua_absindex(L, 2)); lua_pushvalue(L, lua_absindex(L, 3)); i += 3; return i; } static int test_compare (lua_State *L) { luaL_checknumber(L, 1); luaL_checknumber(L, 2); lua_settop(L, 2); lua_pushboolean(L, lua_compare(L, 1, 2, LUA_OPEQ)); lua_pushboolean(L, lua_compare(L, 1, 2, LUA_OPLT)); lua_pushboolean(L, lua_compare(L, 1, 2, LUA_OPLE)); return 3; } static int test_arith (lua_State *L) { lua_settop(L, 2); lua_pushvalue(L, 1); lua_pushvalue(L, 2); lua_arith(L, LUA_OPADD); lua_pushvalue(L, 1); lua_pushvalue(L, 2); lua_arith(L, LUA_OPSUB); lua_pushvalue(L, 1); lua_pushvalue(L, 2); lua_arith(L, LUA_OPMUL); lua_pushvalue(L, 1); lua_pushvalue(L, 2); lua_arith(L, LUA_OPDIV); lua_pushvalue(L, 1); lua_pushvalue(L, 2); lua_arith(L, LUA_OPMOD); lua_pushvalue(L, 1); lua_pushvalue(L, 2); lua_arith(L, LUA_OPPOW); lua_pushvalue(L, 1); lua_arith(L, LUA_OPUNM); return lua_gettop(L)-2; } static int test_globals (lua_State *L) { lua_pushglobaltable(L); return 1; } static int test_tonumber (lua_State *L) { int isnum = 0; lua_Number n = lua_tonumberx(L, 1, &isnum); if (!isnum) lua_pushnil(L); else lua_pushnumber(L, n); return 1; } static int test_tointeger (lua_State *L) { int isnum = 0; lua_Integer n = lua_tointegerx(L, 1, &isnum); if (!isnum) lua_pushnil(L); else lua_pushinteger(L, n); return 1; } static int test_unsigned (lua_State *L) { lua_Unsigned u = luaL_checkunsigned(L, 1); lua_Unsigned u2 = lua_tounsigned(L, 1); lua_pushunsigned(L, u); lua_pushboolean(L, u == u2); return 2; } static int test_optunsigned (lua_State *L) { lua_Unsigned u = luaL_optunsigned(L, 1, 17u); lua_pushunsigned(L, u); return 1; } static int test_len (lua_State *L) { luaL_checkany(L, 1); lua_len(L, 1); lua_pushinteger(L, luaL_len(L, 1)); return 2; } static int test_copy (lua_State *L) { int args = lua_gettop(L); if (args >= 2) { int i = 0; for (i = args-1; i > 0; --i) lua_copy(L, args, i); } return args; } /* need an address */ static char const dummy = 0; static int test_rawxetp (lua_State *L) { if (lua_gettop(L) > 0) lua_pushvalue(L, 1); else lua_pushliteral(L, "hello again"); lua_rawsetp(L, LUA_REGISTRYINDEX, &dummy); lua_settop(L, 0); lua_rawgetp(L, LUA_REGISTRYINDEX, &dummy); return 1; } static int test_udata (lua_State *L) { const char *tname = luaL_optstring(L, 1, "utype1"); void *u1 = lua_newuserdata(L, 1); int u1pos = lua_gettop(L); void *u2 = lua_newuserdata(L, 1); int u2pos = lua_gettop(L); luaL_newmetatable(L, "utype1"); luaL_newmetatable(L, "utype2"); lua_pop(L, 2); luaL_setmetatable(L, "utype2"); lua_pushvalue(L, u1pos); luaL_setmetatable(L, "utype1"); lua_pop(L, 1); (void)u1; (void)u2; lua_pushlightuserdata(L, luaL_testudata(L, u1pos, tname)); lua_pushlightuserdata(L, luaL_testudata(L, u2pos, tname)); return 2; } static int test_subtable (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 1); if (luaL_getsubtable(L, 1, "xxx")) { lua_pushliteral(L, "oldtable"); } else { lua_pushliteral(L, "newtable"); } return 2; } static int test_uservalue (lua_State *L) { void *udata = lua_newuserdata(L, 1); int ui = lua_gettop(L); lua_getuservalue(L, ui); lua_newtable(L); lua_setuservalue(L, ui); lua_getuservalue(L, ui); lua_pushnil(L); lua_setuservalue(L, ui); lua_getuservalue(L, ui); (void)udata; return 3; } static int test_upvalues (lua_State *L) { int i = 1; for (i = 1; i <= NUP; ++i) lua_pushvalue(L, lua_upvalueindex(i)); return NUP; } static int test_tolstring (lua_State *L) { size_t len = 0; luaL_tolstring(L, 1, &len); lua_pushinteger(L, (int)len); return 2; } static int my_mod (lua_State *L) { lua_newtable(L); lua_pushboolean(L, 1); lua_setfield(L, -2, "boolean"); return 1; } static int test_requiref (lua_State *L) { luaL_requiref(L, "requiref1", my_mod, 0); luaL_requiref(L, "requiref2", my_mod, 1); return 2; } static int test_buffer (lua_State *L) { luaL_Buffer b; char *p = luaL_buffinitsize(L, &b, LUAL_BUFFERSIZE+1); p[0] = 'a'; p[1] = 'b'; luaL_addsize(&b, 2); luaL_addstring(&b, "c"); lua_pushliteral(L, "d"); luaL_addvalue(&b); luaL_addchar(&b, 'e'); luaL_pushresult(&b); return 1; } static const luaL_Reg funcs[] = { { "newproxy", test_newproxy }, { "compare", test_compare }, { "arith", test_arith }, { "tonumber", test_tonumber }, { "tointeger", test_tointeger }, { "unsigned", test_unsigned }, { "optunsigned", test_optunsigned }, { "len", test_len }, { "copy", test_copy }, { "rawxetp", test_rawxetp }, { "subtable", test_subtable }, { "udata", test_udata }, { "uservalue", test_uservalue }, { "globals", test_globals }, { "tolstring", test_tolstring }, { "requiref", test_requiref }, { "buffer", test_buffer }, { NULL, NULL } }; static const luaL_Reg more_funcs[] = { { "getupvalues", test_upvalues }, { "absindex", test_absindex }, { NULL, NULL } }; int luaopen_testmod (lua_State *L) { int i = 1; luaL_newlib(L, funcs); /* defeats the purpose of luaL_newlib, but this is test code: */ for (i = 1; i <= NUP; ++i) lua_pushnumber(L, i); luaL_setfuncs(L, more_funcs, NUP); return 1; }