lume.lua 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. --
  2. -- lume
  3. --
  4. -- Copyright (c) 2015 rxi
  5. --
  6. -- This library is free software; you can redistribute it and/or modify it
  7. -- under the terms of the MIT license. See LICENSE for details.
  8. --
  9. local lume = { _version = "2.2.2" }
  10. local pairs, ipairs = pairs, ipairs
  11. local type, assert, unpack = type, assert, unpack or table.unpack
  12. local tostring, tonumber = tostring, tonumber
  13. local math_floor = math.floor
  14. local math_ceil = math.ceil
  15. local math_random = math.random
  16. local math_cos = math.cos
  17. local math_atan2 = math.atan2 or math.atan
  18. local math_sqrt = math.sqrt
  19. local math_abs = math.abs
  20. local math_pi = math.pi
  21. local noop = function()
  22. end
  23. local identity = function(x)
  24. return x
  25. end
  26. local patternescape = function(str)
  27. return str:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%1")
  28. end
  29. local absindex = function(len, i)
  30. return i < 0 and (len + i + 1) or i
  31. end
  32. local iscallable = function(x)
  33. if type(x) == "function" then return true end
  34. local mt = getmetatable(x)
  35. return mt and mt.__call ~= nil
  36. end
  37. local isarray = function(x)
  38. return (type(x) == "table" and x[1] ~= nil) and true or false
  39. end
  40. local getiter = function(x)
  41. if isarray(x) then
  42. return ipairs
  43. elseif type(x) == "table" then
  44. return pairs
  45. end
  46. error("expected table", 3)
  47. end
  48. local iteratee = function(x)
  49. if x == nil then return identity end
  50. if iscallable(x) then return x end
  51. if type(x) == "table" then
  52. return function(z)
  53. for k, v in pairs(x) do
  54. if z[k] ~= v then return false end
  55. end
  56. return true
  57. end
  58. end
  59. return function(z) return z[x] end
  60. end
  61. function lume.clamp(x, min, max)
  62. return x < min and min or (x > max and max or x)
  63. end
  64. function lume.round(x, increment)
  65. if increment then return lume.round(x / increment) * increment end
  66. return x >= 0 and math_floor(x + .5) or math_ceil(x - .5)
  67. end
  68. function lume.sign(x)
  69. return x < 0 and -1 or 1
  70. end
  71. function lume.lerp(a, b, amount)
  72. return a + (b - a) * lume.clamp(amount, 0, 1)
  73. end
  74. function lume.smooth(a, b, amount)
  75. local t = lume.clamp(amount, 0, 1)
  76. local m = t * t * (3 - 2 * t)
  77. return a + (b - a) * m
  78. end
  79. function lume.pingpong(x)
  80. return 1 - math_abs(1 - x % 2)
  81. end
  82. function lume.distance(x1, y1, x2, y2, squared)
  83. local dx = x1 - x2
  84. local dy = y1 - y2
  85. local s = dx * dx + dy * dy
  86. return squared and s or math_sqrt(s)
  87. end
  88. function lume.angle(x1, y1, x2, y2)
  89. return math_atan2(y2 - y1, x2 - x1)
  90. end
  91. function lume.random(a, b)
  92. if not a then a, b = 0, 1 end
  93. if not b then b = 0 end
  94. return a + math_random() * (b - a)
  95. end
  96. function lume.randomchoice(t)
  97. return t[math_random(#t)]
  98. end
  99. function lume.weightedchoice(t)
  100. local sum = 0
  101. for k, v in pairs(t) do
  102. assert(v >= 0, "weight value less than zero")
  103. sum = sum + v
  104. end
  105. assert(sum ~= 0, "all weights are zero")
  106. local rnd = lume.random(sum)
  107. for k, v in pairs(t) do
  108. if rnd < v then return k end
  109. rnd = rnd - v
  110. end
  111. end
  112. function lume.push(t, ...)
  113. local n = select("#", ...)
  114. for i = 1, n do
  115. t[#t + 1] = select(i, ...)
  116. end
  117. return ...
  118. end
  119. function lume.remove(t, x)
  120. local iter = getiter(t)
  121. for i, v in iter(t) do
  122. if v == x then
  123. if isarray(t) then
  124. table.remove(t, i)
  125. break
  126. else
  127. t[i] = nil
  128. break
  129. end
  130. end
  131. end
  132. return x
  133. end
  134. function lume.clear(t)
  135. local iter = getiter(t)
  136. for k, v in iter(t) do
  137. t[k] = nil
  138. end
  139. return t
  140. end
  141. function lume.extend(t, ...)
  142. for i = 1, select("#", ...) do
  143. local x = select(i, ...)
  144. if x then
  145. for k, v in pairs(x) do
  146. t[k] = v
  147. end
  148. end
  149. end
  150. return t
  151. end
  152. function lume.shuffle(t)
  153. local rtn = {}
  154. for i = 1, #t do
  155. local r = math_random(i)
  156. if r ~= i then
  157. rtn[i] = rtn[r]
  158. end
  159. rtn[r] = t[i]
  160. end
  161. return rtn
  162. end
  163. function lume.sort(t, comp)
  164. local rtn = lume.clone(t)
  165. if comp then
  166. if type(comp) == "string" then
  167. table.sort(rtn, function(a, b) return a[comp] < b[comp] end)
  168. else
  169. table.sort(rtn, comp)
  170. end
  171. else
  172. table.sort(rtn)
  173. end
  174. return rtn
  175. end
  176. function lume.array(...)
  177. local t = {}
  178. for x in ... do t[#t + 1] = x end
  179. return t
  180. end
  181. function lume.each(t, fn, ...)
  182. local iter = getiter(t)
  183. if type(fn) == "string" then
  184. for _, v in iter(t) do v[fn](v, ...) end
  185. else
  186. for _, v in iter(t) do fn(v, ...) end
  187. end
  188. return t
  189. end
  190. function lume.map(t, fn)
  191. fn = iteratee(fn)
  192. local iter = getiter(t)
  193. local rtn = {}
  194. for k, v in iter(t) do rtn[k] = fn(v) end
  195. return rtn
  196. end
  197. function lume.all(t, fn)
  198. fn = iteratee(fn)
  199. local iter = getiter(t)
  200. for k, v in iter(t) do
  201. if not fn(v) then return false end
  202. end
  203. return true
  204. end
  205. function lume.any(t, fn)
  206. fn = iteratee(fn)
  207. local iter = getiter(t)
  208. for k, v in iter(t) do
  209. if fn(v) then return true end
  210. end
  211. return false
  212. end
  213. function lume.reduce(t, fn, first)
  214. local acc = first
  215. local started = first and true or false
  216. local iter = getiter(t)
  217. for k, v in iter(t) do
  218. if started then
  219. acc = fn(acc, v)
  220. else
  221. acc = v
  222. started = true
  223. end
  224. end
  225. assert(started, "reduce of an empty table with no first value")
  226. return acc
  227. end
  228. function lume.set(t)
  229. local rtn = {}
  230. for k, v in pairs(lume.invert(t)) do
  231. rtn[#rtn + 1] = k
  232. end
  233. return rtn
  234. end
  235. function lume.filter(t, fn, retainkeys)
  236. fn = iteratee(fn)
  237. local iter = getiter(t)
  238. local rtn = {}
  239. if retainkeys then
  240. for k, v in iter(t) do
  241. if fn(v) then rtn[k] = v end
  242. end
  243. else
  244. for k, v in iter(t) do
  245. if fn(v) then rtn[#rtn + 1] = v end
  246. end
  247. end
  248. return rtn
  249. end
  250. function lume.reject(t, fn, retainkeys)
  251. fn = iteratee(fn)
  252. local iter = getiter(t)
  253. local rtn = {}
  254. if retainkeys then
  255. for k, v in iter(t) do
  256. if not fn(v) then rtn[k] = v end
  257. end
  258. else
  259. for k, v in iter(t) do
  260. if not fn(v) then rtn[#rtn + 1] = v end
  261. end
  262. end
  263. return rtn
  264. end
  265. function lume.merge(...)
  266. local rtn = {}
  267. for i = 1, select("#", ...) do
  268. local t = select(i, ...)
  269. local iter = getiter(t)
  270. for k, v in iter(t) do
  271. rtn[k] = v
  272. end
  273. end
  274. return rtn
  275. end
  276. function lume.concat(...)
  277. local rtn = {}
  278. for i = 1, select("#", ...) do
  279. local t = select(i, ...)
  280. if t ~= nil then
  281. local iter = getiter(t)
  282. for k, v in iter(t) do
  283. rtn[#rtn + 1] = v
  284. end
  285. end
  286. end
  287. return rtn
  288. end
  289. function lume.find(t, value)
  290. local iter = getiter(t)
  291. for k, v in iter(t) do
  292. if v == value then return k end
  293. end
  294. return nil
  295. end
  296. function lume.match(t, fn)
  297. fn = iteratee(fn)
  298. local iter = getiter(t)
  299. for k, v in iter(t) do
  300. if fn(v) then return v, k end
  301. end
  302. return nil
  303. end
  304. function lume.count(t, fn)
  305. local count = 0
  306. local iter = getiter(t)
  307. if fn then
  308. fn = iteratee(fn)
  309. for k, v in iter(t) do
  310. if fn(v) then count = count + 1 end
  311. end
  312. else
  313. if isarray(t) then
  314. return #t
  315. end
  316. for k in iter(t) do count = count + 1 end
  317. end
  318. return count
  319. end
  320. function lume.slice(t, i, j)
  321. i = i and absindex(#t, i) or 1
  322. j = j and absindex(#t, j) or #t
  323. local rtn = {}
  324. for x = i < 1 and 1 or i, j > #t and #t or j do
  325. rtn[#rtn + 1] = t[x]
  326. end
  327. return rtn
  328. end
  329. function lume.first(t, n)
  330. if not n then return t[1] end
  331. return lume.slice(t, 1, n)
  332. end
  333. function lume.last(t, n)
  334. if not n then return t[#t] end
  335. return lume.slice(t, -n, -1)
  336. end
  337. function lume.invert(t)
  338. local rtn = {}
  339. for k, v in pairs(t) do rtn[v] = k end
  340. return rtn
  341. end
  342. function lume.pick(t, ...)
  343. local rtn = {}
  344. for i = 1, select("#", ...) do
  345. local k = select(i, ...)
  346. rtn[k] = t[k]
  347. end
  348. return rtn
  349. end
  350. function lume.keys(t)
  351. local rtn = {}
  352. local iter = getiter(t)
  353. for k, v in iter(t) do rtn[#rtn + 1] = k end
  354. return rtn
  355. end
  356. function lume.clone(t)
  357. local rtn = {}
  358. for k, v in pairs(t) do rtn[k] = v end
  359. return rtn
  360. end
  361. function lume.fn(fn, ...)
  362. assert(iscallable(fn), "expected a function as the first argument")
  363. local args = { ... }
  364. return function(...)
  365. local a = lume.concat(args, { ... })
  366. return fn(unpack(a))
  367. end
  368. end
  369. function lume.once(fn, ...)
  370. local fn = lume.fn(fn, ...)
  371. local done = false
  372. return function(...)
  373. if done then return end
  374. done = true
  375. return fn(...)
  376. end
  377. end
  378. local memoize_fnkey = {}
  379. local memoize_nil = {}
  380. function lume.memoize(fn)
  381. local cache = {}
  382. return function(...)
  383. local c = cache
  384. for i = 1, select("#", ...) do
  385. local a = select(i, ...) or memoize_nil
  386. c[a] = c[a] or {}
  387. c = c[a]
  388. end
  389. c[memoize_fnkey] = c[memoize_fnkey] or {fn(...)}
  390. return unpack(c[memoize_fnkey])
  391. end
  392. end
  393. function lume.combine(...)
  394. local n = select('#', ...)
  395. if n == 0 then return noop end
  396. if n == 1 then
  397. local fn = select(1, ...)
  398. if not fn then return noop end
  399. assert(iscallable(fn), "expected a function or nil")
  400. return fn
  401. end
  402. local funcs = {}
  403. for i = 1, n do
  404. local fn = select(i, ...)
  405. if fn ~= nil then
  406. assert(iscallable(fn), "expected a function or nil")
  407. funcs[#funcs + 1] = fn
  408. end
  409. end
  410. return function(...)
  411. for _, f in ipairs(funcs) do f(...) end
  412. end
  413. end
  414. function lume.call(fn, ...)
  415. if fn then
  416. return fn(...)
  417. end
  418. end
  419. function lume.time(fn, ...)
  420. local start = os.clock()
  421. local rtn = {fn(...)}
  422. return (os.clock() - start), unpack(rtn)
  423. end
  424. local lambda_cache = {}
  425. function lume.lambda(str)
  426. if not lambda_cache[str] then
  427. local args, body = str:match([[^([%w,_ ]-)%->(.-)$]])
  428. assert(args and body, "bad string lambda")
  429. local s = "return function(" .. args .. ")\nreturn " .. body .. "\nend"
  430. lambda_cache[str] = lume.dostring(s)
  431. end
  432. return lambda_cache[str]
  433. end
  434. local serialize
  435. local serialize_map = {
  436. [ "boolean" ] = tostring,
  437. [ "nil" ] = tostring,
  438. [ "string" ] = function(v) return string.format("%q", v) end,
  439. [ "number" ] = function(v)
  440. if v ~= v then return "0/0" -- nan
  441. elseif v == 1 / 0 then return "1/0" -- inf
  442. elseif v == -1 / 0 then return "-1/0" end -- -inf
  443. return tostring(v)
  444. end,
  445. [ "table" ] = function(t, stk)
  446. stk = stk or {}
  447. if stk[t] then error("circular reference") end
  448. local rtn = {}
  449. stk[t] = true
  450. for k, v in pairs(t) do
  451. rtn[#rtn + 1] = "[" .. serialize(k, stk) .. "]=" .. serialize(v, stk)
  452. end
  453. stk[t] = nil
  454. return "{" .. table.concat(rtn, ",") .. "}"
  455. end
  456. }
  457. setmetatable(serialize_map, {
  458. __index = function(t, k) error("unsupported serialize type: " .. k) end
  459. })
  460. serialize = function(x, stk)
  461. return serialize_map[type(x)](x, stk)
  462. end
  463. function lume.serialize(x)
  464. return serialize(x)
  465. end
  466. function lume.deserialize(str)
  467. return lume.dostring("return " .. str)
  468. end
  469. function lume.split(str, sep)
  470. if not sep then
  471. return lume.array(str:gmatch("([%S]+)"))
  472. else
  473. assert(sep ~= "", "empty separator")
  474. local psep = patternescape(sep)
  475. return lume.array((str..sep):gmatch("(.-)("..psep..")"))
  476. end
  477. end
  478. function lume.trim(str, chars)
  479. if not chars then return str:match("^[%s]*(.-)[%s]*$") end
  480. chars = patternescape(chars)
  481. return str:match("^[" .. chars .. "]*(.-)[" .. chars .. "]*$")
  482. end
  483. function lume.wordwrap(str, limit)
  484. limit = limit or 72
  485. local check
  486. if type(limit) == "number" then
  487. check = function(str) return #str >= limit end
  488. else
  489. check = limit
  490. end
  491. local rtn = {}
  492. local line = ""
  493. for word, spaces in str:gmatch("(%S+)(%s*)") do
  494. local str = line .. word
  495. if check(str) then
  496. table.insert(rtn, line .. "\n")
  497. line = word
  498. else
  499. line = str
  500. end
  501. for c in spaces:gmatch(".") do
  502. if c == "\n" then
  503. table.insert(rtn, line .. "\n")
  504. line = ""
  505. else
  506. line = line .. c
  507. end
  508. end
  509. end
  510. table.insert(rtn, line)
  511. return table.concat(rtn)
  512. end
  513. function lume.format(str, vars)
  514. if not vars then return str end
  515. local f = function(x)
  516. return tostring(vars[x] or vars[tonumber(x)] or "{" .. x .. "}")
  517. end
  518. return (str:gsub("{(.-)}", f))
  519. end
  520. function lume.trace(...)
  521. local info = debug.getinfo(2, "Sl")
  522. local t = { info.short_src .. ":" .. info.currentline .. ":" }
  523. for i = 1, select("#", ...) do
  524. local x = select(i, ...)
  525. if type(x) == "number" then
  526. x = string.format("%g", lume.round(x, .01))
  527. end
  528. t[#t + 1] = tostring(x)
  529. end
  530. print(table.concat(t, " "))
  531. end
  532. function lume.dostring(str)
  533. return assert((loadstring or load)(str))()
  534. end
  535. function lume.uuid()
  536. local fn = function(x)
  537. local r = math_random(16) - 1
  538. r = (x == "x") and (r + 1) or (r % 4) + 9
  539. return ("0123456789abcdef"):sub(r, r)
  540. end
  541. return (("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"):gsub("[xy]", fn))
  542. end
  543. function lume.hotswap(modname)
  544. local oldglobal = lume.clone(_G)
  545. local updated = {}
  546. local function update(old, new)
  547. if updated[old] then return end
  548. updated[old] = true
  549. local oldmt, newmt = getmetatable(old), getmetatable(new)
  550. if oldmt and newmt then update(oldmt, newmt) end
  551. for k, v in pairs(new) do
  552. if type(v) == "table" then update(old[k], v) else old[k] = v end
  553. end
  554. end
  555. local err = nil
  556. local function onerror(e)
  557. for k, v in pairs(_G) do _G[k] = oldglobal[k] end
  558. err = lume.trim(e)
  559. end
  560. local ok, oldmod = pcall(require, modname)
  561. oldmod = ok and oldmod or nil
  562. xpcall(function()
  563. package.loaded[modname] = nil
  564. local newmod = require(modname)
  565. if type(oldmod) == "table" then update(oldmod, newmod) end
  566. for k, v in pairs(oldglobal) do
  567. if v ~= _G[k] and type(v) == "table" then
  568. update(v, _G[k])
  569. _G[k] = v
  570. end
  571. end
  572. end, onerror)
  573. package.loaded[modname] = oldmod
  574. if err then return nil, err end
  575. return oldmod
  576. end
  577. local ripairs_iter = function(t, i)
  578. i = i - 1
  579. local v = t[i]
  580. if v then return i, v end
  581. end
  582. function lume.ripairs(t)
  583. return ripairs_iter, t, (#t + 1)
  584. end
  585. function lume.color(str, mul)
  586. mul = mul or 1
  587. local r, g, b, a
  588. r, g, b = str:match("#(%x%x)(%x%x)(%x%x)")
  589. if r then
  590. r = tonumber(r, 16) / 0xff
  591. g = tonumber(g, 16) / 0xff
  592. b = tonumber(b, 16) / 0xff
  593. a = 1
  594. elseif str:match("rgba?%s*%([%d%s%.,]+%)") then
  595. local f = str:gmatch("[%d.]+")
  596. r = (f() or 0) / 0xff
  597. g = (f() or 0) / 0xff
  598. b = (f() or 0) / 0xff
  599. a = f() or 1
  600. else
  601. error(("bad color string '%s'"):format(str))
  602. end
  603. return r * mul, g * mul, b * mul, a * mul
  604. end
  605. function lume.rgba(color)
  606. local a = math_floor((color / 16777216) % 256)
  607. local r = math_floor((color / 65536) % 256)
  608. local g = math_floor((color / 256) % 256)
  609. local b = math_floor((color) % 256)
  610. return r, g, b, a
  611. end
  612. local chain_mt = {}
  613. chain_mt.__index = lume.map(lume.filter(lume, iscallable, true),
  614. function(fn)
  615. return function(self, ...)
  616. self._value = fn(self._value, ...)
  617. return self
  618. end
  619. end)
  620. chain_mt.__index.result = function(x) return x._value end
  621. function lume.chain(value)
  622. return setmetatable({ _value = value }, chain_mt)
  623. end
  624. setmetatable(lume, {
  625. __call = function(t, ...)
  626. return lume.chain(...)
  627. end
  628. })
  629. return lume