lua calculate average number

To calculate the average number in Lua, you can follow these steps:

  1. Initialize the sum variable to 0 and the count variable to 0. These variables will be used to keep track of the sum of the numbers and the number of values entered, respectively.

  2. Use a loop to prompt the user to enter numbers. You can use the function to read input from the user. Inside the loop, add the entered number to the sum variable and increment the count variable by 1.

  3. After the loop ends, calculate the average by dividing the sum by the count. Store the result in a variable called average.

  4. Finally, print the average to the console using the print() function.

Here's an example code snippet that demonstrates the calculation of the average number in Lua:

local sum = 0
local count = 0

while true do
    print("Enter a number (or 'q' to quit):")
    local input =

    if input == "q" then

    local number = tonumber(input)

    if number then
        sum = sum + number
        count = count + 1
        print("Invalid input. Please enter a number.")

if count > 0 then
    local average = sum / count
    print("The average is: " .. average)
    print("No numbers entered.")

I hope this explanation helps you understand how to calculate the average number in Lua.