Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Iterating through an array?

Asked by 8 years ago

I'm attempting to iterate through an array, like the following:

local array ={
['hi'] = "Hello";
['test'] = "Greetings";
}

and print out the key and value like: hi = Hello My current code is:

for i,v in ipairs(array) do
    print(i.." = "..v)
end

2 answers

Log in to vote
1
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
8 years ago

ipairs specifically only iterates through integer numerical indices. What you want to use is pairs:

for i,v in pairs(array)do
    print(i.." = "..v)
end
0
This is the answer you're looking for, why did someone vote down? I'm voting up, he doesn't deserve to lose rep for this, it works! General_Scripter 425 — 8y
0
I agree with Undeniable, though unfortunately, I do not have enough reputation to up-vote. Just know that if I could, I most certainly would. antonio6643 426 — 8y
0
It's worth pointing out that 'i' for 'index' isn't a good variable name in this situation, because you're not using a list. Perci1 4988 — 8y
0
Index doesn't necessarily mean integer. An index can be anything. It could be the table itself. t={} t[t]=t print(t==t[t[t[t]][t]]) 1waffle1 2908 — 8y
0
Who downvoted me, we're about to fight. User#5978 25 — 8y
Ad
Log in to vote
0
Answered by 8 years ago

well, what I see happening is you are putting tables in arrays and the tables are something, idk your thing is hard to read. What I would do though is.

local array = {
    Hi = "Hello", -- hi is just a codename for Hello like print(array.Hi) would print out Hello
    Bye = "Good-Bye"
}

for i,v in pairs(array) do
    print(v)
end

Answer this question