[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Argument checking in Lua?
- From: Chris Marrin <chris@...>
- Date: Thu, 02 Feb 2006 07:23:23 -0800
Rici Lake wrote:
On 1-Feb-06, at 6:46 PM, Chris Marrin wrote:
Ok, thanks. Here is what I am thinking about adding:
local _check_foo = checkArgs("int, string='hello', number=3.14")
function foo(a,b,c)
_check_foo(arg)
...
end
Where checkArgs() returns a function which does all the checking. This
way, I can "compile" the argument checking function for efficiency.
That sounds like a good idea, although it would be a fair amount of
work. However, there is no arg table in 5.1, and ... is not a table, or
indeed any other first-class object. So, for example,
...[2]
does not mean what you think it does. (It would apply the index 2 to the
first argument of the function.)
All is not lost, however, since you can compile a check function with
named arguments; after all, the prototype tells you how many arguments
there will be. And instead of explicitly calling _check_foo, you could
pass foo itself to checkArgs and have it return a wrapped function for you.
Interesting approach. That would change the syntax of the function from:
_foo_check = checkArgs("int, string='hello', number=3.14")
function foo(a,b,c)
a,b,c = _foo_check(a,b,c)
...
end
to:
foo = checkArgs("int, string='hello', number=3.14",
function(a,b,c)
...
end)
which looks pretty good.
Personally, rather than trying to parse a prototype string, I'd go with
a table of individual prototypes, something like this:
function foo(a, b, c) ... end
checked_foo = checkArgs{"int", "string:hello", "number:3.14"}(foo)
I was both trying to avoid so many quotes, which are error prone, and to
match the way I will be generating these strings. Emma is a
declarative system and an author will be able to do something like:
<function name="foo" params="int, string='hello', number=3.14">
function(a,b,c) ... end
</function>
and from this, I can generate the above form. The generated function
would look something like:
function(a,b,c)
...
if b == nil then
b = "hello"
else
assert(type(b) == "string")
end
...
return f(a,b,c)
end
Let me know if that wasn't enough of a hint :)
thanks for the help!
--
chris marrin ,""$, "As a general rule,don't solve puzzles
chris@marrin.com b` $ that open portals to Hell" ,,.
,.` ,b` ,` , 1$'
,|` mP ,` :$$' ,mm
,b" b" ,` ,mm m$$ ,m ,`P$$
m$` ,b` .` ,mm ,'|$P ,|"1$` ,b$P ,` :$1
b$` ,$: :,`` |$$ ,` $$` ,|` ,$$,,`"$$ .` :$|
b$| _m$`,:` :$1 ,` ,$Pm|` ` :$$,..;"' |$:
P$b, _;b$$b$1" |$$ ,` ,$$" ``' $$
```"```'" `"` `""` ""` ,P`