37 Commits

Author SHA1 Message Date
rxi
076ca7972c Version 1.3.1 2014-04-23 20:11:00 +01:00
rxi
c2311f9821 Added missing tostring() call on args in lume.trace() 2014-04-19 09:06:33 +01:00
rxi
beced85d6b Updated test for lume.trace() 2014-04-18 19:16:33 +01:00
rxi
8a2765a41b Fixed lume.trace() to handle and print nil argument 2014-04-18 19:15:13 +01:00
rxi
09847bd266 Version 1.3.0 2014-04-17 20:52:54 +01:00
rxi
841cee30e1 Added another test for lume.slice() 2014-04-17 12:30:19 +01:00
rxi
cd3c0a1eea Made callable tables be accepted as functions 2014-04-17 12:13:50 +01:00
rxi
3190d65130 Removed use of math.min and math.max in lume.slice() 2014-04-17 12:07:59 +01:00
rxi
c7471b32fb Changed lume.uuid() to use local math_random() 2014-04-05 23:08:03 +01:00
rxi
bb56f1ce3a Added missing comment for lume.uuid func in test_lua.lua 2014-04-05 16:37:05 +01:00
rxi
098754056a Added tests for lume.chain() 2014-04-05 16:35:53 +01:00
rxi
330779fb0f Added lume.chain(), added section to README.md 2014-04-05 16:30:10 +01:00
rxi
acdb58a447 Added lume.uuid(), tests and README.md section 2014-04-05 14:41:31 +01:00
rxi
88b428cb4d Added lume.count() to README.md 2014-04-05 12:21:36 +01:00
rxi
fdf01937e2 Added lume.count() function and tests 2014-04-05 12:11:41 +01:00
rxi
3a4ce4fe3b Added type check in lume.fn() and additional tests 2014-04-04 18:38:36 +01:00
rxi
1a087efe99 Added lume.match() to README.md 2014-04-04 18:21:21 +01:00
rxi
9a82d6318e Added tests for lume.match() 2014-04-04 18:09:23 +01:00
rxi
30991649f8 Added lume.match() 2014-04-04 18:08:39 +01:00
rxi
dbd93b3861 Moved position of lume.combine() in readme and other files 2014-04-03 20:17:31 +01:00
rxi
8311519e3f Added test for lume.combine() to test_lume.lua 2014-04-03 20:10:08 +01:00
rxi
82c697b08e Added lume.combine() to README.md 2014-04-03 20:09:56 +01:00
rxi
5db6be936a Added lume.combine() function 2014-04-03 20:09:40 +01:00
rxi
335b928cae Removed function in lume.slice()
Moved the function index() from lume.slice()'s body to local var
absindex, this improves the performance of lume.slice() on luajit
significantly and improves it to a lesser extent on non-jit lua.
2014-04-01 20:16:39 +01:00
rxi
94977b4f7e Updated test for lume.trace() 2014-03-30 18:38:45 +01:00
rxi
e6246834b7 Changed lume.trace() to round numbers to 2 decimal places 2014-03-30 18:31:14 +01:00
rxi
9bf2d24ee2 table.unpack() is now used if unpack() is not available. 2014-03-29 10:02:48 +00:00
rxi
89931c1ad8 Version 1.2.1 2014-03-27 17:57:19 +00:00
rxi
9ff4637201 Moved shared code of lume.split/trim() to local func 2014-03-19 21:05:34 +00:00
rxi
617729e261 Added more tests for lume.trim() 2014-03-19 20:18:32 +00:00
rxi
ad64d7af05 Fixed use of pattern special chars in lume.trim()
Using lua pattern special chars in the `chars` argument of lume.trim()
are now handled correctly and treated like any other character.
2014-03-19 20:14:48 +00:00
rxi
d69f419f5a Improved lume.split()'s README.md section for clarity 2014-03-19 19:49:50 +00:00
rxi
ad34f6ce33 Updated lume.split() in README.md 2014-03-19 13:02:55 +00:00
rxi
5882ca1303 Fixed minor error in lume.set()'s README.md example 2014-03-19 12:54:14 +00:00
rxi
828d23e6f6 Added new tests and updated some others for lume.split() 2014-03-19 12:53:01 +00:00
rxi
13a8edb2e7 Changed lume.split() to mimic python's str.split()
The lume.split() function now mimics python's str.split() function,
though it does not support the third argument (maxsplit)
2014-03-19 12:51:35 +00:00
rxi
425a52b99f Fixed spelling mistake in README.md 2014-03-18 18:01:12 +00:00
3 changed files with 205 additions and 25 deletions

View File

@@ -130,7 +130,7 @@ Returns a copy of the `t` table with all the duplicate values removed. If
`retainkeys` is true the table is not treated as an array and retains its `retainkeys` is true the table is not treated as an array and retains its
original keys. original keys.
```lua ```lua
lume.set({2, 1, 2, "cat", "cat"}) -- Returns {1, 2, cat} lume.set({2, 1, 2, "cat", "cat"}) -- Returns {1, 2, "cat"}
``` ```
### lume.filter(t, fn [, retainkeys]) ### lume.filter(t, fn [, retainkeys])
@@ -156,6 +156,21 @@ exist in the table.
lume.find({"a", "b", "c"}, "b") -- Returns 2 lume.find({"a", "b", "c"}, "b") -- Returns 2
``` ```
### lume.match(t, fn)
Returns the value and key of the value in table `t` which returns true when
`fn` is called on it. Returns `nil` if no such value exists.
```lua
lume.match({1, 5, 8, 7}, function(x) return x % 2 == 0 end) -- Returns 8, 3
```
### lume.count(t [, fn])
Counts the number of values in the table `t`. If a `fn` function is supplied it
is called on each value, the number of times it returns true is counted.
```lua
lume.count({a = 2, b = 3, c = 4, d = 5}) -- Returns 4
lume.count({1, 2, 4, 6}, function(x) return x % 2 == 0 end) -- Returns 3
```
### lume.slice(t [, i [, j]]) ### lume.slice(t [, i [, j]])
Mimics the behaviour of Lua's `string.sub`, but operates on an array rather Mimics the behaviour of Lua's `string.sub`, but operates on an array rather
than a string. Creates and returns a new array of the given slice. than a string. Creates and returns a new array of the given slice.
@@ -200,9 +215,19 @@ seconds the function `fn` took to execute followed by `fn`'s returned values.
lume.time(function(x) return x end, "hello") -- Returns 0, "hello" lume.time(function(x) return x end, "hello") -- Returns 0, "hello"
``` ```
### lume.combine(...)
Creates a wrapper function which calls each supplied argument in the order they
were passed to `lume.combine`. The wrapper function passes its own arguments to
each of its wrapped functions when it is called.
```lua
local f = lume.combine(function(a, b) print(a + b) end,
function(a, b) print(a * b) end)
f(3, 4) -- Prints "7" then "12" on a new line
```
### lume.lambda(str) ### lume.lambda(str)
Takes a string lambda and returns a function. `str` should be a list of Takes a string lambda and returns a function. `str` should be a list of
comma-seperated parameters, followed by `->`, followed by the expression which comma-separated parameters, followed by `->`, followed by the expression which
will be evaluated and returned. will be evaluated and returned.
```lua ```lua
local f = lume.lambda "x,y -> 2*x+y" local f = lume.lambda "x,y -> 2*x+y"
@@ -227,11 +252,12 @@ lume.deserialize("{1, 2, 3}") -- Returns {1, 2, 3}
``` ```
### lume.split(str [, sep]) ### lume.split(str [, sep])
Splits the string `str` into words and returns a table of the sub strings. If Returns an array of the words in the string `str`. If `sep` is provided it is
`sep` is provided the string will be split at any of the characters in `sep` used as the delimiter, consecutive delimiters are not grouped together and will
instead of on whitespace. delimit empty strings.
```lua ```lua
lume.split("One two three") -- Returns {"One", "two", "three"} lume.split("One two three") -- Returns {"One", "two", "three"}
lume.split("a,b,,c", ",") -- Returns {"a", "b", "", "c"}
``` ```
### lume.trim(str [, chars]) ### lume.trim(str [, chars])
@@ -265,6 +291,10 @@ Executes the lua code inside `str`.
lume.dostring("print('Hello!')") -- Prints "Hello!" lume.dostring("print('Hello!')") -- Prints "Hello!"
``` ```
### lume.uuid()
Generates a random UUID string; version 4 as specified in
[RFC 4122](http://www.ietf.org/rfc/rfc4122.txt).
### lume.hotswap(modname) ### lume.hotswap(modname)
Reloads an already loaded module in place, allowing you to immediately see the Reloads an already loaded module in place, allowing you to immediately see the
effects of code changes without having to restart the program. `modname` should effects of code changes without having to restart the program. `modname` should
@@ -284,6 +314,17 @@ arguments to [LÖVE](http://love2d.org)'s setColor() function.
lume.rgba(0xFF304050) -- Returns 48, 64, 80, 255 lume.rgba(0xFF304050) -- Returns 48, 64, 80, 255
``` ```
### lume.chain(value)
Returns a wrapped object which allows chaining of lume functions. The function
result() should be called at the end of the chain to return the resulting
value.
```lua
lume.chain({1, 2, 3, 4})
:filter(function(x) return x % 2 == 0 end)
:map(function(x) return -x end)
:result() -- Returns { -2, -4 }
```
## License ## License

104
lume.lua
View File

@@ -7,10 +7,10 @@
-- under the terms of the MIT license. See LICENSE for details. -- under the terms of the MIT license. See LICENSE for details.
-- --
local lume = { _version = "1.2.0" } local lume = { _version = "1.3.1" }
local pairs, ipairs = pairs, ipairs local pairs, ipairs = pairs, ipairs
local type, assert, unpack = type, assert, unpack local type, assert, unpack = type, assert, unpack or table.unpack
local tostring, tonumber = tostring, tonumber local tostring, tonumber = tostring, tonumber
local math_floor = math.floor local math_floor = math.floor
local math_ceil = math.ceil local math_ceil = math.ceil
@@ -19,10 +19,21 @@ local math_cos = math.cos
local math_atan2 = math.atan2 local math_atan2 = math.atan2
local math_sqrt = math.sqrt local math_sqrt = math.sqrt
local math_abs = math.abs local math_abs = math.abs
local math_min = math.min
local math_max = math.max
local math_pi = math.pi local math_pi = math.pi
local patternescape = function(str)
return str:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%1")
end
local absindex = function(len, i)
return i < 0 and (len + i + 1) or i
end
local iscallable = function(x)
return type(x) == "function" or getmetatable(x).__call ~= nil
end
function lume.clamp(x, min, max) function lume.clamp(x, min, max)
return x < min and min or (x > max and max or x) return x < min and min or (x > max and max or x)
@@ -189,13 +200,33 @@ function lume.find(t, value)
end end
function lume.match(t, fn)
for k, v in pairs(t) do
if fn(v) then return v, k end
end
return nil
end
function lume.count(t, fn)
local count = 0
if fn then
for k, v in pairs(t) do
if fn(v) then count = count + 1 end
end
else
for k in pairs(t) do count = count + 1 end
end
return count
end
function lume.slice(t, i, j) function lume.slice(t, i, j)
local function index(x) return x < 0 and (#t + x + 1) or x end i = i and absindex(#t, i) or 1
i = i and index(i) or 1 j = j and absindex(#t, j) or #t
j = j and index(j) or #t
local rtn = {} local rtn = {}
for i = math_max(i, 1), math_min(j, #t) do for x = i < 1 and 1 or i, j > #t and #t or j do
rtn[#rtn + 1] = t[i] rtn[#rtn + 1] = t[x]
end end
return rtn return rtn
end end
@@ -216,6 +247,7 @@ end
function lume.fn(fn, ...) function lume.fn(fn, ...)
assert(iscallable(fn), "expected a function as the first argument")
local args = {...} local args = {...}
return function(...) return function(...)
local a = lume.merge(lume.clone(args), {...}) local a = lume.merge(lume.clone(args), {...})
@@ -242,6 +274,15 @@ function lume.time(fn, ...)
end end
function lume.combine(...)
local funcs = {...}
assert(lume.all(funcs, iscallable), "expected all arguments to be functions")
return function(...)
for _, f in ipairs(funcs) do f(...) end
end
end
local lambda_cache = {} local lambda_cache = {}
function lume.lambda(str) function lume.lambda(str)
@@ -277,12 +318,19 @@ end
function lume.split(str, sep) function lume.split(str, sep)
return lume.array(str:gmatch("([^" .. (sep or "%s") .. "]+)")) if not sep then
return lume.array(str:gmatch("([%S]+)"))
else
assert(sep ~= "", "empty separator")
local psep = patternescape(sep)
return lume.array((str..sep):gmatch("(.-)("..psep..")"))
end
end end
function lume.trim(str, chars) function lume.trim(str, chars)
chars = chars or "%s" if not chars then return str:match("^[%s]*(.-)[%s]*$") end
chars = patternescape(chars)
return str:match("^[" .. chars .. "]*(.-)[" .. chars .. "]*$") return str:match("^[" .. chars .. "]*(.-)[" .. chars .. "]*$")
end end
@@ -298,8 +346,13 @@ end
function lume.trace(...) function lume.trace(...)
local info = debug.getinfo(2, "Sl") local info = debug.getinfo(2, "Sl")
local head = "[" .. info.short_src .. ":" .. info.currentline .. "] " local t = { "[" .. info.short_src .. ":" .. info.currentline .. "]" }
print(head .. table.concat(lume.map({...}, tostring), " ")) for i = 1, select("#", ...) do
local x = select(i, ...)
x = (type(x) == "number") and lume.round(x, .01) or (x or "nil")
t[#t + 1] = tostring(x)
end
print(table.concat(t, " "))
end end
@@ -308,6 +361,16 @@ function lume.dostring(str)
end end
function lume.uuid()
local fn = function(x)
local r = math_random(16) - 1
r = (x == "x") and (r + 1) or (r % 4) + 9
return ("0123456789abcdef"):sub(r, r)
end
return (("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"):gsub("[xy]", fn))
end
function lume.hotswap(modname) function lume.hotswap(modname)
local oldglobal = lume.clone(_G) local oldglobal = lume.clone(_G)
local updated = {} local updated = {}
@@ -353,4 +416,19 @@ function lume.rgba(color)
end end
local chain_mt = {}
chain_mt.__index = lume.map(lume.filter(lume, iscallable, true),
function(fn)
return function(self, ...)
self._value = fn(self._value, ...)
return self
end
end)
chain_mt.__index.result = function(x) return x._value end
function lume.chain(value)
return setmetatable({ _value = value }, chain_mt)
end
return lume return lume

View File

@@ -204,6 +204,33 @@ tests["lume.find"] = function()
testeq( lume.find({a=1, b=5, c=7}, 5), "b" ) testeq( lume.find({a=1, b=5, c=7}, 5), "b" )
end end
-- lume.match
tests["lume.match"] = function()
local t = { "a", "b", "c", "d" }
local t2 = { a = 1, b = 2, c = 3, d = 4 }
local v, k = lume.match(t, function(x) return x > "c" end)
testeq( v, "d" )
testeq( k, 4 )
local v, k = lume.match(t, function(x) return x < "b" end)
testeq( v, "a" )
testeq( k, 1 )
local v, k = lume.match(t2, function(x) return x < 2 end)
testeq( v, 1 )
testeq( k, "a" )
local v, k = lume.match(t2, function(x) return x > 5 end)
testeq( v, nil )
testeq( k, nil )
end
-- lume.count
tests["lume.count"] = function()
local t = { a = 1, b = 2, c = 5, [13] = 22, z = 8 }
testeq( lume.count(t), 5 )
testeq( lume.count(t, function(x) return x % 2 == 0 end ), 3 )
local a = { 5, 6, 7, 8, 9 }
testeq( lume.count(a), #a )
end
-- lume.slice -- lume.slice
tests["lume.slice"] = function() tests["lume.slice"] = function()
testeq( lume.slice({"a", "b", "c", "d", "e"}, 2, 4), {"b", "c", "d"} ) testeq( lume.slice({"a", "b", "c", "d", "e"}, 2, 4), {"b", "c", "d"} )
@@ -218,6 +245,7 @@ tests["lume.slice"] = function()
testeq( lume.slice({"a", "b", "c", "d", "e"}, 0, 1), {"a"} ) testeq( lume.slice({"a", "b", "c", "d", "e"}, 0, 1), {"a"} )
testeq( lume.slice({"a", "b", "c", "d", "e"}, 0, 0), {} ) testeq( lume.slice({"a", "b", "c", "d", "e"}, 0, 0), {} )
testeq( lume.slice({"a", "b", "c", "d", "e"}, -3), {"c", "d", "e"} ) testeq( lume.slice({"a", "b", "c", "d", "e"}, -3), {"c", "d", "e"} )
testeq( lume.slice({"a", "b", "c", "d", "e"}, -3, 900), {"c", "d", "e"} )
end end
-- lume.invert -- lume.invert
@@ -240,6 +268,7 @@ end
tests["lume.fn"] = function() tests["lume.fn"] = function()
local f = lume.fn(function(a, b) return a + b end, 10) local f = lume.fn(function(a, b) return a + b end, 10)
testeq( f(5), 15 ) testeq( f(5), 15 )
tester.test.error( lume.fn, 123 )
end end
-- lume.once -- lume.once
@@ -247,6 +276,7 @@ tests["lume.once"] = function()
local f = lume.once(function(a, b) return a + b end, 10) local f = lume.once(function(a, b) return a + b end, 10)
testeq( f(5), 15 ) testeq( f(5), 15 )
testeq( f(5), nil ) testeq( f(5), nil )
tester.test.error( lume.once, 123 )
end end
-- lume.time -- lume.time
@@ -256,6 +286,16 @@ tests["lume.time"] = function()
testeq( {a, b, c}, {50, 60, 70} ) testeq( {a, b, c}, {50, 60, 70} )
end end
-- lume.combine
tests["lume.combine"] = function()
local acc = 0
local a = function(x, y) acc = acc + x + y end
local b = function(x, y) acc = acc + x * y end
local fn = lume.combine(a, b)
fn(10, 20)
testeq( acc, 230 )
end
-- lume.lambda -- lume.lambda
tests["lume.lambda"] = function() tests["lume.lambda"] = function()
testeq( lume.lambda "x->x*x"(10), 100 ) testeq( lume.lambda "x->x*x"(10), 100 )
@@ -280,9 +320,15 @@ end
-- lume.split -- lume.split
tests["lume.split"] = function() tests["lume.split"] = function()
testeq( lume.split("cat dog pig"), {"cat", "dog", "pig"} ) testeq( lume.split("cat dog pig"), {"cat", "dog", "pig"} )
testeq( lume.split(",cat,dog,pig", ","), {"cat", "dog", "pig"} ) testeq( lume.split("cat,dog,pig", ","), {"cat", "dog", "pig"} )
testeq( lume.split(",cat,dog;pig", ",;"), {"cat", "dog", "pig"} ) testeq( lume.split("cat,dog;pig", ";"), {"cat,dog", "pig"} )
testeq( lume.split("cat,dog,,pig", ","), {"cat", "dog", "", "pig"} )
testeq( lume.split(";;;cat;", ";"), {"", "", "", "cat", ""} )
testeq( lume.split("cat.dog", "."), {"cat", "dog"} )
testeq( lume.split("cat%dog", "%"), {"cat", "dog"} )
testeq( lume.split("1<>2<>3", "<>"), {"1", "2", "3"} )
tester.test.error( lume.split, "abc", "" )
end end
-- lume.trim -- lume.trim
@@ -290,6 +336,8 @@ tests["lume.trim"] = function()
testeq( lume.trim(" hello world "), "hello world" ) testeq( lume.trim(" hello world "), "hello world" )
testeq( lume.trim("-=-hello-world===", "-="), "hello-world" ) testeq( lume.trim("-=-hello-world===", "-="), "hello-world" )
testeq( lume.trim("***hello world*-*", "*"), "hello world*-" ) testeq( lume.trim("***hello world*-*", "*"), "hello world*-" )
testeq( lume.trim("...hello world.", "."), "hello world" )
testeq( lume.trim("^.hello world]^", "^.]"), "hello world" )
end end
-- lume.format -- lume.format
@@ -311,11 +359,11 @@ tests["lume.trace"] = function()
print = function(x) print = function(x)
file, line, msg = x:match("%[(.-):(.-)%] (.*)") file, line, msg = x:match("%[(.-):(.-)%] (.*)")
end end
lume.trace("Hi world") lume.trace("Hi world", 123.456, 1, nil)
print = oldprint print = oldprint
testeq( file:match(".lua$"), ".lua" ) testeq( file:match(".lua$"), ".lua" )
testeq( tonumber(line) ~= nil, true ) testeq( tonumber(line) ~= nil, true )
testeq( msg, "Hi world" ) testeq( msg, "Hi world 123.46 1 nil" )
end end
-- lume.dostring -- lume.dostring
@@ -324,6 +372,12 @@ tests["lume.dostring"] = function()
testeq( lume.dostring([[return 12345]]), 12345 ) testeq( lume.dostring([[return 12345]]), 12345 )
end end
-- lume.uuid
tests["lume.uuid"] = function()
testeq( type(lume.uuid()), "string" )
testeq( #lume.uuid(), 36 )
end
-- lume.hotswap -- lume.hotswap
tests["lume.hotswap"] = function() tests["lume.hotswap"] = function()
local ok, err = lume.hotswap("bad_module_name") local ok, err = lume.hotswap("bad_module_name")
@@ -340,6 +394,13 @@ tests["lume.rgba"] = function()
testeq( b, 0x78 ) testeq( b, 0x78 )
end end
-- lume.chain
tests["lume.chain"] = function()
local t = lume.chain({1, 2}):map(function(x) return x * 2 end):result()
testeq( t, { 2, 4 } )
testeq( lume.chain(10):result(), 10 )
end
tester.dotests(tests) tester.dotests(tests)
tester.test.global() tester.test.global()