initStdStrings method

void initStdStrings()

Implementation

void initStdStrings() {
  final defToString = LuaFuncBuilder.create('tostring')
      .arg('value')
      .exec(
        call: () {
          final value = findVar('value');
          if (value == null) return 'nil';
          return value.toString();
        },
      );

  defGlobal(defToString).doc = LuaDoc(
    category: catRuntime,
    html: '''
    Converts any lua object into a printable string.</br>
    Depending on the runtime implementation, calling
    <code>tostring</code> on tables
    and functions print their address.
    ''',
  );

  // https://www.lua.org/pil/2.html
  final defType = LuaFuncBuilder.create('type')
      .arg('obj')
      .exec(
        call: () {
          final obj = findVar('obj');
          switch (obj) {
            case null:
              // Case: internal form.
              return 'nil';
            case final LuaObject lua:
              if (lua.isFunc) return 'function';
              if (lua.isTable) return 'table';
              if (lua.isNil) return 'nil';
              return switch (lua.value) {
                final String _ => 'string',
                final num _ => 'number',
                final bool _ => 'boolean',
                _ => 'userdata',
              };
          }
        },
      );

  defGlobal(defType).doc = LuaDoc(
    category: catRuntime,
    html: '''
    Returns the name of the lua object's type as a <code>string</code>.<br/>
    The supported types are:
    <ol>
    <li>function</li>
    <li>table</li>
    <li>nil</li>
    <li>string</li>
    <li>number</li>
    <li>boolean</li>
    </ol>
    If the runtime detects a value other than the
    primitives listed above, then <code>"userdata"</code>
    is returned.
    ''',
  );
}