Angel \”Java\” Lopez on Blog

February 20, 2010

Variable-Length arguments in AjSharp

Filed under: AjSharp, Open Source Projects, Programming Languages — ajlopez @ 3:04 pm

In my experiments with agents, using AjSharp interpreter, I found that I missed one feature: variable number of arguments. So, back to quick coding, test-driven-dev hat on, and today, during a light breakfast, I wrote the code to support such feature.

I had to implement two facets of the feature. First, the declaration of the variable length argument:

function FirstParameter(pars...)
{
	if (pars.Length>0)
		return pars[0];
		
	return null;
}
function SecondParameter(pars...)
{
	if (pars.Length>1)
		return pars[1];
		
	return null;
}
result = FirstParameter(1,2,3);		// 1
result2 = SecondParameter(1,2,3);	// 2
result3 = SecondParameter();		// null

The other side, what if I want to use the received pars… as the parameters to give to another functions? The received pars… is an array of objects. I use the same … (three points) operator, but now, in the invocation side:

function FirstParameter(pars...)
{
	if (pars.Length>0)
		return pars[0];
		
	return null;
}
function SecondParameter(pars...)
{
	if (pars.Length>1)
		return pars[1];
		
	return null;
}
function JustDoIt(fn,pars...)
{
	return fn(pars...);
}
result = JustDoIt(FirstParameter,1,2,3);		// 1
result2 = JustDoIt(SecondParameter,1,2,3);	// 2
result3 = JustDoIt(SecondParameter);		// null

Curiously, two days ago, I found the language

CoffeeScript

that compiles to normal JavaScript. In that page, I found a term new for me: Splats for the operator … (three points). I decided to use that operator some weeks ago, I can’t remember what was the source of such idea.

I should employ this feature in some agent example.

Keep tuned!

Angel "Java" Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: