initMiscRuntime method

void initMiscRuntime()

Implementation

void initMiscRuntime() {
  pcall() {
    final fn = findVar('fn')?.toLuaRet();
    if (fn == null || fn.isNotFunc) {
      throw 'pcall expects a function argument!';
    }

    String err = '';
    except(e) {
      err = e.toString();
    }

    final results = callLuaFunction(fn, onException: except);

    if (err.isNotEmpty) {
      return [false.toLuaRet(), err.toLuaRet()];
    }

    // OK
    return [true.toLuaRet(), ...results];
  }

  defGlobal(
    LuaFuncBuilder.create('pcall').arg('fn').exec(call: pcall),
  ).doc = LuaDoc(
    category: catRuntime,
    html: '''
      The <code>pcall</code> function calls its first argument in protected mode,
      so that it catches any errors while the function is running. If there are no errors,
      <code>pcall</code> returns <code>true</code> plus any values returned by the call.
      Otherwise, it returns <code>false</code> plus the error message.'
      ''',
  );

  defGlobal(
    LuaFuncBuilder.create('xpcall').arg('fn').exec(call: pcall),
  ).doc = LuaDoc(
    category: catRuntime,
    html: '''
    This lua runtime does not support the debug library nor stack traces at runtime.
    Therefore the function <code>xpcall</code> is another name for <code>pcall</code>.
    They do the same thing.
    ''',
  );
}