Examples¶
Some quick examples to get you started on enforcing types.
Simple example¶
local typed = require 'typed'
local function hi(msg)
typed.func(_, 'string')(msg)
print(msg)
end
hi('hello') -- No errors
hi(1) -- bad argument #1 to 'hi' (string expected, got number)
Or statements example¶
local typed = require 'typed'
local function hi(msg)
-- We see the use of `|` to allow strings **or** numbers
typed.func(_, 'string | number')(msg)
print(msg)
end
hi('hello') -- No errors
hi(1) -- No errors
Whatis example¶
assert.are.equal(typed.whatIs(1), 'number')
assert.are.equal(typed.whatIs(''), 'string')
assert.are.equal(typed.whatIs(true), 'boolean')
assert.are.equal(typed.whatIs(print), 'function')
assert.are.equal(typed.whatIs(coroutine.create(function() end)), 'thread')
assert.are.equal(typed.whatIs(io.stdout), 'userdata')
Function example¶
local function hi()
typed.func(_, 'string')()
end
assert.has.error(function()
hi()
end, 'bad argument #1 to \'hi\' (string expected, got nil)')
Typed dictionaries¶
assert.has.error(function()
typed.typedDict('string', 'number')[3] = 2
end)
Typed arrays¶
assert.has_error(function()
local arr = typed.TypedArray('number')
arr:push()
end, 'bad argument #1 to \'push\' (number expected, got nil)')
Schemas¶
local typed = require 'typed'
local schema = typed.Schema('test')
:field('name', 'string')
:field('id', 'number')
print(schema:validate {
name = '3',
id = '2'
}) --> false Expected number, got string on field id
local newSchema = typed.Schema('nested')
:field('sub', schema)
:field('id', 'number')
print(newSchema:validate {
sub = {
name = '3',
id = '2'
},
id = 2
}) --> false Expected test, got Malformed test on field sub; Expected number, got string on field id
Schemas continued¶
--[[
A schema can be very useful when working with config files.
Here we see a use by using a toml parser with schemas to fill in defaults and enforce types.
]]
local typed = require 'typed'
local toml = require 'toml'
local configSchema = typed.Schema('config')
:field('saveLocation', 'string')
:field('playerName', 'string', 'joe')
local data, err = configSchema:validate(toml.parse([[
saveLocation = "hi"
]]))
if err then
error 'Invalid config!'
end
for i, v in pairs(data) do
print(i, v)
--> playerName joe
--> saveLocation hi
end
--- The data would either be the filled in data or nil and an error