Git Product home page Git Product logo

batteries's Introduction

⚡ Batteries for Lua

Helpful stuff for making games with lua, especially with löve.

Get your projects off the ground faster! batteries fills out lua's sparse standard library, and provides implementations of many common algorithms and data structures useful for games.

General purpose and special case, extensively documented in-line, and around a hundred kilobytes uncompressed - including the license and this readme - so you get quite a lot per byte! Of course, feel free to trim it down for your use case as required (see below).

Getting Started

How does that module work?

Examples are in another repo to avoid cluttering the repo history and your project/filesystem when used as a submodule.

They have short, straightforward usage examples of much of the provided functionality.

Documentation is provided as comments alongside the code, because that is the most resilient place for it. Even auto-generated docs often end up out of date and the annotations bloat the code.

Use find-in-all from your editor, or just browse through the code. The module overview below is the only non-code documentation - it is a jumping off point, not a reference.

Installation

batteries works straight out of the repo with no separate build step. The license file required for use is included.

  • Put the files in their own directory, somewhere your project can access them.
  • require the base batteries directory - the one with init.lua in it.
    • Don't forget to use dot syntax on the path!
    • With a normal require setup (ie stock LÖVE or lua), init.lua will pull in all the submodules.
    • Batteries uses the (very common) init.lua convention. If your installation doesn't already have init.lua support (eg plain 5.1 on windows), add package.path = package.path .. ";./?/init.lua" before the require line. You can also modify your LUA_PATH environment variable.
  • (optionally) export everything to the global environment.
--everything as globals
require("path.to.batteries"):export()

-- OR --

--self-contained
local batteries = require("path.to.batteries")

See below for a discussion of the pros and cons of export.

Library Culture and Contributing

batteries aims to be approachable to almost everyone, but I do expect you to get your hands dirty. I'm very open to collaboration, and happy to talk through issues or shortcomings in good faith.

Pull requests are welcome for anything - positive changes will be merged optimistically, and I'm happy to work with you to get anything sensible ready for inclusion.

If you have something "big" to contribute please get in touch before starting work so we can make sure it fits. I'm quite open minded!

If you've had a good look for the answer but something remains unclear, raise an issue and I'll address it. If you haven't had a good look for the answer, checking the source always helps!

If you'd prefer to talk with me about batteries in real time, I'm often available on the love2d discord.

Module Overview

Lua Core Extensions:

Extensions to existing lua core modules to provide missing features.

  • mathx - Mathematical extensions. Alias math.
  • tablex - Table handling extensions. Alias table.
  • stringx - String handling extensions. Alias string.

General Utility:

General utility data structures and algorithms to speed you along your way.

  • class - OOP with inheritance and interfaces in a single function.
  • functional - Functional programming facilities. map, reduce, any, match, minmax, mean...
  • sequence - An oo wrapper on sequential tables, so you can do t:insert(i, v) instead of table.insert(t, i, v). Also supports method chaining for the functional interface above, which can save a lot of needless typing!
  • set - A set type supporting a full suite of set operations with fast membership testing and ipairs-style iteration.
  • sort - Provides a stable merge+insertion sorting algorithm that is also, as a bonus, often faster than table.sort under luajit. Also exposes insertion_sort if needed. Alias stable_sort.
  • state_machine - Finite state machine implementation with state transitions and all the rest. Useful for game states, AI, cutscenes...
  • timer - a "countdown" style timer with progress and completion callbacks.
  • pubsub - a self-contained publish/subscribe message bus. Immediate mode rather than queued, local rather than networked, but if you were expecting mqtt in 60 lines I don't know what to tell you. Scales pretty well nonetheless.
  • pretty - pretty printing tables for debug inspection.

Geometry:

Modules to help work with spatial concepts.

  • intersect - 2d intersection routines, a bit sparse at the moment.
  • vec2 - 2d vectors with method chaining, and garbage saving modifying operations. A bit of a mouthful at times, but you get used to it. (there's an issue discussing future solutions).
  • vec3 - 3d vectors as above.

Special Interest:

These modules are probably only useful to some folks in some circumstances, or are under-polished for one reason or another.

  • async - Asynchronous/"Background" task management.
  • colour - Colour conversion routines. Alias color.
  • manual_gc - Get GC out of your update/draw calls. Useful when trying to get accurate profiling information; moves "randomness" of GC. Requires you to think a bit about your garbage budgets though.
  • measure - Benchmarking helpers - measure the time or memory taken to run some code.
  • make_pooled - add pooling/recycling capability to a class

Any aliases are provided at both the batteries module level, and globally when exported.

Work in Progress, or TODO

Endless, of course :)

  • colour - Bidirectional hsv/hsl/etc conversion would fit nicely here.
  • Geometry:
    • vec3 - Needs more fleshing out for serious use, and a refactor to fit the same naming patterns as vec2.
    • matrix - A geometry focussed matrix module would made 3d work a lot nicer. Possibly just mat4.
    • intersect - More routines, more optimisation :)
  • Network:
    • Various helpers for networked systems, game focus of course.
    • rpc - Remote procedure call system on top of enet or socket or both.
    • delta - Detect and sync changes to objects.
  • Broadphase:
    • Spatial simplification systems for different needs. Probably AABB or point insertion of data.
    • bucket_grid - Dumb 2d bucket broadphase.
    • sweep_and_prune - Popular for bullet hell games.
    • quadtree/octree - Everyone's favourite ;)
  • UI
    • Maybe adopt partner in here, or something evolved from it.
  • Image
    • Maybe adopt chromatic in here, or something evolved from it.

FAQ

Export Globals

You are strongly encouraged to use the library in a "fire and forget" manner through require("batteries"):export() (or whatever appropriate module path), which will modify builtin lua modules (such as table and math), and expose all the other modules directly as globals for your convenience.

This eases consumption across your project - you don't have to require modules everywhere, or remember if say, table.remove_value is built in to lua or not, or get used to accessing the builtin table functions through batteries.table or tablex.

While this will likely sit badly with anyone who's had "no globals! ever!" hammered into them, I believe that for batteries (and many foundational libraries) it makes sense to just import once at boot. You're going to be pulling it in almost everywhere anyway; why bother making yourself jump through more hoops?

You can, of course, use the separate modules on their own, either requiring individual modules explicitly, or a single require for all of batteries and use through something like batteries.functional.map. This more involved approach will let you be more clear about your dependencies, if you care deeply about that - at the cost of more setup work needing to re-require batteries everywhere you use it, or expose it as a global in the first place.

I'd strongly recommend that if you find yourself frustrated with the above, stop and think why/if you really want to avoid globals for something intended to be commonly used across your entire codebase! Are you explicitly requireing math and table everywhere you use it too? Are you just as ideologically opposed to require being a global?

You may wish to reconsider, and save yourself typing batteries a few hundred times :)

Git Submodule or Static Install?

batteries is fairly easily used as a git submodule - this is how I use it in my own projects, because updating is as quick and easy as a git pull, and it's easy to roll back changes if needed, and to contribute changes back upstream.

A static install is harder to update, but easier to trim down if you only need some of the functionality provided. It can also never mysteriously break when updating, which might be appealing to those who just cant stop themselves using the latest and greatest.

Stripping down batteries

Many of the modules "just work" on their own, if you just want to grab something specific.

Some of them depend on class, which can be included alongside pretty easily.

There are some other inter-dependencies in the larger modules, which should be straightforward to detect and figure out the best course of action (either include the dependency or strip out dependent functionality), if you want to make a stripped-down version for your specific use case.

Currently (july 2021) the lib is 40kb or so compressed, including this readme, so do think carefully whether you really need to worry about it!

Versioning?

Currently, the library is operated in a rolling-release manner - the head of the master branch is intended for public consumption. While this is kept as stable as practical, breaking API changes do happen, and more are planned!

For this reason, you should try to check the commit history for what has changed rather than blindly updating. If you let me know that you're using it actively, I'm generally happy to let you know when something breaking is on its way to master as well.

If there is a large enough user base in the future to make a versioning scheme + non-repo changelog make sense, I will accomodate.

snake_case? Why?

I personally prefer it, but I accept that it's a matter of taste and puts some people off.

I've implemented experimental automatic API conversion (UpperCamelCase for types, lowerCamelCase for methods) that you can opt in to by calling :camelCase() before :export(), let me know if you use it and encounter any issues.

License

zlib, see here

batteries's People

Contributors

1bardesign avatar aweptimum avatar billmakes avatar chrsm avatar duznanski avatar flamendless avatar idbrii avatar isometricshahil avatar jalhund avatar jesseviikari avatar josh-perry avatar mikuauahdark avatar monolifed avatar pakeke-constructor avatar qequ avatar radgerayden avatar rhysuki avatar sheepolution avatar speakk avatar turtlep avatar zombrodo avatar zorggn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

batteries's Issues

Docs improvement re package.path

On windows, using the basic lua5.1 interpreter, I had to add package.path = package.path .. ";./?/init.lua" before require("ext.batteries"):export(); to get it to work. Could mention this on the Installation section?

vec3:sset not using z properly

I believe there is a bug with the vec3:sset method.

function vec3:sset(x, y, z)
	self.x = x
	self.y = y or x
	self.z = z or y or z
	return self
end

Line 4. Shouldn't it be z or y or x instead?

colour.lua: hex_to_rgb

Something I noticed that could be useful in the colour namespace is a way to convert hex colors to rgb(a). Although not entirely common to do, it would be helpful as there's lots of predefined web colors, etc that use hex. Converting these to a float format [0, 1] is a pain.

For example, I often use this color tool when making a UI. It would be nice to say colour.hex_to_rgba("#eeeeee") and get the float values off of that.

Edit: I noticed there is unpack_rgb which takes a numerical value, although a string variant might be nice as well. Feel free to close, though, if you think it's not needed.

Testing Discussion

#52 adds testing, and a few other recent prs from @idbrii have also added other CI functionality.

I'm torn on adding this stuff to the repo, especially in the main branch. At the very least we should move them under an easily deleted directory, probably .test or similar so it's ignored by utilities that ignore dotfiles.

The various alternatives, as i see them:

  • keep them in main branch, move to a directory, and don't worry about it beyond that.
  • move them to a test branch that CI can still use, with the caveat that we'll need to merge main into test often (some friction)
  • move them to a separate repo that uses batteries as a submodule (highest friction)

Some discussion from here onwards in discord

vec2 and vec3 interface is not friendly

At the moment, the vector modules have a naming pattern which is fairly user unfriendly. This is affecting uptake.

There are two issues, both basically lead to "hungarian style" names which are hard to understand at a glance.

Type Prefix:

Problem:
Currently, the operation type (scalar or vector) is specified with a "hungarian notation" style single letter prefix.
This avoids type dependent dynamic dispatch and keeps code fast but also is pretty unfriendly to a beginner.

Fix:
fully specified names could be provided for each operation, with hungarian style aliases preserved for writing terse code if preferred. vector_add and vadd both available, but the former canonicalised as the initial definition.

Immediate/Modifying Suffix:

Problem:
Currently, if an operation modifies its operand or not is specified with an "immediate" suffix on the method, eg vaddi for "vector add immediate". This looks a lot more like an assembly instruction than a lua method 😄

Fix:
A different naming convention could be adopted. Current candidate is verb for modifying and verbed for copying - eg normalise and normalised for modifying and copying normalisation respectively.

Note that this would break existing code. It definitely needs to be communicated well to existing users!

I do think both are worth doing though to make the incredibly useful vector modules more likely to get use in the wider community.

attempt to index a nil value (global 'love')

Not sure if I'm doing this right, but I pulled batteries to my project and require("batteries"):export() would fail because love couldn't be found. I added a check for love at capture_callstacks part of async.lua and that did the trick.

Is it expected you pull in love for batteries to work?

Aliases not working

Im using the latest version if batteries

require("batteries"):export()
print(mathx)
print(tablex)
print(stringx)

All outputs nil

`functional.reduce` has an annoying signature

functional.reduce(seq, f, init) has the annoying property of the initial value coming after the function, often several lines removed from the start of the call. This would be a breaking api change, however.

Table.clear error

Line 147 in the assert function in table.lua (table.clear)

Sent from my HUAWEI GR5 2017 using FastHub

table.rotate should use the triple reverse method.

The existing shift/push method touches every element in the table once per step. The triple reverse method touches every element exactly twice.

function tablex.rotate(t, n)
    local tlen = #t
    local mid = -n % tlen
    tablex.reverse(t)
    tablex.reverse(t, 1, mid)
    tablex.reverse(t, mid+1, tlen)
end

For this to work your tablex.reverse needs to take optional bound arguments. Note that tablex.reverse should also be caching the length value rather than recalculating it in the loop.

[Feature Request] path module

About

Discussed on Discord briefly, it would be nice to have a simple path module. These could also be appended to the existing stringx module instead, specifying they operate on file paths/file names.

Functions

  1. {module}.extractFilename - get the filename of a file
    • Useful for when iterating and requiring lua files
  2. {module}.extract(File)Extension - get the extension of a file
  3. Some function that wraps around doing this for the init.lua path

While the first two functions are simple to do, I think it would still be beneficial to have them. Maybe have a function that would also return both pieces of information, should the user want both from one function call.

Use `type` as method instead of `string`

Example in vec2 module:

local pos = vec2:new()
print(pos:type()) -- error

most love libraries and even love userdata use type as a function instead of string, so maybe change it to

local pos = vec2:new()
print(pos:type()) --vec2
print(pos.__type) -vec2

This is probably more of a design choice, I'll be glad to know the your reasons behind it.

[Bug]: Subclass Not Updating Parent Variables

Hey,

I feel like my code is 99% correct, but for some strange reason, it isn't working properly. I have a subclass which extends a parent class, calls super for the necessary details, and then I try to move it around and allow the parent's draw method to handle rendering. However, it doesn't move. The only way for it to move is if I override the draw method and use the subclass's position variables. This doesn't make sense to me, since it should still be able to render at the position of the parent class, though. Here is the code I am using:

local peg = class()

peg.texture = love.graphics.newImage("graphics/objects.png")
peg.quads = {}
for index  = 1, 7 do
    peg.quads[index] = love.graphics.newQuad((index - 1) * 17, 0, 16, 16, peg.texture)
end

function peg:new(type, x, y)
    self.x = x
    self.y = y

    self.width = 16
    self.height = 16

    self.type = type
end

function peg:draw()
    love.graphics.draw(peg.texture, peg.quads[self.type], self.x * 16, self.y * 16)
end

function peg:move(x, y)
    self.x = self.x + x
    self.y = self.y + y
end

function peg:position()
    return self.x, self.y
end

function peg:__eq(other)
    return self.type == other.type
end

return peg
local peg = require((...):gsub("player", "peg"))
local player = class({extends = peg})

function player:new(x, y)
    self:super(1, x, y)
end

function player:movement(button)
    if button == "dpright" then
        self:move(1, 0)
    elseif button == "dpleft" then
        self:move(-1, 0)
    elseif button == "dpup" then
        self:move(0, -1)
    elseif button == "dpdown" then
        self:move(0, 1)
    end
    print(self:position(), self.x, self.y)
end

return player

Unless I'm meant to use the implements config, but that makes more sense for interfaced objects, which is not what I'm doing here. Hopefully I can get pointed to the right direction as to what is wrong.

To clarify a bit: printing the position in peg:draw() does show the initial values I load the player from, but they do not update from player:movement(). The values only change if I check inside the player class.

[Feature Request] tablex.print_r

Description

It would be neat if the function tablex.print_r (or similarly named) was added to batteries. The function would recursively go into a table and print out all the values.

Details

Often I want to print out what is contained in a table. Not really just a specific value, but if I want to validate that multiple items are correct in it.

There's a lot of approaches to doing it, but I'm not sure about their efficiency, which is why I'm raising an issue instead of a pull request. For example, I tend to use the print_r function from mari0.

I think it would generally be beneficial to add this, as it's useful to use when the right time comes.

Other

If there's any questions or clarifications needed, please let me know and I'll do my best to answer them.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.