Here’s a practice exercise to test your understanding of Lua basics:
Write a Lua program that does the following:
- Prints the message “Hello, world!” to the console.
- Assigns the value 10 to a variable called ‘num’.
- Checks whether the value of ‘num’ is greater than 5. If it is, print the message “num is greater than 5” to the console. If it isn’t, print the message “num is less than or equal to 5”.
- Use a ‘for’ loop to print the values of the numbers from 1 to 5 to the console.
- Define a function that takes two parameters and returns their sum. Call the function with the values 5 and 7 and print the result to the console.
Here’s a possible solution:
luaCopy code-- 1. Print "Hello, world!" to the console.
print("Hello, world!")
-- 2. Assign the value 10 to a variable called 'num'.
num = 10
-- 3. Check whether 'num' is greater than 5 and print the result.
if num > 5 then
print("num is greater than 5")
else
print("num is less than or equal to 5")
end
-- 4. Use a 'for' loop to print the values of the numbers from 1 to 5 to the console.
for i=1,5 do
print(i)
end
-- 5. Define a function that takes two parameters and returns their sum. Call the function with the values 5 and 7 and print the result to the console.
function add(x, y)
return x + y
end
result = add(5, 7)
print(result)
This program should print the following output:
pythonCopy codeHello, world!
num is greater than 5
1
2
3
4
5
12