typesluatype-hintingcode-hinting

Type hinting/specifying a type in lua


There's a feature in python where you can specify a type of a variable or a function argument or something, but I'm doing some lua right now I'd like to specify a type as my auto completion shows type any so I thought lua might also have that feature

Basically I have a function called log:

local function log(message)
    io.stderr:write(string.format(" :: %s\n", message))
end

Is there a way to specify the type of arg message and/'or at least' the return type? I want it to be a string :)

In python it'd be:

import sys

def log(message: str) -> None:
    sys.stderr.write(f" :: {message}\n")

Solution

  • Lua does not support type annotations. Your options are the following:

    1. Use a Lua preprocessor like TS2Lua or Teal which supports types
    2. Use asserts to check argument types, throwing a runtime error if they don't match: assert(type(message) == "string"); you can also use an assert(select("#", ...) == 0) to check the arity if you add an additional vararg param ... to the argument list
    3. Use comments to document types inline, possibly in combination with a documentation generator that support your annotations: local function log(message --[[string]]) --> nothing