PDA

View Full Version : are there such things as package functions?


petruza
06-02-2008, 11:47 PM
Hi! I've been reading some mentions to package functions and package variables in AS.
Do they exist in AS 3 ?
if I try to define a function directly inside a package and not in a class, I get this error:

A file found in a source-path can't have more than one externally visible definition. [function name];[filename]

I'm trying to define this function to count the elements of an associative array implemented as an Object:
function length( object :Object ) :uint
{
var length :uint = 0;
for( var i :uint in object )
++length;
return length;
}
I use the unnamed package, and want this function to be accesible from within that package.

One solution would be to make it a static member of any class of the package and access it that way, but the function would be totally unrelated to the class, insulting the whole OOP idea.

While I write this, I figure out that 'the whole OOP idea' would rule out the use of standalone functions in favor of class methods :o

Anyway, are there such things? thanks!

wvxvw
06-03-2008, 12:13 AM
Yes, they do exist, hovewer, anything that doesn't use "public" namespace is considered "internal" i.e. inaccessable for other classes. Also, mind that only 1 top-level public definition is alowed per file. I.e. in your example you had to put your function into public namespace and call the file length.as (I would advise to pick a different name cuz there're lots of other classes that allready have the same method/property). Then, whenever you'd like to use your function, put the import length; statement in that class.

petruza
06-03-2008, 01:03 PM
Thanks for the answer!
Although, it didn't work for me, look:

// File: length.as
package
{
public function length( object :Object ) :uint
{
var length :uint = 0;
for( var i :* in object )
++length;
return length;
}
}

// File: SomeClass.as
package
{
import length;
public class SomeClass
{
public function SomeClass()
{
trace( length( new Object() ) );
}
}
}

// Error: 1180: Call to a possibly undefined method length.


:confused:

wvxvw
06-03-2008, 06:34 PM
Just change the name length to something else.

petruza
06-03-2008, 07:42 PM
:o oops sorry... and I can't say you didn't warn me...

my C++ mind is still trying to adapt... but the error was because there is another thing called 'length' defined somewhere and the names are clashing?
because if try to call length() without defining it myself, it still doesn't exist.

senocular
06-03-2008, 07:59 PM
I'm not sure about this one. It actually surprised me that defining length isn't allowed, but I guess it's a legacy function thats causing the block. You *might* be ok if you put it in a package