Function Parameters: Passing Information Into Functions

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.

Define a Function with a Parameter

Explanation:

  • The comment states the function’s purpose.
  • local function greet_user_by_name(name) defines a function and introduces a parameter named name. 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.
  • end closes the function.
Call the Function with an Argument

Explanation:

  • We call greet_user_by_name and pass "Alex" as the argument. The argument fills the name parameter inside the function.
  • When this line runs, the function prints: Hello, Alex!
  • Try running this in CodeSignal to see the output immediately.
Default Parameter Values in Lua

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 if name is nil or false. 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.

Summary and Next Steps

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.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal