satelito

Static [web] site (or page) generator (ssg) made with Lua script.
git clone git://soucy.cc/satelito.git
Log | Files | Refs | README

README.md (16739B)


      1 # Lume
      2 
      3 A collection of functions for Lua, geared towards game development.
      4 
      5 
      6 ## Installation
      7 
      8 The [lume.lua](lume.lua?raw=1) file should be dropped into an existing project
      9 and required by it:
     10 
     11 ```lua
     12 lume = require "lume"
     13 ```
     14 
     15 
     16 ## Function Reference
     17 
     18 #### lume.clamp(x, min, max)
     19 Returns the number `x` clamped between the numbers `min` and `max`
     20 
     21 #### lume.round(x [, increment])
     22 Rounds `x` to the nearest integer; rounds away from zero if we're midway
     23 between two integers. If `increment` is set then the number is rounded to the
     24 nearest increment.
     25 ```lua
     26 lume.round(2.3) -- Returns 2
     27 lume.round(123.4567, .1) -- Returns 123.5
     28 ```
     29 
     30 #### lume.sign(x)
     31 Returns `1` if `x` is 0 or above, returns `-1` when `x` is negative.
     32 
     33 #### lume.lerp(a, b, amount)
     34 Returns the linearly interpolated number between `a` and `b`, `amount` should
     35 be in the range of 0 - 1; if `amount` is outside of this range it is clamped.
     36 ```lua
     37 lume.lerp(100, 200, .5) -- Returns 150
     38 ```
     39 
     40 #### lume.smooth(a, b, amount)
     41 Similar to `lume.lerp()` but uses cubic interpolation instead of linear
     42 interpolation.
     43 
     44 #### lume.pingpong(x)
     45 Ping-pongs the number `x` between 0 and 1.
     46 
     47 #### lume.distance(x1, y1, x2, y2 [, squared])
     48 Returns the distance between the two points. If `squared` is true then the
     49 squared distance is returned -- this is faster to calculate and can still be
     50 used when comparing distances.
     51 
     52 #### lume.angle(x1, y1, x2, y2)
     53 Returns the angle between the two points.
     54 
     55 #### lume.vector(angle, magnitude)
     56 Given an `angle` and `magnitude`, returns a vector.
     57 ```lua
     58 local x, y = lume.vector(0, 10) -- Returns 10, 0
     59 ```
     60 
     61 #### lume.random([a [, b]])
     62 Returns a random number between `a` and `b`. If only `a` is supplied a number
     63 between `0` and `a` is returned. If no arguments are supplied a random number
     64 between `0` and `1` is returned.
     65 
     66 #### lume.randomchoice(t)
     67 Returns a random value from array `t`. If the array is empty an error is
     68 raised.
     69 ```lua
     70 lume.randomchoice({true, false}) -- Returns either true or false
     71 ```
     72 
     73 #### lume.weightedchoice(t)
     74 Takes the argument table `t` where the keys are the possible choices and the
     75 value is the choice's weight. A weight should be 0 or above, the larger the
     76 number the higher the probability of that choice being picked. If the table is
     77 empty, a weight is below zero or all the weights are 0 then an error is raised.
     78 ```lua
     79 lume.weightedchoice({ ["cat"] = 10, ["dog"] = 5, ["frog"] = 0 })
     80 -- Returns either "cat" or "dog" with "cat" being twice as likely to be chosen.
     81 ```
     82 
     83 #### lume.isarray(x)
     84 Returns `true` if `x` is an array -- the value is assumed to be an array if it
     85 is a table which contains a value at the index `1`. This function is used
     86 internally and can be overridden if you wish to use a different method to detect
     87 arrays.
     88 
     89 
     90 #### lume.push(t, ...)
     91 Pushes all the given values to the end of the table `t` and returns the pushed
     92 values. Nil values are ignored.
     93 ```lua
     94 local t = { 1, 2, 3 }
     95 lume.push(t, 4, 5) -- `t` becomes { 1, 2, 3, 4, 5 }
     96 ```
     97 
     98 #### lume.remove(t, x)
     99 Removes the first instance of the value `x` if it exists in the table `t`.
    100 Returns `x`.
    101 ```lua
    102 local t = { 1, 2, 3 }
    103 lume.remove(t, 2) -- `t` becomes { 1, 3 }
    104 ```
    105 
    106 #### lume.clear(t)
    107 Nils all the values in the table `t`, this renders the table empty. Returns
    108 `t`.
    109 ```lua
    110 local t = { 1, 2, 3 }
    111 lume.clear(t) -- `t` becomes {}
    112 ```
    113 
    114 #### lume.extend(t, ...)
    115 Copies all the fields from the source tables to the table `t` and returns `t`.
    116 If a key exists in multiple tables the right-most table's value is used.
    117 ```lua
    118 local t = { a = 1, b = 2 }
    119 lume.extend(t, { b = 4, c = 6 }) -- `t` becomes { a = 1, b = 4, c = 6 }
    120 ```
    121 
    122 #### lume.shuffle(t)
    123 Returns a shuffled copy of the array `t`.
    124 
    125 #### lume.sort(t [, comp])
    126 Returns a copy of the array `t` with all its items sorted. If `comp` is a
    127 function it will be used to compare the items when sorting. If `comp` is a
    128 string it will be used as the key to sort the items by.
    129 ```lua
    130 lume.sort({ 1, 4, 3, 2, 5 }) -- Returns { 1, 2, 3, 4, 5 }
    131 lume.sort({ {z=2}, {z=3}, {z=1} }, "z") -- Returns { {z=1}, {z=2}, {z=3} }
    132 lume.sort({ 1, 3, 2 }, function(a, b) return a > b end) -- Returns { 3, 2, 1 }
    133 ```
    134 
    135 #### lume.array(...)
    136 Iterates the supplied iterator and returns an array filled with the values.
    137 ```lua
    138 lume.array(string.gmatch("Hello world", "%a+")) -- Returns {"Hello", "world"}
    139 ```
    140 
    141 #### lume.each(t, fn, ...)
    142 Iterates the table `t` and calls the function `fn` on each value followed by
    143 the supplied additional arguments; if `fn` is a string the method of that name
    144 is called for each value. The function returns `t` unmodified.
    145 ```lua
    146 lume.each({1, 2, 3}, print) -- Prints "1", "2", "3" on separate lines
    147 lume.each({a, b, c}, "move", 10, 20) -- Does x:move(10, 20) on each value
    148 ```
    149 
    150 #### lume.map(t, fn)
    151 Applies the function `fn` to each value in table `t` and returns a new table
    152 with the resulting values.
    153 ```lua
    154 lume.map({1, 2, 3}, function(x) return x * 2 end) -- Returns {2, 4, 6}
    155 ```
    156 
    157 #### lume.all(t [, fn])
    158 Returns true if all the values in `t` table are true. If a `fn` function is
    159 supplied it is called on each value, true is returned if all of the calls to
    160 `fn` return true.
    161 ```lua
    162 lume.all({1, 2, 1}, function(x) return x == 1 end) -- Returns false
    163 ```
    164 
    165 #### lume.any(t [, fn])
    166 Returns true if any of the values in `t` table are true. If a `fn` function is
    167 supplied it is called on each value, true is returned if any of the calls to
    168 `fn` return true.
    169 ```lua
    170 lume.any({1, 2, 1}, function(x) return x == 1 end) -- Returns true
    171 ```
    172 
    173 #### lume.reduce(t, fn [, first])
    174 Applies `fn` on two arguments cumulative to the items of the array `t`, from
    175 left to right, so as to reduce the array to a single value. If a `first` value
    176 is specified the accumulator is initialised to this, otherwise the first value
    177 in the array is used. If the array is empty and no `first` value is specified
    178 an error is raised.
    179 ```lua
    180 lume.reduce({1, 2, 3}, function(a, b) return a + b end) -- Returns 6
    181 ```
    182 
    183 #### lume.unique(t)
    184 Returns a copy of the `t` array with all the duplicate values removed.
    185 ```lua
    186 lume.unique({2, 1, 2, "cat", "cat"}) -- Returns {1, 2, "cat"}
    187 ```
    188 
    189 #### lume.filter(t, fn [, retainkeys])
    190 Calls `fn` on each value of `t` table. Returns a new table with only the values
    191 where `fn` returned true. If `retainkeys` is true the table is not treated as
    192 an array and retains its original keys.
    193 ```lua
    194 lume.filter({1, 2, 3, 4}, function(x) return x % 2 == 0 end) -- Returns {2, 4}
    195 ```
    196 
    197 #### lume.reject(t, fn [, retainkeys])
    198 The opposite of `lume.filter()`: Calls `fn` on each value of `t` table; returns
    199 a new table with only the values where `fn` returned false. If `retainkeys` is
    200 true the table is not treated as an array and retains its original keys.
    201 ```lua
    202 lume.reject({1, 2, 3, 4}, function(x) return x % 2 == 0 end) -- Returns {1, 3}
    203 ```
    204 
    205 #### lume.merge(...)
    206 Returns a new table with all the given tables merged together. If a key exists
    207 in multiple tables the right-most table's value is used.
    208 ```lua
    209 lume.merge({a=1, b=2, c=3}, {c=8, d=9}) -- Returns {a=1, b=2, c=8, d=9}
    210 ```
    211 
    212 #### lume.concat(...)
    213 Returns a new array consisting of all the given arrays concatenated into one.
    214 ```lua
    215 lume.concat({1, 2}, {3, 4}, {5, 6}) -- Returns {1, 2, 3, 4, 5, 6}
    216 ```
    217 
    218 #### lume.find(t, value)
    219 Returns the index/key of `value` in `t`. Returns `nil` if that value does not
    220 exist in the table.
    221 ```lua
    222 lume.find({"a", "b", "c"}, "b") -- Returns 2
    223 ```
    224 
    225 #### lume.match(t, fn)
    226 Returns the value and key of the value in table `t` which returns true when
    227 `fn` is called on it. Returns `nil` if no such value exists.
    228 ```lua
    229 lume.match({1, 5, 8, 7}, function(x) return x % 2 == 0 end) -- Returns 8, 3
    230 ```
    231 
    232 #### lume.count(t [, fn])
    233 Counts the number of values in the table `t`. If a `fn` function is supplied it
    234 is called on each value, the number of times it returns true is counted.
    235 ```lua
    236 lume.count({a = 2, b = 3, c = 4, d = 5}) -- Returns 4
    237 lume.count({1, 2, 4, 6}, function(x) return x % 2 == 0 end) -- Returns 3
    238 ```
    239 
    240 #### lume.slice(t [, i [, j]])
    241 Mimics the behaviour of Lua's `string.sub`, but operates on an array rather
    242 than a string. Creates and returns a new array of the given slice.
    243 ```lua
    244 lume.slice({"a", "b", "c", "d", "e"}, 2, 4) -- Returns {"b", "c", "d"}
    245 ```
    246 
    247 #### lume.first(t [, n])
    248 Returns the first element of an array or nil if the array is empty. If `n` is
    249 specificed an array of the first `n` elements is returned.
    250 ```lua
    251 lume.first({"a", "b", "c"}) -- Returns "a"
    252 ```
    253 
    254 #### lume.last(t [, n])
    255 Returns the last element of an array or nil if the array is empty. If `n` is
    256 specificed an array of the last `n` elements is returned.
    257 ```lua
    258 lume.last({"a", "b", "c"}) -- Returns "c"
    259 ```
    260 
    261 #### lume.invert(t)
    262 Returns a copy of the table where the keys have become the values and the
    263 values the keys.
    264 ```lua
    265 lume.invert({a = "x", b = "y"}) -- returns {x = "a", y = "b"}
    266 ```
    267 
    268 #### lume.pick(t, ...)
    269 Returns a copy of the table filtered to only contain values for the given keys.
    270 ```lua
    271 lume.pick({ a = 1, b = 2, c = 3 }, "a", "c") -- Returns { a = 1, c = 3 }
    272 ```
    273 
    274 #### lume.keys(t)
    275 Returns an array containing each key of the table.
    276 
    277 #### lume.clone(t)
    278 Returns a shallow copy of the table `t`.
    279 
    280 #### lume.fn(fn, ...)
    281 Creates a wrapper function around function `fn`, automatically inserting the
    282 arguments into `fn` which will persist every time the wrapper is called. Any
    283 arguments which are passed to the returned function will be inserted after the
    284 already existing arguments passed to `fn`.
    285 ```lua
    286 local f = lume.fn(print, "Hello")
    287 f("world") -- Prints "Hello world"
    288 ```
    289 
    290 #### lume.once(fn, ...)
    291 Returns a wrapper function to `fn` which takes the supplied arguments. The
    292 wrapper function will call `fn` on the first call and do nothing on any
    293 subsequent calls.
    294 ```lua
    295 local f = lume.once(print, "Hello")
    296 f() -- Prints "Hello"
    297 f() -- Does nothing
    298 ```
    299 
    300 #### lume.memoize(fn)
    301 Returns a wrapper function to `fn` where the results for any given set of
    302 arguments are cached. `lume.memoize()` is useful when used on functions with
    303 slow-running computations.
    304 ```lua
    305 fib = lume.memoize(function(n) return n < 2 and n or fib(n-1) + fib(n-2) end)
    306 ```
    307 
    308 #### lume.combine(...)
    309 Creates a wrapper function which calls each supplied argument in the order they
    310 were passed to `lume.combine()`; nil arguments are ignored. The wrapper
    311 function passes its own arguments to each of its wrapped functions when it is
    312 called.
    313 ```lua
    314 local f = lume.combine(function(a, b) print(a + b) end,
    315                        function(a, b) print(a * b) end)
    316 f(3, 4) -- Prints "7" then "12" on a new line
    317 ```
    318 
    319 #### lume.call(fn, ...)
    320 Calls the given function with the provided arguments and returns its values. If
    321 `fn` is `nil` then no action is performed and the function returns `nil`.
    322 ```lua
    323 lume.call(print, "Hello world") -- Prints "Hello world"
    324 ```
    325 
    326 #### lume.time(fn, ...)
    327 Inserts the arguments into function `fn` and calls it. Returns the time in
    328 seconds the function `fn` took to execute followed by `fn`'s returned values.
    329 ```lua
    330 lume.time(function(x) return x end, "hello") -- Returns 0, "hello"
    331 ```
    332 
    333 #### lume.lambda(str)
    334 Takes a string lambda and returns a function. `str` should be a list of
    335 comma-separated parameters, followed by `->`, followed by the expression which
    336 will be evaluated and returned.
    337 ```lua
    338 local f = lume.lambda "x,y -> 2*x+y"
    339 f(10, 5) -- Returns 25
    340 ```
    341 
    342 #### lume.serialize(x)
    343 Serializes the argument `x` into a string which can be loaded again using
    344 `lume.deserialize()`. Only booleans, numbers, tables and strings can be
    345 serialized. Circular references will result in an error; all nested tables are
    346 serialized as unique tables.
    347 ```lua
    348 lume.serialize({a = "test", b = {1, 2, 3}, false})
    349 -- Returns "{[1]=false,["a"]="test",["b"]={[1]=1,[2]=2,[3]=3,},}"
    350 ```
    351 
    352 #### lume.deserialize(str)
    353 Deserializes a string created by `lume.serialize()` and returns the resulting
    354 value. This function should not be run on an untrusted string.
    355 ```lua
    356 lume.deserialize("{1, 2, 3}") -- Returns {1, 2, 3}
    357 ```
    358 
    359 #### lume.split(str [, sep])
    360 Returns an array of the words in the string `str`. If `sep` is provided it is
    361 used as the delimiter, consecutive delimiters are not grouped together and will
    362 delimit empty strings.
    363 ```lua
    364 lume.split("One two three") -- Returns {"One", "two", "three"}
    365 lume.split("a,b,,c", ",") -- Returns {"a", "b", "", "c"}
    366 ```
    367 
    368 #### lume.trim(str [, chars])
    369 Trims the whitespace from the start and end of the string `str` and returns the
    370 new string. If a `chars` value is set the characters in `chars` are trimmed
    371 instead of whitespace.
    372 ```lua
    373 lume.trim("  Hello  ") -- Returns "Hello"
    374 ```
    375 
    376 #### lume.wordwrap(str [, limit])
    377 Returns `str` wrapped to `limit` number of characters per line, by default
    378 `limit` is `72`. `limit` can also be a function which when passed a string,
    379 returns `true` if it is too long for a single line.
    380 ```lua
    381 -- Returns "Hello world\nThis is a\nshort string"
    382 lume.wordwrap("Hello world. This is a short string", 14)
    383 ```
    384 
    385 #### lume.format(str [, vars])
    386 Returns a formatted string. The values of keys in the table `vars` can be
    387 inserted into the string by using the form `"{key}"` in `str`; numerical keys
    388 can also be used.
    389 ```lua
    390 lume.format("{b} hi {a}", {a = "mark", b = "Oh"}) -- Returns "Oh hi mark"
    391 lume.format("Hello {1}!", {"world"}) -- Returns "Hello world!"
    392 ```
    393 
    394 #### lume.trace(...)
    395 Prints the current filename and line number followed by each argument separated
    396 by a space.
    397 ```lua
    398 -- Assuming the file is called "example.lua" and the next line is 12:
    399 lume.trace("hello", 1234) -- Prints "example.lua:12: hello 1234"
    400 ```
    401 
    402 #### lume.dostring(str)
    403 Executes the lua code inside `str`.
    404 ```lua
    405 lume.dostring("print('Hello!')") -- Prints "Hello!"
    406 ```
    407 
    408 #### lume.uuid()
    409 Generates a random UUID string; version 4 as specified in
    410 [RFC 4122](http://www.ietf.org/rfc/rfc4122.txt).
    411 
    412 #### lume.hotswap(modname)
    413 Reloads an already loaded module in place, allowing you to immediately see the
    414 effects of code changes without having to restart the program. `modname` should
    415 be the same string used when loading the module with require(). In the case of
    416 an error the global environment is restored and `nil` plus an error message is
    417 returned.
    418 ```lua
    419 lume.hotswap("lume") -- Reloads the lume module
    420 assert(lume.hotswap("inexistant_module")) -- Raises an error
    421 ```
    422 
    423 #### lume.ripairs(t)
    424 Performs the same function as `ipairs()` but iterates in reverse; this allows
    425 the removal of items from the table during iteration without any items being
    426 skipped.
    427 ```lua
    428 -- Prints "3->c", "2->b" and "1->a" on separate lines
    429 for i, v in lume.ripairs({ "a", "b", "c" }) do
    430   print(i .. "->" .. v)
    431 end
    432 ```
    433 
    434 #### lume.color(str [, mul])
    435 Takes color string `str` and returns 4 values, one for each color channel (`r`,
    436 `g`, `b` and `a`). By default the returned values are between 0 and 1; the
    437 values are multiplied by the number `mul` if it is provided.
    438 ```lua
    439 lume.color("#ff0000")               -- Returns 1, 0, 0, 1
    440 lume.color("rgba(255, 0, 255, .5)") -- Returns 1, 0, 1, .5
    441 lume.color("#00ffff", 256)          -- Returns 0, 256, 256, 256
    442 lume.color("rgb(255, 0, 0)", 256)   -- Returns 256, 0, 0, 256
    443 ```
    444 
    445 #### lume.chain(value)
    446 Returns a wrapped object which allows chaining of lume functions. The function
    447 result() should be called at the end of the chain to return the resulting
    448 value.
    449 ```lua
    450 lume.chain({1, 2, 3, 4})
    451   :filter(function(x) return x % 2 == 0 end)
    452   :map(function(x) return -x end)
    453   :result() -- Returns { -2, -4 }
    454 ```
    455 The table returned by the `lume` module, when called, acts in the same manner
    456 as calling `lume.chain()`.
    457 ```lua
    458 lume({1, 2, 3}):each(print) -- Prints 1, 2 then 3 on separate lines
    459 ```
    460 
    461 ## Iteratee functions
    462 Several lume functions allow a `table`, `string` or `nil` to be used in place
    463 of their iteratee function argument. The functions that provide this behaviour
    464 are: `map()`, `all()`, `any()`, `filter()`, `reject()`, `match()` and
    465 `count()`.
    466 
    467 If the argument is `nil` then each value will return itself.
    468 ```lua
    469 lume.filter({ true, true, false, true }, nil) -- { true, true, true }
    470 ```
    471 
    472 If the argument is a `string` then each value will be assumed to be a table,
    473 and will return the value of the key which matches the string.
    474 ``` lua
    475 local t = {{ z = "cat" }, { z = "dog" }, { z = "owl" }}
    476 lume.map(t, "z") -- Returns { "cat", "dog", "owl" }
    477 ```
    478 
    479 If the argument is a `table` then each value will return `true` or `false`,
    480 depending on whether the values at each of the table's keys match the
    481 collection's value's values.
    482 ```lua
    483 local t = {
    484   { age = 10, type = "cat" },
    485   { age = 8,  type = "dog" },
    486   { age = 10, type = "owl" },
    487 }
    488 lume.count(t, { age = 10 }) -- returns 2
    489 ```
    490 
    491 
    492 ## License
    493 
    494 This library is free software; you can redistribute it and/or modify it under
    495 the terms of the MIT license. See [LICENSE](LICENSE) for details.