Skip to content
Jérôme Leclercq edited this page Dec 8, 2020 · 2 revisions

API: AssertMetatable

Description:

Retrieves the metatable of a table and compares its __name field with the one passed in argument.

This function is useful to check if an object is of the right type when getting it as a parameter.

Prototype:

AssertMetatable(t: table, name: string) -> t: table

Parameters:

  1. t: The table to check.
  2. name: The expected metatable identifier.

Returns:

  1. t: t parameter, this is for convenience (as assert does).

Example code

A function which computes a triangle area from three points.

function triangle_area(a, b, c)
	-- AssertMetatable triggers an error if a, b or c is not a vec2
	AssertMetatable(a, "vec2")
	AssertMetatable(b, "vec2")
	AssertMetatable(c, "vec2")

	local side1 = a:Distance(b)
	local side2 = b:Distance(c)
	local side3 = c:Distance(a)

	-- Sum of any two sides must be smaller than third side
	if (side1 + side2 <= side3 or
		side1 + side3 <= side2 or
		side2 + side3 <= side1) then
		error("not a valid triangle")
	end

	local s = (side1 + side2 + side3) / 2.0;
	return math.sqrt(s * (s - side1) * (s - side2) * (s - side3))
end

-- Prints 50.0
print(Vec2(0.0, 0.0), Vec2(5.0, 10.0), Vec2(10.0, 0.0))

Clone this wiki locally