function sayHello(name)
print("Hello, " .. name .. "!")
end
That function is a simple function, and it works well. But what would happen if we just called sayHello()
?
stdin:2: attempt to concatenate local 'name' (a nil value)
stack traceback:
stdin:2: in function 'sayHello'
stdin:1: in main chunk
[C]: in ?
That's not exactly great. There are two ways of fixing this:
You immediately return from the function:
function sayHello(name)
if not (type(name) == "string") then
return nil, "argument #1: expected string, got " .. type(name)
end -- Bail out if there's no name.
-- in lua it is a convention to return nil followed by an error message on error
print("Hello, " .. name .. "!") -- Normal behavior if name exists.
end
You set a default parameter.
To do this, simply use this simple expression
function sayHello(name)
name = name or "Jack" -- Jack is the default,
-- but if the parameter name is given,
-- name will be used instead
print("Hello, " .. name .. "!")
end
The idiom name = name or "Jack"
works because or
in Lua short circuits. If the item on the left side of an or
is anything other than nil
or false
, then the right side is never evaluated. On the other hand, if sayHello
is called with no parameter, then name
will be nil
, and so the string "Jack"
will be assigned to name
. (Note that this idiom, therefore, will not work if the boolean false
is a reasonable value for the parameter in question.)