December 2009 Archives

| 1 Comment | No TrackBacks
In which I learn about metamethods, try my best to restrain myself from abusing them, and get an opportunity to hurl more abuse at Java

I fancied learning a new language, and needed an excuse to do it. Fortunately, I have been assigned to create a raytracer. We'd already discussed the mathematics of it in class, and the end result is fairly obvious, so there shouldn't be too much frustration caused by boxing myself into a design corner accidentally. What better opportunity?

There were two languages hovering in my mind, Lua and Scala. Well, raytracers need performance, and LuaJIT was far more promising in this respect than Scala, so the choice was obvious. It turns out Lua is an amazingly simple language - for something that isn't Lisp or Brainfuck, at any rate.

This also means there isn't any built-in object system, should you want one. Strings are strings, functions are first-class (yay!), integers are doubles (that's much better than it sounds, by the way) and tables are the only data structure you get to play with. Tables are arrays and/or dictionaries, and while the way you access array and dictionary elements are the same - var[x] - they exist independently, for the most part, so your fears of hash-table-backed arrays are unfounded.

You also get to access dictionary elements using var.element, which is equivalent to var["element"] - a nice bit of syntactic sugar which JavaScript also has, and helps you feel as if you're dealing with well-defined objects rather than key/value stores. You can also duplicate JavaScript's prototype-oriented system very easily in Lua (more later). However, that's where the similarity ends.

Along with tables, you also get metatables. They let you customise the behaviour of a table, remapping operations upon it with your own functions. Think operator overloading in C++, except in a dynamic language. Importantly, you get to overload key accesses and writes, though only for keys that don't exist in the table inspected (for performance reasons if anything else). For example, we try to access foo["abc"], but foo doesn't contain abc. So, we call foo's metamethod for looking up table keys, which simply returns the value of the key in another table, bar. Ta-da, you've just inherited the keys of bar for free! You can do more complicated things, if you wish - but use your power with restraint.

I've seen far too many people condemn operator overloading in C++ - and often for good reason, since there are many things to consider, and many assumptions must be made such as the burden of object allocation, exceptions, and dealing with the sometimes-baroque overload resolution rules.

In Lua, however, you have garbage collection, a well-defined exception system (die horribly), and the simple rule of 'call the left object's metamethod, if it doesn't have one, call the right object's metamethod, if that doesn't have one then die horribly'. It's not complicated, and it leaves you to do something sensible, whatever that might mean in your case.

On the subject of exceptions, this isn't like Java where you are forced to catch exceptions for things which are honestly rather trivial, like a NumberFormatException for parsing a bloody integer of all things. Lua's error system is borne from its origins and primary purpose as an extension language, in that it's OK for a chunk of code to error and return control to its caller, since you probably won't have huge chunks of code anyway, and errors worth halting the whole thing are due to faulty program logic rather than edge cases. As a result, Lua and its libraries return error codes for things which aren't the programmer's fault, such as trying and failing to open a file, and raises halting errors for things that are, like accessing a non-existent member of a table. This is further encouraged because the only error control mechanisms you get are error (and assert) for raising errors, and pcall to execute a function and capture either its return value or its error.

It's certainly satisfactory enough for most uses, though I'd rather have Python's more powerful exception handling if I was writing a large program. In any case, error handling depends more on the programmer than the language. Even when it tries to force your hand like Java's checked exceptions does, it's no guarantee you actually solve the problem, let alone in a reasonable way.

There's one thing Lua does better than Python, though (and Java, but that's obvious). First-class functions with real closures. The best way I can express it is being able to pass around behaviour with state as an object like any other, and being able to define it with the same convenience. If something is easy to use, you will use it more often. Being able to define behaviour means you'll readily create functions that accept behaviours, just like map, filter, sort... and thus get one step closer to the Holy Grail of Code Reuse. I think we can all agree that the less new stuff we have to write, the easier it is for us and the fewer new bugs we will introduce. Amen to that.
| No Comments | No TrackBacks
For quite some time I've been plagued by weird electrical problems. I have an old pair of Roland studio monitors - nice, chunky things, give a pleasant sound, but unfortunately a few unpleasant ones, too.

But only when my (visual) monitor is switched on!

It was fine with a different, but inferior monitor - no unpleasant noise to be heard. The annoying thing was that the quality of the noise changed with the image displayed on the monitor, sometimes exhibiting no noise at all. What's one to do, apart from defenestrate various electrical gadgets?

Anyway, I got a new pair of computer speakers which were fine, and thought nothing of it - if I want quality, I have a pair of Shure E3Cs, so no problem. Until I got a new monitor over the summer - plugged it into my laptop, and what do I see? Interference bars, damnit. But I noticed that it went away as soon as I disconnected my laptop from the mains.

A thought occurs.

No, it's not possible to run my laptop from batteries indefinitely. But, due to the process of elimination, something is dirtying the mains supply and ruining things for the rest of us. Laptop power supplies aren't the best in the world and are an obvious culprit, but is there something I can do about it? A few searches suggested that there was noise across the earth which both laptop, monitor and speaker are connected to, and does well to explain why things are just dandy when the laptop is disconnected.

There is an awful lot on the subject of ground loops, which is what I was subject to. I chose the easy way out and disconnected the earth pin from the kettle lead that plugs into the laptop power brick. This is not something anyone would really recommend due to the whole purpose of earth for safety (so if you do it and something bad happens, you didn't hear it here), but considering it's a sealed plastic power brick with a two-pin output, you aren't losing anything. The important thing is my problem is solved and everyone is happy. Just don't reuse that lead for your kettle, fer'chrissakes.
| No Comments | No TrackBacks
I love animals. Cute ones, especially. Here are some fine examples that I took only this morning at Bristol Zoo - I hope you enjoy them too!

| No Comments | No TrackBacks
It may not look impressive but it was tasty.
 
Improv Veggie the First
The contents of this dish:
  • 1/3 green pepper
  • a small quantity of Quorn mince (or just mushrooms)
  • half a leek
  • a spring onion
  • 1/3 tin kidney beans
  • half a tin of chopped tomatoes
  • large clove of garlic
  • 1tsp basil
  • generous splash of soy sauce
  • an even more generous splash of rosé wine
  • 50g mature cheese
  • 100g pasta
  • salt and pepper to taste
If nothing else, it's healthy, fills a hole and is, at the very least, pleasant. Learning to make do with whatever's to hand is a very useful and frugal skill, and it needn't be disappointing. Have some confidence, learn how to handle all your ingredients, and add a sprinkle of imagination.
| No Comments | No TrackBacks
That's it, my last deadline of 2009 has been met. It's rather too tempting to spend the day making ice cream, playing TF2 (team Demo!) and going out on the town, so that is precisely what I'll do. But only today!

Tomorrow, however... that is when I start my Coder series on

Building a raytracer in Lua

Serving both as the solution to one of my assignments and a diary of my experiences learning a new-to-me, yet very promising language, and one that receives wide usage in the games industry already. I'd do well to know it, especially since MMF2 has a Lua interpreter extension.

Raytracers are very computationally intensive, which is why they're generally written in C(++). As far as performance is concerned, LuaJIT appears to be doing reasonably well for itself, and you get the benefits of dynamic typing, closures and first-class functions. You also have a rather flexible object system - as in, there isn't really one, but the language features plus a little syntactic sugar give you the tools to develop a model that fits your particular circumstances. You know, like Perl, except without the feeling you're filling your source code with censored profanity.

A raytracer might not need all that flexibility, being one of the most naturally-object-oriented applications you can make, but I certainly don't intend to make raytracers all my life. Or ever again.

Plus, since I'm not Steve Yegge, the lack of braces isn't a turn-off. Besides, the benchmarks I've seen put the V8 JavaScript engine slower than LuaJIT - though I have no idea whether that holds once you make a more substantial program.

At the very least, compared to Win32 C programming, Lua will be quite the welcome break. Once you've had a taste of functional programming, writing in C again seems nearly as painful as if you'd lost your compiler and had to resort to typing COPY CON: OHGODWHY.EXE (and believe me, typing italics into a command prompt is tricky stuff). Time will tell whether it's all I've cracked it up to be.
| No Comments | No TrackBacks
Amazingly succulent, sweet and slightly fruity - HP sauce, eat your heart out

Bacon sandwich

Ingredients

  • Two slices wholemeal or seeded bread
  • Two rashers smoked bacon
Cook as usual! I pan-fry on a reasonably high heat - the bacon is thin enough that it doesn't take very long, and the fat crisps up beautifully. Meanwhile...

Sauce
  • 2tsp tomato ketchup
  • 1tsp soy sauce
  • 1tsp dark muscovado sugar
  • 1/4tsp onion granules
  • 1/4tsp garlic powder
  • a few drops of malt vinegar
  • one drop of worcestershire sauce
Mix all the ingredients together in a ramekin. Place in a microwave on high power for 5 seconds, remove and stir, then microwave for another 5 seconds. Spread over the bread.

Update: even best-er with grated cheese over the bacon. Give in to the fat, don't resist it, you know you want some...