openlang

lua: collecting a table’s keys into another table

I'd like to find out how to obtain all the keys from a lua table. For instance, suppose this is my table:

entries = {}
entries[2] = 'c'
entries[4] = 'd'
entries[7] = 'h'

What I want back is a table resembling this one:

indices = {2, 4, 7}

The conversation continues 2

Follow the reasoning
  1. Permalink
    local indices={}
    local count=0
    for index, value in pairs(entries) do
      count=count+1
      indices[count]=index
    end

    Note that indices has no guaranteed ordering. To obtain the keys sorted, apply a sort to indices using table.sort(indices).

  2. Permalink
    local function collect_indices(source)
      local result={}
      for index,_ in pairs(source) do
        table.insert(result, index)
      end
      return result
    end

Other sides of the same question

  1. Choosing enum entries randomly with GDScript in Godot 3.3 without listing each one?

    Here's the enum declaration I'm using in GDScript: I'd like to choose an enum variant randomly without listing every possible…

    Replies 2Latest activity gdscript
  2. Nim remainder syntax

    How is modulus expressed in Nim? cell % 7 == 0 gives undeclared identifier: '%' Neither a Google search nor looking through S…

    Replies 2Latest activity nim
  3. Returning results from an APL function

    How do I make my function return something once execution has finished? For instance, I have: ROUTINE N ? N ⍴ 12 //That gener…

    Replies 2Latest activity apl