user17411100
user17411100

Reputation:

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")

Upvotes: 6

Views: 14830

Answers (2)

Evan Schwartzentruber
Evan Schwartzentruber

Reputation: 556

Lua handles variable types dynamically which is why there are no required annotations. You can, however, explicitly state the type of a variable with the following syntax:

---@type integer
local x = 3

This is entirely optional. Doing so could improve readability as this is built into the documentation and is also recognized by many IDE's with syntax highlighting.

Upvotes: 13

Luatic
Luatic

Reputation: 11201

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

Upvotes: 6

Related Questions