initStdInclude method

void initStdInclude()

Implementation

void initStdInclude() {
  include() {
    final path = findVar('path');
    final v = path?.valueAs<String>();
    if (v == null) {
      final type = v.runtimeType;
      throw 'Expected string for include path, found $type.';
    }

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

    onVisitInclude?.call(v);

    if (included is LuaObject) {
      return included;
    }

    return LuaObject.variable(v, included);
  }

  final token = Token.synthesized('include');
  final defInclude = FuncExpr.named(
    token,
    body: [],
    args: [DeclArg(Token.synthesized('path'))],
    idParts: [RawExpr(token)],
  );

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