Allow argument lists in Function() (fix #505)

This commit is contained in:
Gordon Williams 2015-03-31 09:57:49 +01:00
parent e86615bf95
commit 23225597b0
4 changed files with 40 additions and 4 deletions

View File

@ -18,6 +18,7 @@
Fix assert fail on debug builds on Waveform output (fix #511)
Added more allowed types of whitespace
Added String.prototype.trim() (fix #507)
Allow argument lists in Function() (fix #505)
1v75 : Fixed issue with Pins/Bools as Array indices
Fix crash when out of memory while creating built-in object

View File

@ -164,7 +164,7 @@ static ALWAYS_INLINE void jsvObjectIteratorNext(JsvObjectIterator *it) {
}
}
/// Remove the current element and move to next element. Needs the parent supplied (the JsVar passed to jsvArrayIteratorNew) as we don't store it
/// Remove the current element and move to next element. Needs the parent supplied (the JsVar passed to jsvObjectIteratorNew) as we don't store it
static ALWAYS_INLINE void jsvObjectIteratorRemoveAndGotoNext(JsvObjectIterator *it, JsVar *parent) {
if (it->var) {
JsVarRef next = jsvGetNextSibling(it->var);

View File

@ -48,17 +48,45 @@ JsVar *jswrap_arguments() {
"name" : "Function",
"generate" : "jswrap_function_constructor",
"params" : [
["code","JsVar","A string representing the code to run"]
["args","JsVarArray","Zero or more arguments (as strings), followed by a string representing the code to run"]
],
"return" : ["JsVar","A Number object"]
}
Creates a function
*/
JsVar *jswrap_function_constructor(JsVar *code) {
JsVar *jswrap_function_constructor(JsVar *args) {
JsVar *fn = jsvNewWithFlags(JSV_FUNCTION);
if (!fn) return 0;
JsVar *codeStr = jsvVarPrintf("{\n%v\n}", code);
/* Slightly odd form because we want to iterate
* over all items, but leave the final one as
* that will be for code. */
JsvObjectIterator it;
jsvObjectIteratorNew(&it, args);
JsVar *v = jsvObjectIteratorGetValue(&it);
jsvObjectIteratorNext(&it);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *s = jsvAsString(v, false);
if (s) {
// copy the string - if a string was supplied already we want to make
// sure we have a new (unreferenced) string
JsVar *paramName = jsvNewFromStringVar(s, 0, JSVAPPENDSTRINGVAR_MAXLENGTH);
jsvUnLock(s);
if (paramName) {
jsvMakeFunctionParameter(paramName); // force this to be called a function parameter
jsvAddName(fn, paramName);
jsvUnLock(paramName);
}
}
jsvUnLock(v);
v = jsvObjectIteratorGetValue(&it);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
JsVar *codeStr = jsvVarPrintf("{\n%v\n}", v);
jsvUnLock(v);
jsvUnLock(jsvObjectSetChild(fn, JSPARSE_FUNCTION_CODE_NAME, codeStr));
return fn;
}

View File

@ -0,0 +1,7 @@
var a = new Function('return 42');
var ra = a()==42;
var adder = new Function('a', 'b', 'return a + b');
var rb = adder(2, 6)==8;
result = ra && rb;