Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

1 Answers

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.

like image 96
Evan Schwartzentruber Avatar answered May 11 '26 13:05

Evan Schwartzentruber