diff --git a/src/proc.c b/src/proc.c index e3d06408c..1b31d4e98 100644 --- a/src/proc.c +++ b/src/proc.c @@ -130,6 +130,14 @@ mrb_closure_new(mrb_state *mrb, const mrb_irep *irep) return p; } +/* + * Creates a new Proc object from a C function. + * + * mrb: The mruby state. + * func: The C function to create the Proc from. + * + * Returns a pointer to the new Proc object. + */ MRB_API struct RProc* mrb_proc_new_cfunc(mrb_state *mrb, mrb_func_t func) { @@ -144,6 +152,17 @@ mrb_proc_new_cfunc(mrb_state *mrb, mrb_func_t func) return p; } +/* + * Creates a new Proc object from a C function with a new environment. + * + * mrb: The mruby state. + * func: The C function to create the Proc from. + * argc: The number of arguments to be stored in the environment. + * argv: The array of mrb_value to be stored in the environment. + * These values are copied into the environment. + * + * Returns a pointer to the new Proc object. + */ MRB_API struct RProc* mrb_proc_new_cfunc_with_env(mrb_state *mrb, mrb_func_t func, mrb_int argc, const mrb_value *argv) { @@ -172,12 +191,44 @@ mrb_proc_new_cfunc_with_env(mrb_state *mrb, mrb_func_t func, mrb_int argc, const return p; } +/* + * Creates a new closure from a C function. + * + * This function creates a new Proc object that represents a C function + * along with an environment for a specified number of local variables. + * The local variables in the environment are initialized to nil. + * + * mrb: The mruby state. + * func: The C function to create the closure from. + * nlocals: The number of local variables to allocate space for in the + * closure's environment. + * + * Returns a pointer to the new Proc object representing the closure. + */ MRB_API struct RProc* mrb_closure_new_cfunc(mrb_state *mrb, mrb_func_t func, int nlocals) { return mrb_proc_new_cfunc_with_env(mrb, func, nlocals, NULL); } +/* + * Retrieves a value from the environment of the currently executing C function Proc. + * + * This function is used within a C function that was wrapped into a Proc + * (e.g., using mrb_closure_new_cfunc or mrb_proc_new_cfunc_with_env) + * to access values stored in its associated environment. + * + * mrb: The mruby state. + * idx: The index of the value to retrieve from the C function's environment. + * The index must be non-negative and less than the number of + * environment entries (argc passed during creation). + * + * Returns the mrb_value stored at the specified index in the environment. + * + * Raises E_TYPE_ERROR if the currently executing Proc is not a C function + * or if it does not have an associated environment. + * Raises E_INDEX_ERROR if the provided index is out of bounds. + */ MRB_API mrb_value mrb_proc_cfunc_env_get(mrb_state *mrb, mrb_int idx) {