summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/expr.cc5
-rw-r--r--testdata/scad/misc/string-indexing.scad17
-rw-r--r--tests/CMakeLists.txt3
-rw-r--r--tests/regression/echotest/string-indexing-expected.txt11
4 files changed, 35 insertions, 1 deletions
diff --git a/src/expr.cc b/src/expr.cc
index fc1fbf0..7e1a25b 100644
--- a/src/expr.cc
+++ b/src/expr.cc
@@ -85,6 +85,11 @@ Value Expression::evaluate(const Context *context) const
if (i >= 0 && i < int(v1.vec.size()))
return *v1.vec[i];
}
+ if (v1.type == Value::STRING && v2.type == Value::NUMBER) {
+ int i = (int)(v2.num);
+ if (i >= 0 && i < v1.text.size())
+ return Value(v1.text.substr(i, 1));
+ }
return Value();
}
if (this->type == "I")
diff --git a/testdata/scad/misc/string-indexing.scad b/testdata/scad/misc/string-indexing.scad
new file mode 100644
index 0000000..3dc31c9
--- /dev/null
+++ b/testdata/scad/misc/string-indexing.scad
@@ -0,0 +1,17 @@
+test = "test";
+
+// Correct usage cases
+for(i = [0:len(test)-1]) {
+ echo(test[i]);
+}
+
+// Out of bounds
+echo(test[-1]);
+echo(test[len(test)]);
+
+// Invalid index type
+echo(test["test"]);
+echo(test[true]);
+echo(test[false]);
+echo(test[[0]]);
+echo(test[1.7]); \ No newline at end of file
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 31420b3..5eb03eb 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -396,7 +396,8 @@ list(APPEND ECHO_FILES ${FUNCTION_FILES}
${CMAKE_SOURCE_DIR}/../testdata/scad/misc/parser-tests.scad
${CMAKE_SOURCE_DIR}/../testdata/scad/misc/builtin-tests.scad
${CMAKE_SOURCE_DIR}/../testdata/scad/misc/dim-all.scad
- ${CMAKE_SOURCE_DIR}/../testdata/scad/misc/string-test.scad)
+ ${CMAKE_SOURCE_DIR}/../testdata/scad/misc/string-test.scad
+ ${CMAKE_SOURCE_DIR}/../testdata/scad/misc/string-indexing.scad)
# Add echotest tests to CTest
add_cmdline_test(echotest txt ${ECHO_FILES})
diff --git a/tests/regression/echotest/string-indexing-expected.txt b/tests/regression/echotest/string-indexing-expected.txt
new file mode 100644
index 0000000..3fcdfa4
--- /dev/null
+++ b/tests/regression/echotest/string-indexing-expected.txt
@@ -0,0 +1,11 @@
+ECHO: "t"
+ECHO: "e"
+ECHO: "s"
+ECHO: "t"
+ECHO: undef
+ECHO: undef
+ECHO: undef
+ECHO: undef
+ECHO: undef
+ECHO: undef
+ECHO: "e"
contact: Jan Huwald // Impressum