it’s well known that to get the index of a value in a table with for loop, you simply need to see what’s the value of index on the for loop, but my problem is that i’m using those parameters in a different way, since my table has variables in it, and i need to get the Name of the variable and the value of the variable, and to do that i use the spot of index to get the name of the variable
for name, value in pairs(table) do -- printing name returns the name and not the index
so, my question is, there is a way to get the index, name of the variable, and the value from a table with for loops?
thanks for anyone who replies :DD
EDIT: i already tried to use table.getn(table, name) but it returns 0
local index = 1
for name,value in pairs(table) do
index += 1
end
table = [
[1] = "foo",
["bar"] = "bar"
]
--if you use pairs
for name,value in pairs(table) do
print(name) --prints 1 and bar
end
--if you use ipairs
for name,value in ipairs(table) do
print(name) --prints only 1
end
because pairs works like an linked list
ipairs is handle like an array
i was thinking about creating a number variable to set it as the index, but i feel like its a bad practice,
anyways, i’ll use that as an alternative, thanks for the help :))
An “index” doesn’t exist for dictionaries, like the entries in local t = { a = 1, b = 2, c = 3 }
The order that pairs() (or next()) traverses your dictionary is unspecified, and will not be the same order in which things were written or inserted.
If you want to maintain order of things, use an array, not a dictionary:
local ordered = {
{name = "name1", value = "value1"},
{name = "name2", value = "value2"},
{name = "name3", value = "value3"}
}
And iterate through it with a numeric for loop (for i = 1, #t do) or a generic for loop with ipairs:
for i, v in ipairs(ordered) do -- or: for i = 1, #ordered do local v = ordered[i] ...
print("index:", i, "name:", v.name, "value:", v.value)
end
-- index: 1 name: name1 value: value1
-- index: 2 name: name2 value: value2
-- index: 3 name: name3 value: value3