Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 747
owl Avatar asked Jan 20 '14 05:01

owl


People also ask

How do you get values in Lua?

To access the value associated with the key in a table you can use the table[key] syntax: > t = {} > t["foo"] = 123 -- assign the value 123 to the key "foo" in the table > t[3] = "bar" -- assign the value "bar" to the key 3 in the table > = t["foo"] 123 > = t[3] bar.

How does a table work in Lua?

Tables in Lua have the features of an OOP object like state and identity that is independent of its values. Two objects (tables) with the same value are different objects, whereas an object can have different values at different times, but it is always the same object.

Can you print a table in Lua?

Finally, print() is used for printing the tables. Below are some of the methods in Lua that are used for table manipulation. Strings in the table will be concatenated based on the given parameters.

How do I index a table in Lua?

For Lua, that means "index the table io using the string "read" as the key". When a program has no references to a table left, Lua memory management will eventually delete the table and reuse its memory. Notice the last line: Like global variables, table fields evaluate to nil if they are not initialized.


1 Answers

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
like image 105
Yu Hao Avatar answered Sep 28 '22 08:09

Yu Hao