fieldValueAs<T> method

T? fieldValueAs<T>(
  1. String key, {
  2. T? or,
})

Inspects the result of readField with key. If the result's type is LuaObject, then it also inspects its this.value. If the underlying value type is T, then it is returned. If no underlying value type matches T, then or is returned.

For non-table lua objects, see valueAs.

Implicit Casting

If the underlying value is of type double and the requested T type is int then an implicit cast is performed.

This is because in lua, reals and integers are stored the same way and the fractional part of the stored value determines whether or not some lua value is or isn't an integer.

Implementation

T? fieldValueAs<T>(String key, {T? or}) {
  uses++;
  if (skipSemanitcs) return or;

  final v = switch (readField(key)) {
    final LuaObject obj => obj.value,
    final Object? other => other,
  };

  if (v is double && T == int) {
    return v.toInt() as T;
  }

  return switch (v) {
    final T obj => obj,
    _ => or,
  };
}