Functions in Lua

Functions are central in Lua. We’ll learn about functions with a few different examples.

-- Here's a function that takes two numbers and returns their sum
function plus(a, b)
    return a + b
end

-- In Lua, you don't need to specify parameter types or return types
function plusPlus(a, b, c)
    return a + b + c
end

-- The main function in Lua is typically just the script itself,
-- but we'll wrap it in a function for consistency
function main()
    -- Call a function just as you'd expect, with name(args)
    local res = plus(1, 2)
    print("1+2 =", res)

    res = plusPlus(1, 2, 3)
    print("1+2+3 =", res)
end

-- Call the main function
main()

To run the program, save it as functions.lua and use the lua command:

$ lua functions.lua
1+2 = 3
1+2+3 = 6

There are several other features to Lua functions. One is multiple return values, which we’ll look at next.

Key differences from the original example:

  1. Lua uses function keyword to declare functions instead of func.
  2. Lua doesn’t require explicit type declarations for parameters or return values.
  3. The local keyword is used for variable declarations within functions.
  4. Lua uses -- for comments instead of //.
  5. In Lua, there’s no built-in main function. Scripts are executed from top to bottom, but we’ve wrapped the main code in a function for similarity.
  6. Lua uses print function for output instead of fmt.Println.
  7. String concatenation in Lua print statements is done with commas, not the + operator.

These changes reflect the idiomatic way of writing Lua code while maintaining the structure and purpose of the original example.