7.2 Command Line Arguments in Lua
Moving to our Lua example and run the tests.
1cd ~/lua 2busted
These tests fail because we updated the exercise setup and we have not yet written the new Lua code.
1-- 20 successes / 2 failures / 0 errors / 0 pending : 0.005102 seconds 3 4Failure → spec/convert_spec.lua @ 2 5convert shows greeting 6spec/convert_spec.lua:6: Expected objects to be the same. 7Passed in: 8(string) 'Hello World! 9' 10Expected: 11(string) 'Hello ! 12' 13 14Failure → spec/convert_spec.lua @ 8 15convert shows greeting 16spec/convert_spec.lua:12: Expected objects to be the same. 17Passed in: 18(string) 'Hello World! 19' 20Expected: 21(string) 'Hello Mark! 22'
We fix this by editing the Lua program to contain the following.
1name = arg[1] 2greeting_message = "Hello " .. name .. "!" 3print(greeting_message)
As in our Bash example we are assigning the command line argument to the variable name. Unlike Bash, Lua creates a special variable called arg. This arg variable refers to data in a ‘table’. Briefly (we look at tables in more detail later) a table is like a list of other data where each item in the list can be referred to using a key. In this case the table contains a list of the command line arguments, each argument is referred to by its position on the command line (so the key 1 in this example refers to the first argument passed on the command line).
Line 2 looks very different to the Bash version too. Here we are concatenating (the two dots .. tell Lua to take the string to the left, make a copy and then append a copy of the string to the right) three strings; the literal string "Hello " (note the space), the string held in name, and the literal string "!". The resulting string is then assigned to the greeting_message variable.
Line 3 is unchanged.