diff options
author | Marius Kintel <marius@kintel.net> | 2011-11-13 21:53:40 (GMT) |
---|---|---|
committer | Marius Kintel <marius@kintel.net> | 2011-11-13 21:53:40 (GMT) |
commit | be7b18043275a002892525164ff88d74c1884e86 (patch) | |
tree | 7a66364294a6d2f3b0a788e4e586c9e41f471e05 | |
parent | 2cfcdf557d7742422965035a64ef617ac043a429 (diff) | |
parent | af2d4223df8640dea8a7d5a79db1d89aab392269 (diff) |
Merge pull request #36 from brad/stringindexing
String indexing
-rw-r--r-- | src/expr.cc | 5 | ||||
-rw-r--r-- | testdata/scad/misc/string-indexing.scad | 17 | ||||
-rw-r--r-- | tests/CMakeLists.txt | 3 | ||||
-rw-r--r-- | tests/regression/echotest/string-indexing-expected.txt | 11 |
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" |