5.2 Hello World in Lua

1cd ~/lua 
2busted

The busted command runs a set of tests to confirm that the requirements have been met (these tests are often called ‘acceptance tests’). Later in this course we will look at these tests and how, when, and why to write our own tests.

busted
1lua: cannot open bin/convert.lua: No such file or directory 
2- 
30 successes / 1 failure / 0 errors / 0 pending : 0.0029 seconds 
4 
5Failure  spec/convert_spec.lua @ 2 
6convert shows greeting 
7spec/convert_spec.lua:6: Expected objects to be the same. 
8Passed in: 
9(string) '' 
10Expected: 
11(string) 'Hello World! 
12'

The busted tests are currently failing, which should be unsurprising as we have not yet written any code. The output from busted may be confusing but don’t worry too much about it at the moment, the main things to notice are on line 3 (telling us we had one failure) and line 1 (telling us that the test was trying to run the script bin/convert.lua but it could not since that script does not exist yet).

On line 6 we are told that busted was trying to confirm that the convert script ‘shows a greeting’. Lines 7 through 12 tell us that we are expecting the output to be ‘Hello World!’ (ending with a newline character).

Let’s now write the code to satisfy our requirement.

1mkdir bin 
2touch bin/convert.lua

These commands create the convert.lua file (unlike the bash script in §5.1 we don’t need to make this script executable as it will be passed to the lua processor as a simple text file—we look at how to treat lua scripts as executables later). Now we will edit that file and print out our message.

1vi bin/convert.lua

Add the following, single line, to the bin/convert.lua file and save the file.

bin/convert.lua
1print("Hello World!")

Running bin/convert.lua will print the message ‘Hello World!’ followed by a new line to the screen.

1lua bin/convert.lua
bin/convert.lua
1Hello World!

If we now run our tests they pass.

1busted
busted
1o 
21 success / 0 failures / 0 errors / 0 pending : 0.002722 seconds

The only interesting line in this output is line 2 where we are told we ran one successful test with no failures.

Congratulations! You have written a simple lua script that outputs a message to the screen.