Hello World in Lua
Every programming journey starts with “Hello, World!” This simple program demonstrates the basic structure of a Lua script and how to output text to the console.
Your First Lua Program
Create a new file called hello.lua using any text editor:
print("Hello, World!")Save the file and run it from your terminal:
lua hello.luaYou should see:
Hello, World!Understanding the Code
Let’s break down this simple program:
print()is a built-in Lua function that outputs text to the console"Hello, World!"is a string literal containing the text to display- The parentheses
()contain the arguments passed to the function - The line ends with no semicolon (unlike many other languages)
Interactive Mode
You can also try this in Lua’s interactive mode:
luaThen type:
> print("Hello, World!")
Hello, World!
> Adding More Output
Let’s expand our program with more information:
print("Hello, World!")
print("Welcome to Lua programming!")
print("Lua version:", _VERSION)The _VERSION variable automatically contains the current Lua version.
Comments in Lua
Add comments to explain your code:
-- This is a single-line comment
print("Hello, World!") -- This prints a greeting
--[[
This is a multi-line comment
that can span multiple lines
Useful for longer explanations
--]]
print("Program finished!")Running Lua Code Directly
You can also run Lua code directly from the command line:
lua -e "print('Hello from command line!')"Next Steps
Congratulations! You’ve written your first Lua program. Next, learn about variables to store and manipulate data.
For more Lua examples and exercises, check out Lua Users Wiki.