diff --git a/docs/tutorial.md b/docs/tutorial.md index f3be0ba..d4318af 100644 --- a/docs/tutorial.md +++ b/docs/tutorial.md @@ -316,6 +316,14 @@ one could be with ellipsis that means "the rest pf arguments as List": assert( { a, b...-> [a,...b] }(100, 1, 2, 3) == [100, 1, 2, 3]) void +### Using lambda as the parameter + + fun mapValues(iterable, transform) { + var result = [] + for( x in iterable ) result += transform(x) + } + assert( [11, 21, 31] == mapValues( [1,2,3], { it*10+1 })) + >>> void # Lists (aka arrays) diff --git a/library/src/commonMain/kotlin/net/sergeych/lyng/Compiler.kt b/library/src/commonMain/kotlin/net/sergeych/lyng/Compiler.kt index 3e9c69a..6173afc 100644 --- a/library/src/commonMain/kotlin/net/sergeych/lyng/Compiler.kt +++ b/library/src/commonMain/kotlin/net/sergeych/lyng/Compiler.kt @@ -499,7 +499,7 @@ class Compiler( else -> { cc.previous() - parseStatement(cc)?.let { args += ParsedArgument(it, t.pos) } + parseExpression(cc)?.let { args += ParsedArgument(it, t.pos) } ?: throw ScriptError(t.pos, "Expecting arguments list") } } diff --git a/library/src/commonTest/kotlin/ScriptTest.kt b/library/src/commonTest/kotlin/ScriptTest.kt index 7acfdde..9551a58 100644 --- a/library/src/commonTest/kotlin/ScriptTest.kt +++ b/library/src/commonTest/kotlin/ScriptTest.kt @@ -1138,7 +1138,8 @@ class ScriptTest { @Test fun testIsPrimeSampleBug() = runTest { - eval(""" + eval( + """ fun naive_is_prime(candidate) { val x = if( candidate !is Int) candidate.toInt() else candidate var divisor = 1 @@ -1151,6 +1152,20 @@ class ScriptTest { } naive_is_prime(4) - """.trimIndent()) + """.trimIndent() + ) + } + + @Test + fun testLambdaAsFnCallArg() = runTest { + eval( + """ + fun mapValues(iterable, transform) { + var result = [] + for( x in iterable ) result += transform(x) + } + assert( [11, 21, 31] == mapValues( if( true) [1,2,3] else [10], { it*10+1 })) + """.trimIndent() + ) } } \ No newline at end of file