Category Archives: Lua

Automatic Lua Properties

Automatic Lua Properties?

Starting with an example using the Lua specification and testing framework Busted:

describe("automatic lua properties",function()
    it ("should be clear from an example",function()
        local autoprop = require 'autoprop'

        -- an empty table upon creation --
        local config = autoprop()
        assert.True( #config == 0 )

        -- properties are added dynamically on demand --
        config.some.url = 'http://olivinelabs.com/busted'
        config.some.number = 42
        config.some.other.url = 'https://github.com/nrother/dynamiclua'

        -- this should hold --
        assert.are_equal(42, config.some.number)
        assert.True( #config.some.url > 0 )
        assert.True( #config.some.other.url > 0 )
    end)
end)

Here is a little exercise in Lua metaprogramming.

Code

https://github.com/d-led/automatic-lua-property-tables

Spec: autoprop_spec.lua
Implementation: autoprop.lua

P.S. Other implementations: lua-users wiki: Automagic Tables

function argument sequence

In many APIs one is confronted with the question, which parameter stands for what.

Consider a call in a code you’re reading or trying to write:

is_funkier(1,2)

Is 2 funkier than 1 or vice versa? A long time ago I asked a childhood friends’ father if I could try program their game console. The response was that one has to know a programming language, such as basic. On a request to quote a bit from a programming language I heard “begin, end, goto”. ‘Sounds like English to me’, I replied,’I could do that’. And now, years later I want to program close to English: not Shakespeare but rather a DSL.

A minimal example of how I would improve the API above [1. in Lua here, but not limited to Lua in principle]. Test:

assert( not is(1).funkier_than(1) )
assert( is(2).funkier_than(1) )

And an easy way of implementing the API [2. returning a function would suffice in case of one query]:

local function is(subject)
   local queries = {}

   queries.funkier_than = function(what)
      return subject > what
   end

   -- queries extensible
   -- if subject is stored in the table
   -- queries.subject = subject
  
   return queries
end

Depending on the usage, such constrained argument ordering may improve readability and thus perhaps reduce risks associated with writing code.

To further extend the DSL, further mechanisms can be used of the language of choice. There are some languages that can help remove clutter even further by eliminating punctuation. See also: a nice introduction to creating readable DSLs in Groovy.

Update:

At the time of writing the post was intended as a quick demonstration how such queries/assertions could be implemented. The well known DSLs with this idea are, of course, rspec, Fluent Assertions, AssertJ, with various implementations available in Lua as well