瀏覽代碼

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

Implement table.filter() default delegate in base library
Alberto Demichelis 8 年之前
父節點
當前提交
453a966890
共有 2 個文件被更改,包括 34 次插入0 次删除
  1. 5 0
      doc/source/reference/language/builtin_functions.rst
  2. 29 0
      squirrel/sqbaselib.cpp

+ 5 - 0
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
 ^^^^^^

+ 29 - 0
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}
 };