Hello Lua!

This is the second entry in my Lua Tutorial series. See here for an introduction for this series, or here for our next entry covering variables.

Our first tutorial is going to address writing a basic Lua program. We’re then going to expand over some of the basic features of Lua as well. The goal is to cover using the Lua interpreter as installed, basic printing, and some basic language functions which will be of use down the line.

Well, let’s cut to the chase and get our first “hello world” out of the way entirely. I am going to write this so that people using both Windows and macOS or Linux can follow along.

hello.lua:

#!/usr/bin/lua5.1

print( "Hello World!" )

If we run:
Windows:

lua51.exe hello.lua

*NIX:

chmod +x hello.lua; ./hello.lua

We should see:

./hello.lua 
Hello World!

One thing to keep in mind, since we are writing this on macOS and Linux, we are going to use the shebang (#!/usr/bin/lua5.1). The only real thing we care about for our entire program, is the print command. Print takes an argument or set of arguments and prints them onto the standard output for us. “Print” adds a newline by default.

We can also add to our strings or concatenate them with the “..” operator. This basically adds a string to another string.

hello2.lua:

#!/usr/bin/lua5.1

print( "1" .. "0" )

If we run this, we should see the following:

./hello2.lua
10

We could then edit this to do some basic math, if we write the following hello3.lua:

#!/usr/bin/lua5.1

print( 1 + 1 )

This will then print the string interpretation of 1 + 1 which is 2.
If we continue doing similar, we can also do something like follows for hello4.lua:

#!/usr/bin/lua5.1

print( 1 + 1 .. 0 + 0 )

The will give us the string interpretation 1 + 1 then append the string representation of 0 + 0 giving us “20”. We can continue with different math operations for hello5.lua:

#!/usr/bin/lua5.1

print( 1 + 1 .. 3 - 1 .. 2 * 1 .. 4 / 2 .. 5 % 3 )

This will display 1 + 1 = 2 appended to 3 – 1 = 2 appended to 2 * 1 = 2 appended to 4 / 2 = 2 appended to 5 % 3 = 2 (5 divided by 3 = 1 + remainder of 2 for the modulo operator) for “22222”.

Now, to review, and for readers looking to skip ahead through the explanations, we can put all of this together in a new hello_all.lua script:

#!/usr/bin/lua5.1

print( "Hello World!" )
print( "1" .. "0" )
print( 1 + 1 )
print( 1 + 1 .. 0 + 0 )
print( 1 + 1 .. 3 - 1 .. 2 * 1 .. 4 / 2 .. 5 % 3 )

This should give us the following when run with either:
Windows:

lua51.exe hello_all.lua

*NIX:

chmod +x hello_all.lua; ./hello_all.lua

We should get the following output:

./hello_all.lua 
Hello World!
10
2
20
22222