summaryrefslogtreecommitdiff
path: root/src/core/script/Function.hpp
diff options
context:
space:
mode:
authorAndreas Stöckel <astoecke@techfak.uni-bielefeld.de>2014-10-24 13:25:04 +0000
committerandreas <andreas@daaaf23c-2e50-4459-9457-1e69db5a47bf>2014-10-24 13:25:04 +0000
commit4a9912f516bf096c6f8c6259b3fc6ba4b95b8d69 (patch)
treee4b578c76e27ade40de5d2cae2efbd2b17d18e59 /src/core/script/Function.hpp
parentc654793a3a513a9c8ffcd1aa9c3962b6a72e61bd (diff)
finished implementation of HostFunction
git-svn-id: file:///var/local/svn/basicwriter@74 daaaf23c-2e50-4459-9457-1e69db5a47bf
Diffstat (limited to 'src/core/script/Function.hpp')
-rw-r--r--src/core/script/Function.hpp67
1 files changed, 66 insertions, 1 deletions
diff --git a/src/core/script/Function.hpp b/src/core/script/Function.hpp
index 35e2205..4c13dbc 100644
--- a/src/core/script/Function.hpp
+++ b/src/core/script/Function.hpp
@@ -46,6 +46,13 @@ public:
*/
virtual Variant call(const std::vector<Variant> &args) const = 0;
+ /**
+ * Calls the underlying function with no arguments.
+ *
+ * @return a Variant containing the return value.
+ */
+ Variant call() const { return call({}); }
+
};
/**
@@ -70,7 +77,7 @@ struct ArgumentDescriptor {
* ArgumentValidatorError is an exception type used to represent argument
* validator errors.
*/
-class ArgumentValidatorError : std::exception {
+class ArgumentValidatorError : public std::exception {
public:
@@ -110,6 +117,11 @@ private:
*/
std::string errorMessage;
+ std::pair<bool, std::vector<Variant>> setError(int idx,
+ const std::string &msg, std::vector<Variant> &res);
+
+ void resetError();
+
public:
/**
@@ -153,6 +165,59 @@ public:
/**
* The HostFunction class represents a function that resides in the script host.
*/
+template<class T>
+class HostFunction : public Function {
+
+private:
+ T callback;
+ ArgumentValidator *validator;
+ void *data;
+
+public:
+
+ HostFunction(T callback, std::vector<ArgumentDescriptor> signature,
+ void *data = nullptr) :
+ callback(callback), validator(new ArgumentValidator(signature)),
+ data(data) {}
+
+ HostFunction(T callback, void *data = nullptr) :
+ callback(callback), validator(nullptr), data(data) {}
+
+ ~HostFunction()
+ {
+ delete validator;
+ }
+
+ virtual Variant call(const std::vector<Variant> &args) const override
+ {
+ if (validator) {
+ std::pair<bool, std::vector<Variant>> res = validator->validate(args);
+ if (!res.first) {
+ throw validator->error();
+ }
+ return callback(res.second, data);
+ } else {
+ return callback(args, data);
+ }
+ }
+
+ using Function::call;
+
+};
+
+template<class T>
+static HostFunction<T> createHostFunction(T callback,
+ std::vector<ArgumentDescriptor> signature, void *data = nullptr)
+{
+ return HostFunction<T>(callback, signature, data);
+}
+
+template<class T>
+static HostFunction<T> createHostFunction(T callback, void *data = nullptr)
+{
+ return HostFunction<T>(callback, data);
+}
+
}
}