Menu
CoddyTech

Functions and Arguments

Lesson 17 of 48 in Coddy's Lua for Go Developers course.

Go functions have static parameter and result types and can be passed as values. Lua functions are values too, but missing arguments become nil and extra arguments can be ignored. Define the contract with function/end and validate input before operations that require a number or table. Go compile-time arity checks are not supplied by Lua.

Go

package main
import ("fmt")
func twice(n int) int {return n*2}
func main(){
fmt.Println(twice(4))
}

Lua

local function twice(x)
  return x * 2
end
print(twice(4))

Porting trap

Document and validate the Lua function boundary rather than expecting a Go signature check.

challenge icon

Challenge

Easy

Input is integer unit price and nonnegative integer quantity on two lines. Define a local function subtotal(price, quantity) and return its result.

Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.

Try it yourself

local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for Go Developers

Practice on your own: Online Lua compiler