Learn Lua in Neovim: Comments & User Input — io.read() & tonumber() | Episode 6
Video: Learn Lua in Neovim: Comments & User Input — io.read() & tonumber() | Episode 6 by Taught by Celeste AI - AI Coding Coach
Watch full page →Learn Lua in Neovim: Comments & User Input — io.read() & tonumber()
In this episode, you will learn how to add comments in Lua using single-line and multi-line syntax, and how to toggle comments efficiently in Neovim with Comment.nvim. Additionally, you'll discover how to make your Lua scripts interactive by reading user input with io.read() and converting that input to numbers using tonumber().
Code
-- Single-line comment: this line is ignored by Lua
--[[
Multi-line comment:
Everything inside these brackets is ignored by Lua
]]
-- Prompt the user for their name
print("What is your name?")
local name = io.read() -- Reads a line of input from the user
print("Hello, " .. name .. "!")
-- Prompt the user for their age
print("How old are you?")
local ageInput = io.read() -- Reads input as a string
-- Convert the string input to a number
local age = tonumber(ageInput)
if age then
print("You will be " .. (age + 1) .. " years old next year.")
else
print("That doesn't look like a valid number.")
end
Key Points
- Use
--to start a single-line comment in Lua. - Wrap multi-line comments with
--[[and]]to ignore multiple lines. - In Neovim with Comment.nvim, toggle comments on a line with
gccand on a visual block withV + gc. io.read()pauses program execution and reads a line of user input as a string.tonumber()converts a string input to a numeric value, returning nil if conversion fails.