const_get 在 mruby 中如何工作?

How does const_get work in mruby?

我使用 mruby 1.3.0 (2017-7-4)build_config.rb:

MRuby::Build.new do |conf|
  if ENV['VisualStudioVersion'] || ENV['VSINSTALLDIR']
    toolchain :visualcpp
  else
    toolchain :gcc
  end
  enable_debug
  conf.gembox 'default'
  conf.gem :git => 'https://github.com/mattn/mruby-uv'
  conf.gem :git => 'https://github.com/mattn/mruby-http'
  conf.gem :git => 'https://github.com/iij/mruby-socket'
  conf.gem :git => 'https://github.com/luisbebop/mruby-polarssl.git'
  conf.gem :git => 'https://github.com/iij/mruby-digest'
  conf.gem :git => 'https://github.com/iij/mruby-pack'
  conf.gem :git => 'https://github.com/matsumoto-r/mruby-simplehttp.git'
  conf.gem :git => 'https://github.com/matsumotory/mruby-httprequest'
  conf.gem :git => 'https://github.com/iij/mruby-aws-s3.git'
end

MRuby::Build.new('host-debug') do |conf|
  if ENV['VisualStudioVersion'] || ENV['VSINSTALLDIR']
    toolchain :visualcpp
  else
      toolchain :gcc
  end

  enable_debug
  conf.gembox 'default'
  conf.cc.defines = %w(MRB_ENABLE_DEBUG_HOOK)
  conf.gem :core => "mruby-bin-debugger"
end

MRuby::Build.new('test') do |conf|
  if ENV['VisualStudioVersion'] || ENV['VSINSTALLDIR']
    toolchain :visualcpp
  else
    toolchain :gcc
  end
  enable_debug
  conf.enable_bintest
  conf.enable_test
  conf.gembox 'default'
end

我发现 const_get 方法在 mruby 中与在 ruby 中不同。在 ruby (2.4.0p0) 中,Class.const_get('Fixnum') returns 常量 Fixnum,而在 mruby Class.const_get('Fixnum') 中导致错误 uninitialized constant Class::Fixnum (NameError).

然后,我尝试了另一个例子:class Hoge; end; class Hoge::Fuga; end。在ruby中,Class.const_get('Hoge::Fuga')Hoge.const_get('Fuga')都给出了常量Hoge::Fuga。在mruby中,只有Hoge.const_get('Fuga')是returns Hoge::Fuga.

mruby 的 Module#const_get 与 CRuby 中的第二个参数(被命名为 inherit 以搜索超类)false 类似。 如果您改用 Object.const_get(:Integer),它的行为应该与您在 mruby 和 CRuby 中的预期相同。