Sunday, 4 September 2016

Lua inf, -inf and nan

The Lua number datatype has the conventional three special values inf (positive infinity), -inf (negative infinity) and nan (not a number). It seems not to be so conventional when it comes to comparing these values. It returns true when comparing inf with inf, -inf with -inf, and nan with nan. I believe that mathematically this is not quite correct. However, I can see the advantages of being able to compare them from a programming perspective.

Saturday, 3 September 2016

Preparing to Learn Lua

I took my second step in preparing to learn Lua. I've set up a simple training project through which I can get a feeling of the workflow and practices that will work for me when programming in Lua. I've based the project on the StockFetch example from Test Driving Javascript Applications by Dr. Venkat Subramaniam. (A very worthwhile read).

Before I set up the project, I wanted to see how easy it would be to read the contents of a web page in Lua. It turned out to be very easy once I had installed luasocket.

    sudo luarocks-jit install luasocket

Reading a webpage highlighted, for me, the ability to return multiple values from a Lua function:

   http = require 'socket.http'
    body,code,headers,status = http.request('http://bbc.co.uk')

I also noticed that much Lua is written defensively in the sense that care is taken to minimise opportunities for crashes through the use of the assert function and other such techniques. Clearly, being able to return a status code and a value from a function will help to write robust code.

Knowing how to read websites in Lua, I proceeded to set up the project. I adopted a directory structure that will be familiar to many people but I don't know how common it is in Lua circles.

The basic structure is:

    stockfetch/                           -- main directory
        stockfetch-cli.lua                -- command line interface
        src/                              -- lua modules
            stockfetch.lua                -- main app module
        test/                             -- tests
            stockfetch-busted.lua         -- busted tests
            stockfetch-unit.lua           -- Lua unit tests

After setting up the project, I wanted to work out how best to test its main program, stock watch-cli.lua. It's basically a three line script to initiate the main stockfetch module.

      local stockfetch = require('src/stockfetch');
      local rc = stockfetch.run()
      os.exit(rc)

I'm glad I did as I found out a few things about file paths in Lua that were useful to know from the off:
  • Lua retains the current working director setting from the OS. So relative paths calculated in a script can change depending on the directory from which the script was launched
  • Another way of looking at that is the Lua does not change the current working directory to that from which a script is loaded
  • The dofile function only accepts absolute file paths
  • There is no builtin function to "clean" a file path limiting the use of setting a base-file path and a relative path including ../
It soon became apparent that I wasn't going to be able to test stock watch-cli by using docile. (I would be delighted to learn of such a way if there is one.) Instead, I used Lua's command line interfaces to test it.

I found two different ways to run command line programs from Lua - os.execute and io.popen. The first returns the return code from the command executed, the second returns the output from the command. I wanted both, so I chose to use os.execute and redirect the command output to a file. That way I'm able to get both the output and the return code.

I successfully wrote tests in both Busted and LuaUnit using this approach. 

Finally, I loaded the project into a GitHub repository.

Next, I will complete the stockfetch app following a test-driven approach and start to learn how to code in Lua.

Sunday, 28 August 2016

Busted or LuaUnit?

Having decided to learn Lua and testing Lua at the same time, I need to decide on a testing framework. There seem to be quite a large number available. I was guided to look at Busted and LuaUnit. Both seem active, professional and have good documentation. They have quite different approaches and it is hard to chose between them without any experience of them. 

I have decided to use them both whilst learning Lua. That decision will, no doubt, slow my learning a little but it should give a greater depth to what I learn.

To get started quickly, a took a function from a Prag Prog Magazine  article "a-functional-introduction-to-lua" and created a module to put it in and wrote both Busted and LuaUnit tests for it.

Here is the module and function:

    local learnLua = {}

    function learnLua.namesOf (things)
      local names = {}
        for index, thing in pairs(things) do
    names[index] = thing.name
  end
      return names
    end

    return learnLua

Here's the Busted test:

    require 'busted.runner'()
    local ll = require 'learnLua'

    describe("Flames with Lua", function()
      describe("namesOf", function()
        it("extract string names", function()
          local cats = {
            { name = "meg", breed = "persian" },
      { name = "mog", breed = "siamese" }
          }
          assert.equal("meg", ll.namesOf(cats)[1])
          assert.equal("mog", ll.namesOf(cats)[2])
          assert.equal(2, # ll.namesOf(cats))
        end)
      end)
    end)

Here's the LuaUnit test:

    luaunit = require 'luaunit'
    ll = require 'learnLua'

    local cats = {
      { name = "meg", breed = "persian" },
      { name = "mog", breed = "siamese" }
    }

    function testNameExtract() 
      local cats = {
        { name = "meg", breed = "persian" },
  { name = "mog", breed = "siamese" }
      }
      local names = ll.namesOf(cats)
      luaunit.assertEquals(names[1], "meg")
      luaunit.assertEquals(names[2], "mog")
      luaunit.assertEquals(# names, 2)
   end

  os.exit( luaunit.LuaUnit.run() )

Both tests pass:
    $ luajit learn-unit.lua            
    . 
    Ran 1 tests in 0.000 seconds, 1 success, 0 failures    OK

    $ luajit learn-busted.lua    ●
    1 success / 0 failures / 0 errors / 0 pending : 0.000617 seconds

Not a lot to chose between them when testing such a simple function. I need to work up to something more complex to really see the differences between them.

I'd be happy to learn about improvements in style or form that I could make in writing Lua, Busted tests and LuaUnit tests.

There is some early feedback on Busted and LuaUnit in Test Doubles and you can read my conclusion in Busted or LuaUnit? Answered

Installing LuaJIT and Luarocks on OS X

Thanks to Homebrew, installing Lua on OS X is easy. I wanted to install the LuaJIT version as that is the one that I'm likely to be using in the future. It was just a matter of:

    $ brew install luajit

I also wanted to install the Luarocks package manager. My first attempt failed.

Then I found the very helpful instructions at Mesca's Homebrew-Luarocks page. 

Sadly, it is no longer available via Homebrew. I need to find a new method to install Luarocks to use with Luajit

Learning Lua

It looks as though I may be working on a project using Lua and I thought it would be a good idea to start learning the language ahead of time. I know JavaScript and Red which like Lua are influenced, either directly or indirectly, by Scheme. I'm hoping my knowledge of them will help me in understanding both the concepts and philosophy of Lua.

The most common way of learning a new language, especially one with a command line interpreter, seems to be to experimenting with coding whilst reading or going through a tutorial. Once you've learnt the language, you go on to learn about its environment - modules (or packages), testing and the like. 

I'm going to adopt a different approach to learning Lua and try to use things  such as modules and testing from the outset. Over the next few months, we'll see how well it works for me.

Sunday, 3 May 2015

Installing gtk3 Ruby Gem on OS X Yosemite

As I found installing the gtk3 Ruby Gem on OS X Yosemite is a little fiddly, I thought I'd make a note of how to do it for next time so that I don't need to spend time searching the internet to found out how.

First, you need to install X-windows. That's pretty straightforward simply click on the X.11 icon in the Others collection in LaunchPad and follow the instructions.

Second, you need to install gtk+3 itself. Using HomeBrew that's straightforward:

    brew install gtk+3

Then the tricky bit. You need to help gem find the correct libffi library. I found  out how to do it thanks to the Ruby-Gnome team:

   sudo PKG_CONFIG_PATH=/usr/local/opt/libffi/lib/pkgconfig gem install gtk3

Wednesday, 4 March 2015

Trying to Like Python

Having fun with projects on the Raspberry Pi would be so easy if I could overcome my dislike, in all probability based on my misperceptions, of Python. When it comes to Raspberry Pi, Python sits at the top table whereas Ruby wouldn't even get the crumbs of the floor if it wasn't for Sonic Pi.

I still have a belief, may be an irrational one, that it is easier for young kids to learn Ruby than Python. However, I know for a fact that it is a infinitely easier for them to use Python in Raspberry Pi projects.

Update: I still am finding Python difficult to like.