Quick actions

cmd+k|ctrl+k

Navigation

Languages

TypeCheck love2d 0.10.1

Snippet info

Language

Lua

Visibility

public

Author

evine

Created

2016-03-24T14:47:26Z

Updated

2016-03-31T02:50:59Z

local heart = {}

heart.validType =
{
    ["number"] = true,
    ["string"] = true,
    ["nil"] = true,
    ["userdata"] = true,
    ["function"] = true,
    ["table"] = true,
    ["single"] = function(singleCharString)
        if heart.typeCheck(singleCharString, "string") and
            utf8.len(singleCharString) == 1 then
            return true
        end
        return false
    end,

	--Audio
	Source = true,
	--Filesystem
	File = true,
	FileData = true,
	--Font
	GlyphData = true,
	Rasterizer = true,
	--Graphics
	Drawable = function(isDrawable) -- superclass
		return heart.typeCheck(
			isDrawable,
			"Canvas",
			"Image",
			"Mesh",
			"ParticleSystem",
			"SpriteBatch",
			"Text",
			"Texture",
			"Video")
	end,
	Canvas = true,
	Font = true,
	Image = true,
	Mesh = true,
	ParticleSystem = true,
	Quad = true,
	Shader = true,
	SpriteBatch = true,
	Text = true,
	Texture = true,
	Video = true,
	--Image
	CompressedImageData = true,
	ImageData = true,
	--Joystick
	Joystick = true,
	--Math
	BezierCurve = true,
	CompressedData = true,
	RandomGenerator = true,
	--Mouse
	Cursor = true,
	--Sound
	Decoder = true,
	SoundData = true,
	--Thread
	Channel = true,
	Thread = true,
	--Video
	VideoStream = true,
}

function heart.type(variable)
    return (
        type(variable) == "userdata" and
        variable.__index and
        variable.__index.type and
        variable:type()
        ) or
        type(variable)
end

function heart.typeCheck(variable, ...)
    local isType = false
    for i = 1, select("#", ...) do
        local check = select(i, ...)
        
        assert(heart.validType[check], "Invalid type passed to heart.typeCheck.")
        if heart.validType[check] == true then
            if check == heart.type(variable) then
                isType = true
                break
            end
        else
            if heart.validType[check](variable) then
                isType = true
                break
            end
        end
    end
    return isType
end

function heart.typeAssert(variable, ...)
    if not heart.typeCheck(variable, ...) then
        assert(false, "Variable is not of type: "..table.concat({...}, ", "))    
    end
end

print(heart.typeCheck("SomeString", "string", "number"))

heart.typeAssert({}, "table")

heart.typeAssert(3, "string", "function")
INFO