Your First Lua Function

Welcome to the first step in writing functions in Lua. In this lesson, you will learn how to define a simple function and how to call it. Functions help you organize code, avoid repetition, and make your programs easier to read.

Define and Call a Function

Here is a small program that defines a function and then calls it:

Explanation:

  • The comment explains what the code is about. Comments help you and others understand your code.
  • local function greet_user() creates a function named greet_user. The keyword local keeps this function limited to the current file, which helps prevent name conflicts. The empty parentheses mean it takes no inputs.
  • print("Hello, traveller!") is the action the function performs. It will run only when the function is called.
  • end closes the function body.
  • greet_user() calls the function. When this line runs, the message is printed to the output.

On CodeSignal, run the file to see the printed text in the output panel. No extra libraries or setup are required here.

Summary and Next Steps

You have learned how to:

  • Define a function with a name and a body.
  • Use local to keep your function scoped to your file.
  • Call the function to execute its code.

Functions are the building blocks of clean, reusable programs. Ready to put this into action? Head to the practice section and try it yourself.

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