Wizards of Lua

The Art of Spell Crafting


Types - Managing Types

The Types module can be used to check objects for their type and to create new types.

Here is an overview of the Types functions:

Function Parameters Results
 declare  className, metatable nil
 instanceOf  classTable, object boolean
 type  LuaObject string

Functions

Below you find short descriptions about each of the functions and some examples about how to use them in your spells.


declare (className, metatable) -> nil

The ‘declare’ function creates a new class with the given name and the optionally given superclass.

Example

Declaring a “Book” class with some functions.

Types.declare("Book")

function Book.new(title)
  local o = {title=title, pages={}}
  setmetatable(o,Book)
  return o
end

function Book:addPage(text)
  table.insert(self.pages, text)
end

Please note that there is also a shortcut for “Types.declare”:

declare("Book")

Example

Declaring the “Newspaper” class as a subclass of “Book”.

declare("Newspaper", Book)

function Newspaper.new(title)
  local o = {title=title, pages={}}
  setmetatable(o,Newspaper)
  return o
end

instanceOf (classTable, object) -> boolean

The ‘instanceOf’ function returns true if the given object is an instance of the given class.

Example

Checking if the current spell’s owner is a player.

if Types.instanceOf(Player, spell.owner) then
  print("Owner is a player")
end

type (LuaObject) -> string

The ‘type’ function returns the name of the given object’s type.

Example

Printing the type of the spell’s owner.

print( Types.type(spell.owner))

Since “Types.type” is widely used there exists also a shortcut: “type”.

print( type(spell.owner))