jessedoyle / duktape.cr

Evaluate JavaScript from Crystal!
MIT License
137 stars 17 forks source link

Add push_global_proc method #17

Closed jessedoyle closed 8 years ago

jessedoyle commented 8 years ago

This PR simplifies the process to push a named native function to the Duktape stack:

sbx.push_global_proc("test", 0) do |ptr|
  env = Duktape::Sandbox.new ptr
  env << 42
  env.call_success 
end

sbx.eval!("test();") # => 42

This PR also adds the env.call_success, env.call_failure and env.return_undefined helpers to return the proper integer status codes from a native call.

Note: call_failure may optionally take a symbol that will define the type of error object pushed to the stack after a call.

Here's the current possible symbols:

    ERRORS = {
      unimplemented: -LibDUK::ERR_UNIMPLEMENTED_ERROR,
      unsupported:   -LibDUK::ERR_UNSUPPORTED_ERROR,
      internal:      -LibDUK::ERR_INTERNAL_ERROR,
      alloc:         -LibDUK::ERR_ALLOC_ERROR,
      assertion:     -LibDUK::ERR_ASSERTION_ERROR,
      api:           -LibDUK::ERR_API_ERROR,
      uncaught:      -LibDUK::ERR_UNCAUGHT_ERROR,
      error:         -LibDUK::ERR_ERROR,
      eval:          -LibDUK::ERR_EVAL_ERROR,
      range:         -LibDUK::ERR_RANGE_ERROR,
      reference:     -LibDUK::ERR_REFERENCE_ERROR,
      syntax:        -LibDUK::ERR_SYNTAX_ERROR,
      type:          -LibDUK::ERR_TYPE_ERROR,
      uri:           -LibDUK::ERR_URI_ERROR,
    }

So for example:

sbx.push_proc do |ptr|
  ...
  env.call_failure(:reference) # => causes a ReferenceError to be pushed to stack after the call
  ...
end