Categories
Programming

Language of the Month: Lua, part 2

I’m a few days behind schedule since Lua was June’s language, but here it comes, some summary of my experience, after setting things up in the first part.

A Trip to the Moon / Le Voyage dans la Lune
Lua is not this painful, indeed, just the opposite

Overview

I really liked this language, and I’m sure I’ll keep learning it. Very useful and lots of interesting concepts. I haven’t seen an embedded language before, and some parts

Most of what I picked up was from Beginning Lua Programming and Programming in LuaLua Missions was another very useful experience: a “fill in the blank” type of source code collection, which drilled my understanding of the Lua concepts. Some sections felt a little short, so maybe later I’ll think whether there are any more questions I can come up with. Very well worth the time!

There are two things that stand out: tables and local environments.

Tables

If I have to refer to my knowledge of Python, then Lua tables are like Python lists and dicts rolled into one and then some. Here’s one such table:

x = {1, 2, 3, y = "something", ["or else"]="what"}

The first three elements are giving an array (and one can loop over them), then the last two are key-value pairs. One tricky thing is that the “y” there is actually a string (the same as [“y”]), just made it more readable with syntactic sugar. Since variables (references to variables) can be keys as well, this can get confusing if one has a variable called “y”… There are quite a few things about tables that are confusing, but actually pretty consistent so my fuses are not blowing that much as they were in the beginning (for example: how the length is looked up, how to iterate through the different values) .

They are very complex animals so some things are quite complex to do, which in turn enables quite complex things to be done. Pretty much any kind of data structure can be built upon them. So all in all, I’m enjoying them with all their quirks. Also, “weak tables” are an interesting concept (where certain table entries can garbage collected).

Scopes

In Python, the name spaces and environments seem to be on the sidelines (at least what I’ve seen so far): people need it and have to us it, but nothing more than that. In Lua this is taken to a whole new level: scopes can be essential parts of the way algorithms are implemented and neat tricks can be played.

I tried to come up with some good example and failed, here’s a “duh” one:

function newCounter ()
    local i = 0
    return function ()   -- anonymous function
        i = i + 1
        return i
    end
end

c1 = newCounter()
print(c1())  -- 1
print(c1())  -- 2

This is a bit like Python’s “yield” type of generator, without anything special.

Also, in Python there are only two kinds of variables (I think): local and global: either just for you or for everyone. Here they have one more: upvalues, where the variable is local to a parent, so children environment can access them but the parent’s parents cannot. They are strange beasts as well, e.g. the code itself cannot really know if a variable is upvalue or global, only that it can access that.

And of course these scopes help embedding to not just be possible but straightforward and powerful. Local environments can be restricted, some things selectively enabled, and all this transparently, so the script running might not even know that it’s being in the Matrix.

The Lua Experience

Good

  • Fast, both start up and running
  • Language itself is quite small, possible to wrap one’s head around quite easily
  • Written in ANSI C, so basically on every architecture where one can run C, one can have Lua as well
  • Quite a few program has Lua interpreter or interface built in, see the list of these at Wikipedia
  • Tables are great and once one mastered them, are really Swiss Army Knives
  • Built in interpreter (though could use a little love like iPython)
  • The “…” syntax for variable number of arguments
  • Astrological naming convention – modules are rocks, the exercises I linked previously are missions, web framework is Kepler

Bad

  • There seem to be a lot of reserved names (e.g. in metatables) that would be pretty much impossible to figure out with a book (and/or an iPython-like helpful environment), though this is a problem probably only when starting out with Lua

Ugly

  • While some complex things can be solved, some simple things can require complex coding (e.g. in case of the tables when using “__index” and “__newindex“) and there are things that are not even possible. Or I just misunderstood some sections of the book.
  • Using a lot of syntactic sugar (especially in the object oriented section), that I feel need some more practice to pick up, as things can be done in multiple ways
  • The tables’ syntactic sugar covered way of handling string keys, convenient when things go well, mighty confusing at even the slightest problem
  • Too few projects using Lua, too few sources of information (this is not the language’s fault, though)

Project

Originally I wanted to do some useful programming in every language I learn during the Language of the Month series. I failed with Scala (lazy), and now failed with Lua too (underestimating the difficulty). I’m using VLC a lot and it has Lua scripting enabled, so I wanted to do a plugin that can be useful for me later as well. This didn’t work out very well, mainly because it feels the VLC Lua interface is not very well documented, one mostly have to find some examples that exist already and use them. I ended up wasting a lot of time and still don’t quite understand how to do certain things I would like for my code, and don’t even know if it’s possible to do or not. Will come back to it later, until that here are a few links that helped me to get started:

  • VLC Lua FAQ – detailed list of available API functions, but almost no context and examples
  • Lua extensions in the VLC git repo – one can pick up something by checking out those examples
  • Example: Streaming Radio Player Extension – someone who have gone further down this road than me and has a working extension. Very educational, especially to see how concise and straightforward it can be, because the VLC Lua API seems to be thought out well.

Again, hopefully pick this up later (I mean it).

Categories
Programming

Language of the Month: Lua

New month, new language. So far in this series:

I think I do want to amend the original rules set up for this Language of the Month series. At first I though I can write a new project in any language I learn. That is probably too ambitious. So new rules: every month write a new project in the given language OR contribute to an open-source project in that language. This should take away most of the stress and add some social aspect as well. :)

Lua

I’m intrigued by this language because of it’s niche: scripting language within other software. How one sets out to do something like this? What are the requirements for the language, in terms of design, syntax and so on?

Lua programming language logo
See, the moon!

First impressions

So far I was trying out some code snippets and example scripts. First thing to notice was that Lua is pretty darn quick to start. And pretty quick to run as well, though I haven’t used it for very heavy computation yet. E.g. the “get_all_factors” code at the Lua Crash Course (using a larger example number, 1029384756) is timed at ~7ms, wheres the same version on Python (the language that I probably know best and compare other languages to) runs ~10x slower. The snappiness of a scripting language is a surprisingly happy feeling. :)

Tables look very interesting, how the same thing can implement several data structures at once (it’s like Python’s dict, list and kinda-struct at the same time).

Quite intriguing that the Lua Virtual Machine is stack based, probably that’s the reason the language is so embeddable. A while back I was looking for a language with small resource (especially memory) requirements. I had a few suggestions (Dalvik, Forth) that were interesting, but maybe Lua is the one?

The “local” keyword (and the reasons for having it) seems to be a possible source of many harder to debug scenarios. Got to keep this in mind, again not being in Pythonland anymore.

Interesting how the “function” can be defined inline, so looks like there’s essentially no need for a special “lambda” keyword, at the expense of tying a few characters more…

The interpreter is quite well done (with it’s intelligent indentation probably even better then ipython, though would love to see more colours ^^)

As an exercise, here’s a version of FizzBuzz:

function fizzbuzz(num)
   --[[--
   The usual FizzBuzz from Jeff Atwood
   Doing it a bit roundabout to try some Lua language features
   --]]--
   local answer = ""

   if (num % 5) == 0 then
      answer = "Fizz"
   end
   if (num % 3) == 0 then
      answer = answer .. "Buzz"
   end

   if answer ~= "" then
      print(answer)
   else
      print(num)
   end
end

-- Run the thing
for num=1,100,1 do
   fizzbuzz(num)
end

Links

This section will be updated gradually as I find more information.

(Edit: added the second part of this experiment.)

Install

Tutorials

Books

Articles and info

Source of code

Projects using Lua

Categories
Programming

Language of the Month: Scala, part 3

This is a post I should have written yesterday, actually, since it is already June, ready for the next “Language of the Month“. Still, let’s finish off this May Edition.

Taking score

First, I should have spent more time on practicing Scala, as I haven’t actually finished anything in the end. It is probably an excuse, but after using Python for such a long time, getting used to a compiled language with its own weird path-, naming- and import conventions, was just a little bit too much. Mostly I was reading the Pragmatic Bookshelf: Programming Scala, practicing the examples within. That book uses Scala 2.7.x and the current version is 2.9.0.1, so there are a few things that work differently and I ended up having strange error messages with little to no clue how to fix them (mostly imports, and some method signatures must have changed as well). So it was a limited but exciting success.

Scala screenshot
Using them example code

All in all, I liked the language even if I don’t have a clear usage case for it in my mind (just yet). Some bullet-points of my experience:

Good

  • Different way of thinking about “batch” operations (i.e. foldLeft)
  • Once I figure out the Actors that well that I can write related code without referring to the tutorials, that’s going to be a very powerful tool
  • Pattern matching, pattern matching everything. This is one thing that blown my mind in the little Haskell I checked so far, and missing from Python a lot.
  • Flexibility with class definitions, they can handle so many different situations in a very logical and powerful way

Bad

  • Length of compilation and program start. Will have to get used to it, though I read some hints that this can be improved.

Ugly

  • Pretty frequent need of using things directly from Java, so one is never quite independent
  • Special methods that have reserved name for certain functionality (act, apply, …) that are non-obvious, and not easily distinguished from the arbitrarily defined methods.

Future

Definitely will come back to it and learn it in more detail. It looks like a fine language to do parts of larger projects in. In the meantime I will update the link collection in the previous post with new links that I find. I certainly notice more and more Scala posts on Hacker News these days.

Categories
Programming

Language of the month: Scala, part 2

For the last 3 weeks or so I was checking out Scala, and will do for a little while more, so just want to do a little catch up where things are at the moment.

Start

I tried to find a couple of starting points to start to know about Scala. First thought video tutorials or talks would be useful, so been around checking on YouTube. It seems the mainly referenced intro is Scala: a scalable language. Well, it told me a lot about how Scala compares to other languages and how is it better than those, but not much to start learning it. Though the talk made it sound like it is one of the best and most modern languages out there, taking the most useful ideas from loads of other languages.

Had a copy of the Pragmatic programmer: Programming Scala, and just finished going through it. By that I mean that skimmed all the chapters and did try some of the code samples that looked interesting or strange. Not bad, but from the book I just have a very limited answer to the question of: “but what is it really great for?” Concurrency, sure, but that is probably not all.

I don’t know a language before I code enough in it, but before I know it I don’t have to much inspiration what to code. In this case, programming puzzle sites come very handy, though not all of them support Scala. I went to Coderloop because they do and I can submit my solution for performance testing, or could use Project Euler because they are language agnostic (one sends the results only).

Experience

Since Scala is built upon the Java Virtual Machine and supports pretty much all of Java, it feels a little Frankenstein language: every now and then, even for some things that should be quite commonly used, things have to be programmed in Java. Lots of language features are cool, though, even if most of it feels just syntactic sugar. In a way, maybe the whole language is just that? It’s not bad, makes things very concise and powerful, but always feels there’s something more in the background.

Actors and concurrency are pretty cool, though. In the talks I’ve seen people compared them to Erlang, just even more powerful. This is something more to play around with, would like to make something interesting, scalable and fault-tolerant – those are the fun stuff aren’t they? (But this also makes me want to try Erlang soon so I can compare).

Since I was doing mostly Python lately, it feels a bit weird to use a compiled language. For simple programs, it takes quite a long time to do that compilation, enough to wind me up a little when I was troubleshooting. That said, maybe I’m doing a little bit too much “programming by accident“, so I deserve it? Also, starting a Scala program takes a while as well, though once it is up and running, it’s pretty fast.

At this point, I’m not totally sure yet what project to make until the end of the month. I need more programming itches to scratch. The only ideas I came up so far are self-playing games with actors. Or some server/provider. Well, just keep brainstorming, something better has to come up. Maybe when I dive a little bit more into it, since at the moment I cannot really “think Scala” yet.

There’s also a web framework for it, called Lift, which is probably not surprising. The close connection wit Java (and hence with so many of enterprise software) and event based, fault tolerant concurrency is just too juicy. Not sure if anyone’s hosing it, tough (got to check out), either way I can just try it on my local network. I wonder how does it compare to Django, since that’s what I have a bit of experience with.

Links

Information

Example sources

Companies using Scala

Others writing about Scala

(Last updated: 2011 June 23)

Categories
Programming

Language of the Month: Scala

I was thinking what what to write about, but then I realized that is doing this whole blogging thing completely the wrong way. I should be thinking what to do and interesting things to write about will come out of that. It always does.

I was watching the Programming Paradigms lecture series from Stanford. I quite enjoy it, mostly because Jerry Cain seems to be a good lecturer. A quick check confirms that others feel that too. I haven’t finished it yet (24 lectures in to the 27 long series, each ~50 minutes), he talked a lot about C, then Scheme, now about Python. He also mentioned a couple of other languages he suggest for the students to try. That got me thinking: I love languages (human and programming as well) and always looking out to learn more things. Why not do some more exploration in this area – trying out languages that are quite different from each other and see what can I take home from each. I did have similar idea last year, “Language of the Week”, but one week is just too little to get to any practical depth in a language and that idea died. Now, I’m hoping to resurrect it in the form of “Language of the Month”. It is conveniently the beginning of a month so I can just start right now. :) Also, let’s make it round – a 12 language series, one for each month until the same time next year. That should be a challenge. So I made a 12 item list for planning:

Many of these I was planning to check out for a long time and now I have proper motivation. Some of them I got intrigued about while I was checking this humbling list. Note, that “?” are not weird languages, but I keep things open to add more as I get more experience with this (you too can give me recommendation in the comments!:). Also note the absence of some languages, like C and Ruby: those I really should know more, that’s why I won’t do them here, they have enough intrinsic motivation, here I want to try somewhat more off-the-path things.

The simple rule for this series is: every month choose one new language and by the end of the month implement something practical in that language. Something that scratches a real life programming itch. Other than this, all bets are off. See what I can learn.

Now the hard part: which one to start with, since the above list is rather a “set” – ordering is not included. I did roll a dice, but didn’t like the result (like most rolls of dice:), so let’s just choose one: The Language of the Month for May is Scala (because I know absolutely nothing about that, unlike some of the others).

Let the coding begin…

Emacs editor screen, ready to accept source code input
What will this space contain?