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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With