Skip to main content

Overview

@generic adds type parameters to a function. GLuaLS uses them to carry types through helpers such as filter, map, and wrapper functions.

Syntax


Basic generic function


Multiple type parameters


Generic with constraint

Use : ConstraintType to restrict the types that T accepts:

Generic arrays


When to use generics

Generics work best for:
  • Functions that transform a value but keep its type
  • Functions that filter or map over a typed list
  • Functions that take a callback and return its result type
For simple cases, a union type or any can be easier to read.

String-template capture (GLuaLS)

Use backticks when a string argument names a class or type. Use this when a function takes a class name as text and returns that class type:
For collection-returning functions:
Rule:
  • T uses the normal Lua value type ("x" becomes string)
  • `T` uses the string text as a class or type name ("sent_npc" becomes sent_npc)
Common string-template forms:

Naming the parent class with base_class

A factory can create a class from one string and take its parent in another argument. Put base_class on the parameter that holds the parent:
The argument can name the parent in two ways:
  • A string. It gets the same prefix and suffix as the class parameter, so you write "Mech", not "battlemechs.Mech". Type the parameter as a plain string, not a string template, or a typo would create a new class.
  • A class value, such as the table an earlier call returned. Its class becomes the parent.
GLuaLS adds the parent only when the argument names an existing class. Otherwise the class keeps the root_class from constructor, if there is one. root_class is the parent every class from the factory gets; base_class adds the one this call names. A class never inherits from itself or from one of its own subclasses.

Explicit generic call arguments

When inference is unclear, pass generics at the call site: