Merge pull request #119 from VasiliyRyabtsev/feature/table-filter

Implement table.filter() default delegate in base library
This commit is contained in:
Alberto Demichelis 2017-12-05 16:28:35 +08:00 committed by GitHub
commit 453a966890
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 0 deletions

View File

@ -316,6 +316,11 @@ Sets the delegate of the table. To remove a delegate, 'null' must be passed to t
returns the table's delegate or null if no delegate was set.
.. js:function:: table.filter(func(key,val))
Creates a new table with all values that pass the test implemented by the provided function. In detail, it creates a new table, invokes the specified function for each key-value pair in the original table; if the function returns 'true', then the value is added to the newly created table at the same key.
^^^^^^
Array
^^^^^^

View File

@ -472,6 +472,34 @@ static SQInteger table_getdelegate(HSQUIRRELVM v)
return SQ_SUCCEEDED(sq_getdelegate(v,-1))?1:SQ_ERROR;
}
static SQInteger table_filter(HSQUIRRELVM v)
{
SQObject &o = stack_get(v,1);
SQTable *tbl = _table(o);
SQObjectPtr ret = SQTable::Create(_ss(v),0);
SQObjectPtr itr, key, val;
SQInteger nitr;
while((nitr = tbl->Next(false, itr, key, val)) != -1) {
itr = (SQInteger)nitr;
v->Push(o);
v->Push(key);
v->Push(val);
if(SQ_FAILED(sq_call(v,3,SQTrue,SQFalse))) {
return SQ_ERROR;
}
if(!SQVM::IsFalse(v->GetUp(-1))) {
_table(ret)->NewSlot(key, val);
}
v->Pop();
}
v->Push(ret);
return 1;
}
const SQRegFunction SQSharedState::_table_default_delegate_funcz[]={
{_SC("len"),default_delegate_len,1, _SC("t")},
{_SC("rawget"),container_rawget,2, _SC("t")},
@ -483,6 +511,7 @@ const SQRegFunction SQSharedState::_table_default_delegate_funcz[]={
{_SC("clear"),obj_clear,1, _SC(".")},
{_SC("setdelegate"),table_setdelegate,2, _SC(".t|o")},
{_SC("getdelegate"),table_getdelegate,1, _SC(".")},
{_SC("filter"),table_filter,2, _SC("tc")},
{NULL,(SQFUNCTION)0,0,NULL}
};