initStdTable method

void initStdTable()

Implementation

void initStdTable() {
  defGlobal(
    LuaObject.tableFrom('table', [
      LuaFuncBuilder.create('insert')
        .arg('t')
        .arg('position')
        .arg('value', optional: true)
        .exec(
          call: () {
            LuaObject? tableData = findVar('t');

            if ((tableData?.isNil ?? true) || tableData!.isNotTable) {
              throw 'Expected table argument "t" for function.';
            }

            LuaObject? value = findVar('value');
            int? position;

            if (value?.isNil ?? true) {
              value = findVar('position');

              // Insert a nil value is a noop
              if (value == null) {
                return LuaObject.nil('ret');
              }
            } else {
              final pos = findVar('position');
              position = pos?.valueAsInt();

              if ((pos?.isNil ?? true) || position == null) {
                throw 'Expected integer "position" for function.';
              }
            }

            final int sz = tableData.tableSize;
            final int next = (position ?? sz) + 1;
            if (tableData.tableInsert(next, value!) == null) {
              throw 'Index out of bounds: $next with bounds of $sz.';
            }
          },
        )
      ..doc = LuaDoc(
        category: catRuntime,
        html: '''
        Inserts <code>value</code> into table <code>t</code> at <code>position</code>.<br/>
        <br/>
        If only two arguments are given, then the second argument becomes <code>value</code>
        and the <code>position</code> is determined to be the front of the table <code>t</code>.<br/>
        This is convenient to write stacks in lua.
<pre><code class="language-lua">local t = {}
table.insert(t, 1, "foo")
-- is the same as
table.insert(t, "foo")
</code></pre>
              ''',
      ),
      LuaFuncBuilder.create('remove')
        .arg('tableData')
        .arg('position')
        .exec(
          call: () {
            LuaObject? tableData = findVar('tableData');

            if ((tableData?.isNil ?? true) || tableData!.isNotTable) {
              throw 'Expected table argument "tableData" for function.';
            }

            int? position = findVar('value')?.valueAsInt();

            if (position == null) {
              throw 'Expected integer "position" for function.';
            }

            return tableData.tableRemove(position);
          },
        ),
      ],
    ),
  ).doc = LuaDoc(
    category: catRuntime,
    html: '''
    Tables are to lua what classes are to other modern programming languages.<br/>
    They can also be used as lists.
    ''',
  );
}