Skip to content

Vararg check? #92

@freddylist

Description

@freddylist

t doesn't have a way to check varargs (if there is, then it's not documented and should be documented / I couldn't find it). You could, of course, t.array(check)({...}) inside the function to check, but you can't do that with t.wrap.

I suggest passing the last remaining arguments in a t.tuple check to the last check:

function t.tuple(...)
	local checks = { ... }
	local checkCount = #checks -- or `select('#', ...)`, whichever is fastest ig idk

	return function(...)
		local args = { ... }

		for i, check in ipairs(checks) do
			-- Pass any remaining arguments to the last check:
			local success, errMsg
			
			if i == checkCount then
				success, errMsg = check(select(i, ...))
			else
				success, errMsg = check(args[i])
			end

			if success == false then
				return false, string.format("Bad tuple index #%s:\n\t%s", i, errMsg or "")
			end
		end

		return true
	end
end

And adding a vararg check:

function t.vararg(check)
	assert(t.callback(check))

	return function(...)
		for i, v in ipairs({...}) do
			local success, errMsg = check(v)

			if success == false then
				return false, string.format("Bad vararg index #%s:\n\t%s", i, errMsg or "")
			end
		end
		
		return true
	end
end

This way, I can check varargs in wrapped functions! :D

local add = t.wrap(function(a, b, ...)
	local total = a + b
	
	for _, v in pairs({...}) do
		total += v
	end
	
	return total
end, t.tuple(t.number, t.number, t.vararg(t.number)))

print(add(1, 2, 3, 4, 5)) -- 15
print(add(1, 2, 3, 4, "a") -- error: bad tuple index 3, bad vararg index 3

I didn't open a pull request because I don't want to mess up those typescript thingies. The code here could probably be improved as well, but if you want, I can open a pull request with tests and I will do my best to do the typescript stuff correctly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions