From a030a20985ff679b2ddc4f3bb615d7976c9ed915 Mon Sep 17 00:00:00 2001 From: David Briscoe Date: Sat, 5 Mar 2022 20:19:07 -0800 Subject: [PATCH] async: Assert that args is a table; add type_or_nil If args is valid, assert it's a table. Provides a clear and immediate error message when you convert add_timeout() to call(). Also add type_or_nil. Very useful for optional parameters like this one. Seems clearer than checking the arg first: if args then assert:type() end --- assert.lua | 9 +++++++++ async.lua | 2 ++ 2 files changed, 11 insertions(+) diff --git a/assert.lua b/assert.lua index 978ce10..93f1df9 100644 --- a/assert.lua +++ b/assert.lua @@ -73,6 +73,15 @@ function assert:type(a, t, msg, stack_level) return a end +--assert a value is nil or a certain type. +-- useful for optional parameters. +function assert:type_or_nil(a, t, msg, stack_level) + if a ~= nil then + assert:type(a, t, msg, stack_level + 1) + end + return a +end + --replace everything in assert with nop functions that just return their second argument, for near-zero overhead on release function assert:nop() local nop = function(self, a) diff --git a/async.lua b/async.lua index cfdc68c..b309c1c 100644 --- a/async.lua +++ b/async.lua @@ -16,6 +16,7 @@ ]] local path = (...):gsub("async", "") +local assert = require(path .. "assert") local class = require(path .. "class") local async = class({ @@ -51,6 +52,7 @@ end --add a task to the kernel function async:call(f, args, callback, error_callback) + assert:type_or_nil(args, "table", "async:call - args", 1) f = capture_callstacks(f) self:add(coroutine.create(f), args, callback, error_callback) end