diff options
author | Case Duckworth | 2024-04-02 12:46:16 -0500 |
---|---|---|
committer | Case Duckworth | 2024-04-02 12:46:16 -0500 |
commit | 434f9c1b3102ef1bbce5f73f17babdbf7b55d974 (patch) | |
tree | 29645b4ce2f334927090397920e6610f0264934f /util.lua | |
parent | Implement list length (diff) | |
download | lam-434f9c1b3102ef1bbce5f73f17babdbf7b55d974.tar.gz lam-434f9c1b3102ef1bbce5f73f17babdbf7b55d974.zip |
Implement arity checks
Diffstat (limited to 'util.lua')
-rw-r--r-- | util.lua | 28 |
1 files changed, 24 insertions, 4 deletions
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) | |||
7 | return table.remove(tbl, 1) | 7 | return table.remove(tbl, 1) |
8 | end | 8 | end |
9 | 9 | ||
10 | function m.arity (r, min, max) | 10 | function m.proc (arity, fn) |
11 | --[[ Return whether R is within MIN and MAX (inclusive). ]] | 11 | --[[ Wrap RN in a check that for its ARITY. |
12 | local len = #r | 12 | ARITY can be a number, the minimum number of arguments, |
13 | return len >= min and len <= max | 13 | or a table {MIN, MAX}. If MIN is nil or absent, it's 0; |
14 | if MAX is nil or absent, it's infinity. MIN and MAX are | ||
15 | both inclusive. | ||
16 | ]] | ||
17 | local rmin, rmax, rstr | ||
18 | if type(arity) ~= "table" then | ||
19 | rmin, rmax = arity, arity | ||
20 | rstr = rmin | ||
21 | else | ||
22 | rmin, rmax = arity[1] or 0, arity[2] or 1/0 -- infinity | ||
23 | rstr = rmin .. ".." .. rmax | ||
24 | end | ||
25 | return function (r) | ||
26 | local rlen = r and #r or 0 | ||
27 | if rlen < rmin or rlen > rmax then | ||
28 | error(string.format("Wrong arity: %s, need %s", | ||
29 | rlen, | ||
30 | rstr)) | ||
31 | end | ||
32 | return fn(r) | ||
33 | end | ||
14 | end | 34 | end |
15 | 35 | ||
16 | --- | 36 | --- |