From 434f9c1b3102ef1bbce5f73f17babdbf7b55d974 Mon Sep 17 00:00:00 2001 From: Case Duckworth Date: Tue, 2 Apr 2024 12:46:16 -0500 Subject: Implement arity checks --- util.lua | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) (limited to 'util.lua') diff --git a/util.lua b/util.lua index b5a57b1..d151858 100644 --- a/util.lua +++ b/util.lua @@ -7,10 +7,30 @@ function m.pop (tbl) return table.remove(tbl, 1) end -function m.arity (r, min, max) - --[[ Return whether R is within MIN and MAX (inclusive). ]] - local len = #r - return len >= min and len <= max +function m.proc (arity, fn) + --[[ Wrap RN in a check that for its ARITY. + ARITY can be a number, the minimum number of arguments, + or a table {MIN, MAX}. If MIN is nil or absent, it's 0; + if MAX is nil or absent, it's infinity. MIN and MAX are + both inclusive. + ]] + local rmin, rmax, rstr + if type(arity) ~= "table" then + rmin, rmax = arity, arity + rstr = rmin + else + rmin, rmax = arity[1] or 0, arity[2] or 1/0 -- infinity + rstr = rmin .. ".." .. rmax + end + return function (r) + local rlen = r and #r or 0 + if rlen < rmin or rlen > rmax then + error(string.format("Wrong arity: %s, need %s", + rlen, + rstr)) + end + return fn(r) + end end --- -- cgit 1.4.1-21-gabe81