summaryrefslogtreecommitdiff
path: root/luaextra-number.lua
diff options
context:
space:
mode:
authorKhaled Hosny <khaledhosny@eglug.org>2010-01-11 15:15:52 +0200
committerKhaled Hosny <khaledhosny@eglug.org>2010-01-11 16:03:13 +0200
commitf1c3cb9dc199c28cdd2c813eb1ea5c21345125d0 (patch)
tree808986ca292251a39a2fc9fa3a7e01b9e761577e /luaextra-number.lua
parente5ad063f805ecbf5fd093712bc60ef5aec25a6fd (diff)
downloadlualibs-f1c3cb9dc199c28cdd2c813eb1ea5c21345125d0.tar.gz
Import ConTeX's lua libraries
Replace most of luaextra.lua with a bunch of require() calls and add renamed (but unmodified) ConTeX lua libraries to the repository. ConTeXt's l-xml.lua module has been excluded because it depends on a bunch of other ConTeXt specific modules. Also l-pdfview.lua has been dropped, I don't know what to use it for.
Diffstat (limited to 'luaextra-number.lua')
-rw-r--r--luaextra-number.lua58
1 files changed, 58 insertions, 0 deletions
diff --git a/luaextra-number.lua b/luaextra-number.lua
new file mode 100644
index 0000000..a1249f0
--- /dev/null
+++ b/luaextra-number.lua
@@ -0,0 +1,58 @@
+if not modules then modules = { } end modules ['l-number'] = {
+ version = 1.001,
+ comment = "companion to luat-lib.mkiv",
+ author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
+ copyright = "PRAGMA ADE / ConTeXt Development Team",
+ license = "see context related readme files"
+}
+
+local tostring = tostring
+local format, floor, insert, match = string.format, math.floor, table.insert, string.match
+local lpegmatch = lpeg.match
+
+number = number or { }
+
+-- a,b,c,d,e,f = number.toset(100101)
+
+function number.toset(n)
+ return match(tostring(n),"(.?)(.?)(.?)(.?)(.?)(.?)(.?)(.?)")
+end
+
+function number.toevenhex(n)
+ local s = format("%X",n)
+ if #s % 2 == 0 then
+ return s
+ else
+ return "0" .. s
+ end
+end
+
+-- the lpeg way is slower on 8 digits, but faster on 4 digits, some 7.5%
+-- on
+--
+-- for i=1,1000000 do
+-- local a,b,c,d,e,f,g,h = number.toset(12345678)
+-- local a,b,c,d = number.toset(1234)
+-- local a,b,c = number.toset(123)
+-- end
+--
+-- of course dedicated "(.)(.)(.)(.)" matches are even faster
+
+local one = lpeg.C(1-lpeg.S(''))^1
+
+function number.toset(n)
+ return lpegmatch(one,tostring(n))
+end
+
+function number.bits(n,zero)
+ local t, i = { }, (zero and 0) or 1
+ while n > 0 do
+ local m = n % 2
+ if m > 0 then
+ insert(t,1,i)
+ end
+ n = floor(n/2)
+ i = i + 1
+ end
+ return t
+end