diff --git a/doc/source/reference/language/builtin_functions.rst b/doc/source/reference/language/builtin_functions.rst index aeaa42f..ea2f1e0 100644 --- a/doc/source/reference/language/builtin_functions.rst +++ b/doc/source/reference/language/builtin_functions.rst @@ -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 ^^^^^^ diff --git a/squirrel/sqbaselib.cpp b/squirrel/sqbaselib.cpp index b37c975..5252788 100644 --- a/squirrel/sqbaselib.cpp +++ b/squirrel/sqbaselib.cpp @@ -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} };