In the previous lesson, you defined and called a simple function with no inputs. As a quick reminder, that function ran the same way every time because it had no data coming in. In this lesson, you will learn how to make your functions flexible by giving them parameters — placeholders that accept information when the function is called. This is how you customize a function’s behavior.
Explanation:
- The comment states the function’s purpose.
local function greet_user_by_name(name)defines a function and introduces a parameter namedname. This parameter is a placeholder for the value you will pass in later.print("Hello, " .. name .. "!")builds the message using the string concatenation operator..to combine text and the parameter value.endcloses the function.
Explanation:
- We call
greet_user_by_nameand pass"Alex"as the argument. The argument fills thenameparameter inside the function. - When this line runs, the function prints: Hello, Alex!
- Try running this in CodeSignal to see the output immediately.
Lua does not support default parameter values directly in the function definition like some other languages. However, you can easily set a default value inside the function body using the or operator.
Explanation:
name = name or "Guest"checks ifnameisnilorfalse. If so, it assigns"Guest"as the default value.- Now, if you call
greet_user_by_name()without an argument, it will greet "Guest".
Example calls:
This pattern allows you to provide default values for parameters in your Lua functions.
You have learned how to:
- Define a function that accepts a parameter.
- Pass an argument when calling the function to customize its output.
- Use
..to concatenate strings with variable values.
You are ready to practice by writing your own parameterized functions and exploring how different inputs change the behavior. Let’s head to the practice section and apply what you have learned.
