simionx.Type - A type system¶
simionx.Type - A type system (provides type checking).
SYNOPSIS¶
local Type = require "simionx.Type"
-- A function with parameter checked against a built-in type.
function sqrt(x)
Type.nonnegative_integer:check(x)
return math.sqrt(x)
end
assert(sqrt(0) == 0)
-- A custom type.
local T_color = Type(
function(o) return o == "red" or o == "blue" end, "color")
-- A function with named parameter validation.
local argt
function format_thing(t)
argt = argt or Type {
mass = Type.number,
color = T_color + Type['nil']
}; argt:check(t)
return t.mass .. " " .. (t.color == nil and "unknown" or t.color)
end
assert(format_thing {mass = 10, color="blue"} == "10 blue")
DESCRIPTION¶
This module provides a Type class that represents variable types for type checking values. It is particularly useful for checking named arguments to functions.
A type object can be created as follows:
local T_positive_number = Type (
function (o) return type(o) == "number" and o > 0 end,
"positive number"
)
The first argument is a predicate function that returns whether the object o provided to it is of the given type. The second argument is a descriptive name of the type (used only for error reporting).
This module provides many common built-in types too. For example, positive_integer already implements the type described above.
Once you have a type, you can validate values against it. For example, the T:is() method returns a boolean value indicating whether the given value has the given type:
assert(Type.positive_number:is(2))
assert(not Type.positive_number:is(0))
The T:check() method is similar but raises an error, instead of retuning a value, if the type doesn’t match:
Type.positive_number:check(2) -- passes
Type.positive_number:check(0) -- raises error
Types can be composed with the + operator, which is a logical “OR”. The composed type will match values of either component type:
local T2 = Type.number + Type.string
assert(T2:is(3) and T2:is("a"))
assert(not T2:is({x=2}))
Types can also be composed by passing a table of key-value pairs to the Type function.:
local T3 = Type {
mass = Type.positive_number,
color = Type.string + Type['nil']
}
assert(T3:is {mass = 2, color = "blue"})
assert(T3:is {mass = 2})
For a table t to match the type, it must have the same keys as the type table, and the values of t must match the corresponding types in the type table.
Note that in the above we write Type['nil'] rather than Type.nil. The latter is syntactially invalid in Lua since nil is a reserved word in Lua.
Note
See these additional sections in this topic in the offline SIMION 8.1.0 help file:- Interface
SOURCE¶
(c) 2007 Scientific Instrument Services, Inc. Licensed under the terms of SIMION 8. www.simion.com. D.Manura-2007.
version: 20080821
