Advertisement

Array support

Started by July 28, 2004 05:39 AM
6 comments, last by WitchLord 20 years, 3 months ago
Hi, just a small suggest would be array support in script syntax. For example, I have to get an item number then parse each item to process it. At this time, the only way I found to proceed is: STRING item0Name, item1Name, ... etc ...; ... void ProcessItem( int nNumItem, STRING& itemName ) { if( nNumItem < GetItemCount() ) { ... } } void main() { ProcessItem( 0, &item0Name ); ProcessItem( 1, &item1Name ); ... } it would be great to write script like : STRING itemNameArray[10]; void ProcessItem( STRING& itemName ) { ... } void main() { int n; for( n = 0; n < GetItemCount(); n++ ) { ProcessItem( &itemNameArray[n] ); } } By the way, the work you already made on AS is really great and useful ! Lbas
Lbas
I'm happy you like AS :)

Native arrays in the scripts are planned but are still quite far away. For now you can register an array object that would allow you to work with arrays of strings. Example:

class CStringArray{public:  // Some functions for initialization etc  // Our array indexing operator  STRING &GetString(int index);};// Register the string type and any methods you need// Register the overloaded indexing operatorengine->RegisterTypeBehaviour("CStringArray", asBEHAVE_INDEX, "STRING &f(int)", asMETHOD(CStringArray, GetString), asCALL_THISCALL);


This string array object could be used in the script as follows:

CStringArray itemNameArray;void main(){    // Initialize the array  int n;  for( n = 0; n < itemNameArray.GetLength(); n++ )  {    ProcessItem( itemNameArray[n] );  }    }void ProcessItem( STRING& itemName ){  ...}


This is just to give you an idea.

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

Advertisement
Excellent !
Thx a lot for the tip.

Maybe a "contrib" page on the site could allow to add some useful class developped by users (for example, if I developp array class for each base type, including int, uint, etc, it could be shared with other users). Another example is I'm using wxWidgets so I implemented a wxStringFactory so you can register any wxWidget method which uses wxString to AS without need to write wrapper functions from bstr to wxString.

Lbas
Lbas
I can host these files if you wish. Or put up links to them if you prefer that.

I'll probably add a page for contributions, add-ons, or something like that as I gather more of them. So far I haven't got too many so they are available under the "library & samples" page.

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

Some time ago I have written some template-code to register arrays for whatever type you want.

!!!! I haven't tested it since I wrote it though !!!!

This way I can just do
gRegisterArray<Vector2>(outEngine,		"Vector2");

to register a Vector2Array that supports stuff like SetLength(..), GetLength(), Add(..), Remove(..) etc.

Any fixes, improvements (does it work at all ? :) ), suggestions or "constructive" critiscism would be great ofcourse.

ASArray.h
#ifndef AS_SCRIPT_ARRAY_H#define AS_SCRIPT_ARRAY_H#include <string>#include <memory.h>#include <assert.h>#include "include/AngelScript.h"//---------------------------------------------------------------------------------------------------------------------//	//---------------------------------------------------------------------------------------------------------------------template <typename T> bool gRegisterArray(asIScriptEngine * outEngine, const char * inTypeName){	int result;	std::string type_name(inTypeName);	std::string array_name(inTypeName); array_name+="Array";	// register array-type	result = outEngine->RegisterObjectType(array_name.c_str(), sizeof(ASArray<T>()), asOBJ_GUESS); assert(result>=0);	// Behaviours	result = outEngine->RegisterTypeBehaviour(array_name.c_str(),	asBEHAVE_CONSTRUCT,		"void Construct()", asFUNCTION(ASArray<T>::ASConstruct), asCALL_CDECL_OBJLAST); assert(result>=0);	result = outEngine->RegisterTypeBehaviour(array_name.c_str(),	asBEHAVE_ASSIGNMENT,	(array_name + " &Assign(" + array_name + "&)").c_str(), asFUNCTION(ASArray<T>::ASAssign), asCALL_CDECL_OBJLAST); assert(result>=0);		result = outEngine->RegisterTypeBehaviour(0,					asBEHAVE_ADD,			(array_name + " f(const " + array_name + "&, const " + array_name + "&)").c_str(), asFUNCTION(ASArray<T>::ASOperatorAddArray), asCALL_CDECL); assert(result>=0);	result = outEngine->RegisterTypeBehaviour(0,					asBEHAVE_ADD,			(array_name + " f(const " + array_name + "&, const " + type_name + "&)").c_str(), asFUNCTION(ASArray<T>::ASOperatorAddElement), asCALL_CDECL); assert(result>=0);	result = outEngine->RegisterTypeBehaviour(0,					asBEHAVE_EQUAL,			(std::string("bool f(const ") + array_name + "&, const " + array_name + "&)").c_str(), asFUNCTION(ASArray<T>::ASOperatorEqual), asCALL_CDECL); assert(result>=0);	result = outEngine->RegisterTypeBehaviour(0,					asBEHAVE_NOTEQUAL,		(std::string("bool f(const ") + array_name + "&, const " + array_name + "&)").c_str(), asFUNCTION(ASArray<T>::ASOperatorNotEqual), asCALL_CDECL); assert(result>=0);	result = outEngine->RegisterTypeBehaviour(array_name.c_str(),	asBEHAVE_INDEX,			(type_name + std::string("& f(int)")).c_str(), asMETHOD(ASArray<T>, ASIndex), asCALL_THISCALL); assert(result>=0);	// methods	result = outEngine->RegisterObjectMethod(array_name.c_str(), "void SetLength(int)",											asMETHOD(ASArray<T>, SetLength), asCALL_THISCALL); assert(result>=0);	result = outEngine->RegisterObjectMethod(array_name.c_str(), "int GetLength()",												asMETHOD(ASArray<T>, GetLength), asCALL_THISCALL); assert(result>=0);		result = outEngine->RegisterObjectMethod(array_name.c_str(), (std::string("void Add(") + type_name + " &)").c_str(),		asMETHOD(ASArray<T>, ASAddElement), asCALL_THISCALL); assert(result>=0);	result = outEngine->RegisterObjectMethod(array_name.c_str(), (std::string("void Add(") + array_name + " &)").c_str(),		asMETHOD(ASArray<T>, ASAddArray), asCALL_THISCALL); assert(result>=0);	result = outEngine->RegisterObjectMethod(array_name.c_str(), "void Remove(int)",											asMETHOD(ASArray<T>, ASRemove), asCALL_THISCALL); assert(result>=0);	return (result >= 0);}template <class T> class ASArray{public:	ASArray();	ASArray(const ASArray<T> &);	~ASArray();	void Allocate(int numElements, bool keepData);	int  GetCapacity() const;	void PushLast(const T & element);	T    PopLast();	void Remove(int inIndex);	void SetLength(int numElements);	int  GetLength() const;	void Copy(const T*, int count);	ASArray<T> &operator =(const ASArray<T> &);	T &operator [](int index) const;	T *AddressOf();	inline bool				operator == (const ASArray<T> & inRHS) const	{ return (length == inRHS.length) && (memcmp((void*)array, (void*)inRHS.array, length) == 0); }	inline bool				operator != (const ASArray<T> & inRHS) const	{ return (length != inRHS.length) || (memcmp((void*)array, (void*)inRHS.array, length) != 0); }		inline const ASArray<T>	operator + (const ASArray<T> & inRHS) const;	inline const ASArray<T>	operator + (const T & inRHS) const;	inline ASArray<T>&		operator += (const ASArray<T> & inRHS);	static void	_cdecl		ASConstruct(ASArray<T> & inThis);	static ASArray<T> & _cdecl	ASAssign(const ASArray<T> & inSource, ASArray<T> & inDest);		static ASArray<T> _cdecl	ASOperatorAddArray(const ASArray<T> & inLHS, const ASArray<T> & inRHS);	static ASArray<T> _cdecl	ASOperatorAddElement(const ASArray<T> & inLHS, const T & inRHS);	static bool _cdecl		ASOperatorEqual(const ASArray<T> & inLHS, const ASArray<T> &inRHS);	static bool	_cdecl		ASOperatorNotEqual(const ASArray<T> & inLHS, const ASArray<T> &inRHS);	T*						ASIndex(int inIndex);	void					ASAddElement(const T & inElement)		{ PushLast(inElement); }	void					ASAddArray(const ASArray<T> & inArray);	void					ASRemove(int inIndex);protected:	T   *array;	int  length;	int  maxLength;};// Implementationtemplate <class T>T *ASArray<T>::AddressOf(){	return array;}template <class T>ASArray<T>::ASArray(void){	array     = 0;	length    = 0;	maxLength = 0;}template <class T>ASArray<T>::ASArray(const ASArray<T> ©){	array     = 0;	length    = 0;	maxLength = 0;	*this = copy;}template <class T>ASArray<T>::~ASArray(void){	if( array )	{		delete[] array;		array = 0;	}}template <class T>int ASArray<T>::GetLength() const{	return length;}template <class T>T &ASArray<T>::operator [](int index) const{	assert(index >= 0);	assert(index < maxLength);	return array[index];}template <class T>void ASArray<T>::PushLast(const T & element){	if( length == maxLength )		Allocate(int(maxLength*1.5f) + 1, true);	array[length++] = element;}template <class T>T ASArray<T>::PopLast(){	assert(length > 0);	return array[--length];}template <class T>void ASArray<T>::Remove(int inIndex){	assert(inIndex >= 0);	assert(inIndex < maxLength);	int num = (length - inIndex) - 1;	if (num > 0)		memmove((void*) &array[inIndex], (void*) &array[inIndex+1], num);	length--;}template <class T>void ASArray<T>::Allocate(int numElements, bool keepData){	assert(numElements >= 0);	T *tmp = new T[numElements];	for (int i=0; i<numElements; i++)		T::ASConstruct(tmp);	if( array )	{		if( keepData )		{			if( length > numElements )				length = numElements;			memcpy(tmp, array, length*sizeof(T));		}		else			length = 0;		delete[] array;	}	array = tmp;	maxLength = numElements;}template <class T>int ASArray<T>::GetCapacity() const{	return maxLength;}template <class T>void ASArray<T>::SetLength(int numElements){	assert(numElements >= 0);	if( numElements > maxLength )		Allocate(numElements, true);	length = numElements;}template <class T>void ASArray<T>::Copy(const T *data, int count){	if( maxLength < count )		Allocate(count, false);	memcpy(array, data, count*sizeof(T));}template <class T>ASArray<T> &ASArray<T>::operator =(const ASArray<T> ©){	Copy(copy.array, copy.length);	return *this;}template <class T>const ASArray<T> ASArray<T>::operator +(const ASArray<T> & inRHS) const{	ASArray<T> result;	result.Allocate(length + inRHS.length, false);	memcpy((void *)result.array, (void *)array, length * sizeof(T));	memcpy((void *)(result.array+length), (void*)inRHS.array, inRHS.length * sizeof(T));	return result;}template <class T>const ASArray<T> ASArray<T>::operator +(const T & inRHS) const{	ASArray<T> result;	result.Allocate(length + 1, false);	memcpy((void *)result.array, (void *)array, length * sizeof(T));	result[length] = inRHS;	return result;}template <class T>ASArray<T> &ASArray<T>::operator +=(const ASArray<T> & inRHS){	int old_len = length;	Allocate(old_len + inRHS.length, true);	memcpy((void *)(array+old_len), (void*)inRHS.array, inRHS.length * sizeof(T));	return *this;}template <class T>void ASArray<T>::ASConstruct(ASArray<T> & inThis){	inThis.array     = 0;	inThis.length    = 0;	inThis.maxLength = 0;}template <class T>ASArray<T> & ASArray<T>::ASAssign(const ASArray<T> & inSource, ASArray<T> & inDest){	inDest = inSource;	return inDest;}	template <class T>ASArray<T>	ASArray<T>::ASOperatorAddArray(const ASArray<T> & inLHS, const ASArray<T> & inRHS){	return inLHS + inRHS;}template <class T>ASArray<T>	ASArray<T>::ASOperatorAddElement(const ASArray<T> & inLHS, const T & inRHS){	return inLHS + inRHS;}template <class T>bool ASArray<T>::ASOperatorEqual(const ASArray<T> & inLHS, const ASArray<T> &inRHS){	return inLHS == inRHS;}template <class T>bool ASArray<T>::ASOperatorNotEqual(const ASArray<T> & inLHS, const ASArray<T> &inRHS){	return inLHS != inRHS;}template <class T>T* ASArray<T>::ASIndex(int inIndex){	if ((inIndex >= 0) && (inIndex < GetLength()))		return &array[inIndex];	// The script is trying to access memory that isn't 	// allowed so we'll throw an exception. 	asIScriptContext *context = asGetActiveContext(); 	// Should this function be called by the host application directly	// then there will not be any active context to set the exception on	if( context )		context->SetException("Array accessed out of range.");	return NULL;}template <class T>void ASArray<T>::ASRemove(int inIndex){	if ((inIndex >= 0) && (inIndex < GetLength()))		Remove(inIndex);}template <class T>void ASArray<T>::ASAddArray(const ASArray<T> & inArray){	(*this) += inArray;}#endif


Edit:
It *does* need a registered member-function "ASConstruct" for the specified type to work(?) though..
_-=[ "If there's anything more important than my ego around, I want it caught and shot now." ]=--=[ BeatHarness ]=-=[ Guerrilla Games ]=-=[ KillZone ]=-
Your code looks good, but wouldn't it be easier to derive your class from acCarray instead? This prevents you from having to change the same code in two different place.

I would put my vote on this for the official array implementation.
There could be an additional array variable type (besides refference, pointer and regular). This is how I imagine this (unless you overload the [] operator, it uses the build-in):
void array_add(int[]& array, int add) {	for(int i=0;i<array.count();i++)		array += add;}void main() {	int num_array[3] = { 7, 3, 15 };	array_add(num_array, 15);}
Advertisement
The code above is a nice trick to easily add array support for different types to the current version of AS - thanks for sharing the code.

I'd still not like that to be the official way to support arrays. Having a class of code generated (through template) for every distinct type of array to be used is bloat.

One feature I'm looking for in a scripting language is small size, which means that usage of STL and any heavy template structures would need to be limited. I do use e.g. STL quite heavily sometimes in my projects, but still my opinion is that a library like a scripting language should have more lightweight solution for supporting arrays.

BTW, what's the current plan for arrays - when are they coming?
--Jetro Lauha - tonic - http://jet.ro
Don't worry. This will not be the official way of handling arrays.

The way I will implement support for arrays in AngelScript will probably be with a factory function for allocating memory (kind of like the string factory function). When the memory has been allocated each item in the array is initialized by calling the constructor (if there is one). There will probably also be a function for accessing elements in the array through the indexing operator.

It will be designed for flexibility so that every application can choose their own exact implementation of arrays. It will also be up to the application if it wants to do bounds checking or not.

I will of course release a working example of how to register these functions to use arrays.

I can't say when native arrays will be implemented as I can't foresee how much time I will have to work on AngelScript. These last days I have had quite a lot of time, but that can change any time without warning (depends on the workload I get at my job). There are a few things that I think are more important than arrays, but they are few and I'll get to arrays soon enough. Arrays will NOT be supported in 1.9.x, but maybe in 1.10.x.

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

This topic is closed to new replies.

Advertisement