I'm getting started with mruby. I'm also pretty new to programming in C, so I may not be familiar with many of the basics. I was able to compile the example mruby program which loads the ruby code from a string. Now I would like to load it from an external file. Here's the example code that I'm using:
#include <stdlib.h>
#include <stdio.h>
#include <mruby.h>
static mrb_value my_c_method(mrb_state *mrb, mrb_value value)
{
puts("Called my C method");
return value;
}
int main(void)
{
mrb_state *mrb = mrb_open();
struct RClass *mymodule = mrb_define_module(mrb, "MyModule");
mrb_define_class_method(mrb, mymodule, "my_c_method", my_c_method, MRB_ARGS_NONE());
mrb_load_string(mrb, "MyModule.my_c_method"); // move this to an external file
return 0;
}
As you can see in the example above, I would like to move the ruby code to an external file. I'm a little confused as to whether or not I can simply "include" the ruby file, or if I need to precompile it into an .mrb
file. Even then I'm not sure how to include that .mrb
file when compiling.
What do I need to change to be able to load the ruby code from an external file?
In the mruby/compile.h
there is a method called mrb_load_file
which allows you to load a ruby file and execute it with mruby:
#include <stdlib.h>
#include <stdio.h>
#include <mruby.h>
#include <mruby/compile.h>
static mrb_value my_c_method(mrb_state *mrb, mrb_value value)
{
puts("Called my C method");
return value;
}
int main(void)
{
mrb_state *mrb = mrb_open();
struct RClass *mymodule = mrb_define_module(mrb, "MyModule");
mrb_define_class_method(mrb, mymodule, "my_c_method", my_c_method, MRB_ARGS_NONE());
FILE *f = fopen("example.rb", "r");
mrb_load_file(mrb, f);
return 0;
}