Passing Arguments into Lua
To pass arguments into Lua, the script name and arguments must be enclosed within double quotes. The arguments are stored within the arg variable in Lua, which is a table of strings.
The example below shows how to iterate through the arguments and demonstrates some of the implications of the fact that the arguments are strings.
-- Print the script name
print(string.format('Script Name: "%s"',arg[0]))
FormatString = '%-10s%-10s%-15s%-15s'
print(string.format(FormatString,'Arg#','Type','String','Number'))
-- Iterate through the arguments
Sum = 0
NumberOfTwenties = 0
for i = 1,4 do
-- Print some information about the argument
-- NOTE: The type of these arguments is always "string"
print(string.format(FormatString,i,type(arg[i]),arg[i],tonumber(arg[i])))
-- Check if the string represents a number
if (tonumber(arg[i]) ~= nil) then
-- If the string represents a number, Lua will automatically
-- convert the string to a number for arithmetic
Sum = Sum + arg[i]
end
-- Since the arg values are always of type "string"
-- a direct comparison with a number will always fail
if (arg[i] == 20) then
NumberOfTwenties = NumberOfTwenties + 1
end
end
print('')
print(string.format("Sum of Number Arguments: %d",Sum))
print(string.format("Number of 20s found: %d",NumberOfTwenties))
Here is how to call this script using the LUA command. Note how the string "20" is not considered equal to the number 20.
lua prompt "scriptargs.lua 1 20 Hello 300"
<OK
[COM1]Lua 5.3.4 Copyright (C) 1994-2017 Lua.org, PUC-Rio
Script Name: "scriptargs.lua"
Arg# Type String Number
1 string 1 1
2 string 20 20
3 string Hello nil
4 string 300 300
Sum of Number Arguments: 321
Number of 20s found: 0
>