Angelscript transfer array from C++

423 views Asked by At

I need to transfer an array of tiles from C++ to Angelscript, I have tried adding a function that returns an std::vector but it returns this error

Failed in call to function 'RegisterGlobalFunction' with 'array<DumbTile> GetTilesAt(int x, int y)' (Code: asINVALID_DECLARATION, -10) 


my code:

std::vector<DumbTile> GetTilesAt(int x, int y) {
    std::vector<DumbTile> output;
    for (DumbTile t : tiles) {
        if (t.x == x && t.y == y) {
            output.push_back(t);
        }
    }
    return output;
}
engine->RegisterGlobalFunction("array<DumbTile> GetTilesAt(int x, int y)", asFUNCTIONPR(GetTilesAt, (int, int), std::vector<DumbTile>), asCALL_CDECL); 
1

There are 1 answers

2
Samira On BEST ANSWER

Is DumbTile registered before GetTilesAt() registration?

Is array<T> registered before GetTilesAt() registration?

Both needs to be registered before you can register your function.

Are you using stock array implementation (sdk/add_on/scriptarray/) or your own, std::vector<>-based implementation? When using stock addon, application must convert std::vector to CScriptArray first, as angelscript can't really do that on its own due to way how arrays works.

There is obvious alternative - switch from using std::vector to CScriptArray everywhere where you want scripts to access data, but this might be annoying.


Example std::vector<Object*> <-> CScriptArray* conversion

template<typename Type>
void AppendVectorToArrayRef( vector<Type>& vec, CScriptArray* arr )
{
    if( !vec.empty() && arr )
    {
        uint i = (uint)arr->GetSize();
        arr->Resize( (asUINT)(i + (uint)vec.size() ) );
        for( uint k = 0, l = (uint)vec.size(); k < l; k++, i++ )
        {
            Type* p = (Type*)arr->At( i );
            *p = vec[k];
            (*p)->AddRef();
        }
    }
}
template<typename Type>
void AssignScriptArrayInVector( vector<Type>& vec, CScriptArray* arr )
{
    if( arr )
    {
        uint count = (uint)arr->GetSize();
        if( count )
        {
            vec.resize( count );
            for( uint i = 0; i < count; i++ )
            {
                Type* p = (Type*)arr->At( i );
                vec[i] = *p;
            }
        }
    }
}

Code is bit old but i think it should still work, even if it begs for some refresh.