This is a port of the mruby/c tutorial Chapter 03 to the mbed environment.

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers value.c Source File

value.c

00001 #include <stdint.h>
00002 #include <string.h>
00003 #include "value.h "
00004 #include "static.h"
00005 #include "symbol.h"
00006 #include "alloc.h"
00007 #include "vm.h"
00008 
00009 mrb_object *mrbc_obj_alloc(mrb_vm *vm, mrb_vtype tt)
00010 {
00011   mrb_object *ptr = (mrb_object *)mrbc_alloc(vm, sizeof(mrb_object));
00012   if( ptr ){
00013     ptr->tt = tt;
00014     ptr->next = 0;
00015   }
00016   return ptr;
00017 }
00018 
00019 mrb_class *mrbc_class_alloc(mrb_vm *vm, const char *name, mrb_class *super)
00020 {
00021   mrb_class *ptr = (mrb_class *)mrbc_alloc(vm, sizeof(mrb_class));
00022   if( ptr ){
00023     ptr->tt = MRB_TT_CLASS;
00024     ptr->super = super;
00025     ptr->name = add_sym (name);
00026     ptr->procs = 0;
00027     ptr->next = 0;
00028   }
00029   return ptr;
00030 }
00031 
00032 mrb_proc *mrbc_rproc_alloc(mrb_vm *vm, const char *name)
00033 {
00034   mrb_proc *ptr = (mrb_proc *)mrbc_alloc(vm, sizeof(mrb_proc));
00035   if( ptr ) {
00036     ptr->sym_id = add_sym (name);
00037     ptr->next = 0;
00038   }
00039   return ptr;
00040 }
00041 
00042 mrb_proc *mrbc_rproc_alloc_to_class(mrb_vm *vm, const char *name, mrb_class *cls)
00043 {
00044   mrb_proc *rproc = mrbc_rproc_alloc(vm, name);
00045   if( rproc != 0 ){
00046     rproc->next = cls->procs;
00047     cls->procs = rproc;
00048   }
00049   return rproc;
00050 }
00051 
00052 
00053 // EQ? two objects
00054 // EQ: return true
00055 // NEQ: return false
00056 int mrbc_eq(mrb_value *v1, mrb_value *v2)
00057 {
00058   // TT_XXX is different
00059   if( v1->tt != v2->tt ) return 0;
00060   // check value
00061   switch( v1->tt ){
00062   case MRB_TT_TRUE:
00063   case MRB_TT_FALSE:
00064   case MRB_TT_NIL:
00065     return 1;
00066   case MRB_TT_FIXNUM:
00067   case MRB_TT_SYMBOL:
00068     return v1->value.i == v2->value.i;
00069   case MRB_TT_FLOAT:
00070     return v1->value.d == v2->value.d;
00071   case MRB_TT_STRING:
00072     return !strcmp(v1->value.str, v2->value.str);
00073   case MRB_TT_ARRAY: {
00074     mrb_value *array1 = v1->value.obj;
00075     mrb_value *array2 = v2->value.obj;
00076     int i, len = array1[0].value.i;
00077     if( len != array2[0].value.i ) return 0;
00078     for( i=1 ; i<=len ; i++ ){
00079       if( !mrbc_eq(array1+i, array2+i) ) break;
00080     }
00081     if( i > len ){
00082       return 1;
00083     } else {
00084       return 0;
00085     }
00086   } break;
00087   default:
00088     return 0;
00089   }
00090 }
00091