initStdRequire method

void initStdRequire()

Implementation

void initStdRequire() {
  exec() {
    final modname = findVar('modname');
    final v = modname?.valueAs<String>();
    if (v == null) {
      final type = v.runtimeType;
      throw 'Expected string for modname in `require(modname)`. Found $type.';
    }

    Object? result;
    try {
      pushScope();
      result = onRequireImpl?.call(v, this);
    } catch (e) {
      addError(e.toString());
    } finally {
      popScope();
    }

    onRequireImplComplete?.call(v);

    return result?.makeLuaRef()?.unpack() ?? LuaObject.nil(v);
  }

  final token = Token.synthesized('require');
  final defRequire = FuncExpr.named(
    token,
    body: [],
    args: [DeclArg(Token.synthesized('modname'))],
    idParts: [RawExpr(token)],
  );

  defGlobal(LuaObject.func('require', defRequire, exec)).doc = LuaDoc(
    category: catRuntime,
    html: '''
    The runtime resolves the lua script identified by <code>modname</code>, executes,
    and returns any values. This enables passing lua objects
    between files.
<pre>
<code class="language-lua">local f = require('fibonacci.lua')
print(f(7)) -- prints 13
</code>
</pre>
    ''',
  );
}