Jan 20

Getting started with Lua

"Lua does not try to help you write programs with hundreds of thousands of lines. Instead, Lua tries to help you solve your problem with only hundreds of lines, or even less." This sounds pretty interesting right? Here is how I got started with Lua.

So lately I've come to the joy of joining a development team who uses Lua extensively, mainly as an embedded scripting language for C++. For me as a Java dev this sounded really interesting and so I started an expedition into the world of Lua and wanted to give a short introduction and a couple of links I found useful. Please note I am still just playing with Lua, haven't written that much code in it yet, but so far I can say: It's definately worth a try.

What's the first thing you do, when you take a look at a new language? Well at least I do: "Hello World" ;-) To actually see Lua in action you don't even have to download anything. lua.org offers an online demo for the language. So what does it take for a hello world?

print("hello world")

Yep, that's it. Easy, huh? ;-) Now what else can you do? Expand our example a bit, but before doing that I decided to get Lua installed on my Kubuntu VM. Fun story, it is already installed, so Ubuntu ships Lua with it. To start the Lua shell you just have to type lua. Now inside the shell you are able to basically do anything you want and just try things out, for example

original = "Check it out - this is one long text."
changed = string.gsub(a, "long", "even longer")

So this is an easy method to replace / exchange the contents of strings. Now what was new for me, there is no such thing as String original to declare original as a String. That saves you some time ;-).

You can put all of the code into a Lua file (ending with .lua) and then call this file using the Lua interpreter: lua stringswitch.lua. This will run it and print the two strings. Now the last thing I tried was expanding my hello world example to:

text = "Hello"
name = io.read()
print(text .. " " .. name)

The two dots (..) append the following string to the leading one, So inside the print method Lua takes the text appends a whitespace to it and then appends the name. The result will be Hello Stefan if you enter "Stefan" when prompted for an input.

Those were my first steps in the process of getting to know Lua, so far I like it, it's fun to use and has nice and very important intuitive methods to offer.

Some links:
Lua.org - Official homepage
Programming in Lua - complete book online
The Lua online demo interpreter
My github repository for my lua learning path

Please feel free to comment, contact me with questions via email, twitter or in a different way. Would love to get some feedback and opinions on Lua.