function

Contents

function#

Functions are first-class values, the same kind of value as a number or a string. The operator stores them in variables, in table fields (which is how methods work), passes them as arguments, and returns them from other functions.

Bind a function to a local name.

local greet = function(name) return "hello, " .. name end
print(greet("operator"))

Store functions as table values for dispatch.

local handlers = {
  get  = function(req) return "got "    .. req end,
  post = function(req) return "posted " .. req end,
}
print(handlers.get("/health"))

Full surface (multiple returns, varargs, closures, methods) lives in Functions.

References#

  • Functions for the full function surface.

  • table for tables-of-functions as method dispatch.

  • OOP for self and method-call sugar.