Felix
Felix

Reputation: 2386

Lua get index name of table as table

Is there any way to get every index value of a table?

Example:

local mytbl = {
    ["Hello"] = 123,
    ["world"] = 321
}

I want to get this:

{"Hello", "world"}

Upvotes: 0

Views: 1087

Answers (1)

Yu Hao
Yu Hao

Reputation: 122383

local t = {}
for k, v in pairs(mytbl) do
  table.insert(t, k)  -- or t[#t + 1] = k
end

Note that the order of how pairs iterates a table is not specified. If you want to make sure the elements in the result are in a certain order, use:

table.sort(t)

Upvotes: 5

Related Questions