Exemplo n.º 1
0
// Converts Go value to mruby value.
func (m *MRuby) mrubyValue(i interface{}) C.mrb_value {
	v := reflect.ValueOf(i)
	switch v.Kind() {
	case reflect.Invalid:
		return C.mrb_nil_value() // mrb_undef_value() explodes
	case reflect.Bool:
		b := v.Bool()
		if b {
			return C.mrb_true_value()
		} else {
			return C.mrb_false_value()
		}
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return C.mrb_fixnum_value(C.mrb_int(v.Int()))
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return C.mrb_fixnum_value(C.mrb_int(v.Uint()))
	case reflect.Float32, reflect.Float64:
		return C.mrb_float_value((*C.struct_mrb_state)(m.state), C.mrb_float(v.Float()))
	case reflect.String:
		cs := C.CString(v.String())
		defer C.free(unsafe.Pointer(cs))
		if v.Type() == symbolT {
			return C.mrb_check_intern_cstr(m.state, cs)
		} else {
			return C.mrb_str_new_cstr(m.state, cs)
		}
	case reflect.Array, reflect.Slice:
		l := v.Len()
		res := C.mrb_ary_new_capa(m.state, C.mrb_int(l))
		for i := 0; i < l; i++ {
			C.mrb_ary_set(m.state, res, C.mrb_int(i), m.mrubyValue(v.Index(i).Interface()))
		}
		return res
	case reflect.Map:
		l := v.Len()
		res := C.mrb_hash_new_capa(m.state, C.int(l))
		for _, key := range v.MapKeys() {
			val := v.MapIndex(key)
			C.mrb_hash_set(m.state, res, m.mrubyValue(key.Interface()), m.mrubyValue(val.Interface()))
		}
		return res
	}

	panic(fmt.Errorf("gomruby bug: failed to convert Go value %#v (%T) to mruby value", i, i))
}
Exemplo n.º 2
0
// Loads mruby code. Arguments are exposed as ARGV array.
func (c *LoadContext) Load(code string, args ...interface{}) (res interface{}, err error) {
	l := len(args)
	ARGV := C.mrb_ary_new_capa(c.m.state, C.mrb_int(l))
	for i := 0; i < l; i++ {
		ii := C.mrb_int(i)
		C.mrb_ary_set(c.m.state, ARGV, ii, c.m.mrubyValue(args[ii]))
	}
	C.mrb_define_global_const(c.m.state, argvCS, ARGV)

	codeC := C.CString(code)
	defer C.free(unsafe.Pointer(codeC))
	v := C.mrb_load_string_cxt(c.m.state, codeC, c.context)
	res = c.m.goValue(v)
	if c.m.state.exc != nil {
		v = C.mrb_obj_value(unsafe.Pointer(c.m.state.exc))
		err = errors.New(c.m.inspect(v))
	}
	return
}