From 1a33ad9dc2669663fd6173644771ec257d3cde0e Mon Sep 17 00:00:00 2001 From: Ilari Liusvaara Date: Wed, 7 Mar 2012 12:35:46 +0200 Subject: [PATCH] Lua: bit.extract --- manual.lyx | 22 ++++++++++++++++++++++ manual.txt | 13 +++++++++++++ src/lua/bit.cpp | 17 +++++++++++++++++ 3 files changed, 52 insertions(+) diff --git a/manual.lyx b/manual.lyx index e272a37b..b568e904 100644 --- a/manual.lyx +++ b/manual.lyx @@ -2141,6 +2141,28 @@ Shift bits-bit (max 48, default 48) number arithmetically right by amount The new bits are shifted in with copy of the high bit. \end_layout +\begin_layout Subsubsection +bit.extract(number base[, number bit0[, number bit1,...]]) +\end_layout + +\begin_layout Standard +Returns number that has bit0-th bit as bit 0, bit1-th bit as 1 and so on. +\end_layout + +\begin_layout Standard +Notes: +\end_layout + +\begin_layout Itemize +Bit numbers up to 51 should work reliably (then things start falling apart + due to double precision issues). +\end_layout + +\begin_layout Itemize +There are two special bit positions, true and false, standing for always + set bit and always clear bit. +\end_layout + \begin_layout Subsection Table gui: \end_layout diff --git a/manual.txt b/manual.txt index 26b12e2b..b0341459 100644 --- a/manual.txt +++ b/manual.txt @@ -1041,6 +1041,19 @@ Shift bits-bit (max 48, default 48) number arithmetically right by amount (default 1) places. The new bits are shifted in with copy of the high bit. +8.2.10 bit.extract(number base[, number bit0[, number bit1,...]]) + +Returns number that has bit0-th bit as bit 0, bit1-th bit as 1 +and so on. + +Notes: + +• Bit numbers up to 51 should work reliably (then things start + falling apart due to double precision issues). + +• There are two special bit positions, true and false, standing + for always set bit and always clear bit. + 8.3 Table gui: Most of these functions can only be called in on_paint and diff --git a/src/lua/bit.cpp b/src/lua/bit.cpp index 109d76b1..abf6dc8d 100644 --- a/src/lua/bit.cpp +++ b/src/lua/bit.cpp @@ -102,6 +102,23 @@ namespace } }; + function_ptr_luafun lua_print("bit.extract", [](lua_State* LS, const std::string& fname) -> int { + uint64_t num = get_numeric_argument(LS, 1, fname.c_str()); + uint64_t ret = 0; + for(size_t i = 0;; i++) { + if(lua_isnumber(LS, i + 2)) { + uint8_t bit = get_numeric_argument(LS, i + 2, fname.c_str()); + ret |= (((num >> bit) & 1) << i); + } else if(lua_isboolean(LS, i + 2)) { + if(lua_toboolean(LS, i + 2)) + ret |= (1ULL << i); + } else + break; + } + lua_pushnumber(LS, ret); + return 1; + }); + lua_symmetric_bitwise bit_none("bit.none"); lua_symmetric_bitwise bit_bnot("bit.bnot"); lua_symmetric_bitwise bit_any("bit.any");