ref: b46ee8d829027bb4eb54a49498205dda98857b2a
parent: 780b14b5b73724c36800bf72db1f8f1a2b77f76d
author: Tor Andersson <[email protected]>
date: Fri Apr 27 11:07:38 EDT 2018
Add more js_tryxxx conversion functions.
--- a/docs/reference.html
+++ b/docs/reference.html
@@ -313,7 +313,7 @@
<pre>
if (js_try(J)) {
- fprintf(stderr, "error: %s", js_tostring(J, -1));
+ fprintf(stderr, "error: %s", js_trystring(J, -1, "Error"));
js_pop(J, 1);
return;
}
@@ -422,7 +422,7 @@
<pre>
int js_toboolean(js_State *J, int idx);
double js_tonumber(js_State *J, int idx);
-double js_tointeger(js_State *J, int idx);
+int js_tointeger(js_State *J, int idx);
int js_toint32(js_State *J, int idx);
unsigned int js_touint32(js_State *J, int idx);
short js_toint16(js_State *J, int idx);
@@ -440,6 +440,19 @@
<p>
There is no guarantee that the pointer returned by js_tostring will be valid after
the corresponding value is removed from the stack.
+
+<p>
+Note that the toString and valueOf methods that may be invoked by these functions
+can throw exceptions. If you want to catch and ignore exceptions, use the following
+functions instead. The 'error' argument is the default value that will be returned
+if a toString/valueOf method throws an exception.
+
+<pre>
+int js_tryboolean(js_State *J, int idx, int error);
+double js_trynumber(js_State *J, int idx, double error);
+int js_tryinteger(js_State *J, int idx, int error);
+const char *js_trystring(js_State *J, int idx, const char *error);
+</pre>
<h3>Objects</h3>
--- a/jsstate.c
+++ b/jsstate.c
@@ -58,6 +58,42 @@
return s;
}
+double js_trynumber(js_State *J, int idx, double error)
+{
+ double v;
+ if (js_try(J)) {
+ js_pop(J, 1);
+ return error;
+ }
+ v = js_tonumber(J, idx);
+ js_endtry(J);
+ return v;
+}
+
+int js_tryinteger(js_State *J, int idx, int error)
+{
+ int v;
+ if (js_try(J)) {
+ js_pop(J, 1);
+ return error;
+ }
+ v = js_tointeger(J, idx);
+ js_endtry(J);
+ return v;
+}
+
+int js_tryboolean(js_State *J, int idx, int error)
+{
+ int v;
+ if (js_try(J)) {
+ js_pop(J, 1);
+ return error;
+ }
+ v = js_toboolean(J, idx);
+ js_endtry(J);
+ return v;
+}
+
static void js_loadstringx(js_State *J, const char *filename, const char *source, int iseval)
{
js_Ast *P;
--- a/mujs.h
+++ b/mujs.h
@@ -181,6 +181,9 @@
void *js_touserdata(js_State *J, int idx, const char *tag);
const char *js_trystring(js_State *J, int idx, const char *error);
+double js_trynumber(js_State *J, int idx, double error);
+int js_tryinteger(js_State *J, int idx, int error);
+int js_tryboolean(js_State *J, int idx, int error);
int js_tointeger(js_State *J, int idx);
int js_toint32(js_State *J, int idx);