Search code examples
arrayslualua-tablemetatable

How to get data from table in Lua


I have a table:

Table = {
    button = {},
    window = {},
    label = {},
    edit = {},
    error = {}
}

How I can get keys and values of the table?

I tried to get as:

for key, value in ipairs(Table) do
    for k, v in ipairs(key) do
       print(k, v)
    end
end

But it does't work.


Solution

  • ipairs is for sequences(i.e, array-like tables). But Table in your code is not a sequence, you need to use pairs instead.

    Another problem is that in Table, the keys are strings ("button", "window" etc.). That's because in the table constructor, button = {} is equivalent to ["button"] = {}.

    You need to iterate the values which are (now empty) tables.

    for key, value in pairs(Table) do
        for k, v in pairs(value) do
           print(k, v)
        end
    end