[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Bit manipulation functions (was: More on environments and objects)
- From: Mike Pall <mikelu-0508@...>
- Date: Sat, 27 Aug 2005 19:27:02 +0200
Hi,
Rici Lake wrote:
> >- Hex numbers (parser + luaO_str2d with strtol fallback for non-C99)
>
> Agreed.
>
> >- Missing bit operations (math.*)
>
> I'd put bit operations in string.*, not math.*. We can argue about this
> after 5.1 comes out.
I really want them for manipulating bits in numbers, not for
arbitrary-length bit strings. That's why I mentioned hex
numbers first. Limiting this to int32 is just fine for me
(e.g. for interfacing with C or certain low-level calculations).
[
The underlying type for arbitrary-length bit strings depends
a lot on your usage patterns, but userdata seems to be more
apropriate IMHO. I'd see this more as a small part of an
arbitrary-precision math module (like the GMP binding).
]
But hex numbers and simple bit manipulation could/should be
within the scope of Lua 5.1 IMHO. I already explained how to
do the former. The latter would look something like:
static int math_bitor (lua_State *L) {
lua_pushinteger(L, luaL_checkinteger(L, 1) | luaL_checkinteger(L, 2));
return 1;
}
static int math_bitand (lua_State *L) { /* aka tobit */
lua_pushinteger(L, luaL_checkinteger(L, 1) & luaL_optinteger(L, 2, -1));
return 1;
}
static int math_bitxor (lua_State *L) { /* aka bitnot */
lua_pushinteger(L, luaL_checkinteger(L, 1) ^ luaL_optinteger(L, 2, -1));
return 1;
}
#define LI_BITS (sizeof(lua_Integer)*8)
#define LI_MASK(m) (~(((lua_Integer)-1) << (m)))
static int math_bitfield (lua_State *L) { /* aka bitshift */
lua_Integer i = luaL_checkinteger(L, 1);
int start = luaL_checkinteger(L, 2);
int len = luaL_optinteger(L, 3, LI_BITS);
if (start > 0) i = (i >> start) & LI_MASK(LI_BITS - start);
if (len < LI_BITS) i &= LI_MASK(len);
if (start < 0) i <<= -start;
lua_pushinteger(L, i);
return 1;
}
That's all!
I can live without bit operators, but bit manipulation functions
would come real handy. I'm pretty sure they would get used more
often than math.tanh(). ;-)
Bye,
Mike