Hi, I'm Liam

I talk about code and stuff

Lua Collections

Published on

When working on Lua code bases, I frequently find that the code gets more difficult to read as the project gets more complex, partially due to how almost everything in Lua is an iterable table which allows for some extremely powerful functionality.

Introducing Lua Collections.

collections.lua is a port of the extremely robust collections found in Laravel directly to Lua, with some minor adjustments to account for the fact that Lua behaves slightly differently (such as no strict comparisons).

It allows you to take a typical table and use appropriately named methods to perform common functions, such as pagination, shuffling the order of the items, and getting the sum of all items.

There is also a lot of functionality based on using higher order functions, allowing you to pass closures to certain methods to customise what you need to do even further.

For an example of some of the functionality and fluidity this can open up when writing code, see this example below:

collect({'Cat', 'Dog', 'Mouse', 'Elephant', 'Hamster', 'Lion'})
        :shuffle()
        :map(function(key, value)
            return key, value:upper()
        end)
        :append('Coyote')
        :split(3)
        :all()

--[[
    {
        {'DOG', 'CAT', 'LION'},
        {'MOUSE', 'HAMSTER', 'ELEPHANT'},
        {'Coyote'}
    }
]]

You can include the collections.lua file directly in your project or install it with LuaRocks, there are installation instructions in the repository.

You can learn a lot about using collections and higher-order functions to your full advantage in your code in Adam Wathan’s course “Refactoring to Collections” which I highly recommend.

Photo of Liam Hammett
written by
Liam Hammett
Found a typo? Suggest a fix here!
Hit me up on Twitter / GitHub / LinkedIn / email me
Copyright © 2024 Liam Hammett and all that kind of stuff