lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sun, May 20, 2012 at 6:48 PM, Maha Akkari <maha.akkari@gmail.com> wrote:
> hello,
> I have the following lua table :
>
>> t = {name="sandy", age="22", major="computerScience"}
>
> I want to iterate over it, both methods below do NOT work
>
> Method 1
>> function printAssociateTable(t)  print("before the loop")    for i,v
>> in ipairs(t) do
>>     print(v)    end end
>
>
> Method 2
>> function printAssociateTable2(t)  print("before the loop")    for k in
>> ipairs(t) do
>>     print("before the loop")
>>     print(k.. " is " ..t.k)    end end
>
>
> when I call either methods, they print "before the loop". so the problem the
> program is not entering the loop !
>
> i tried to manually access the table, if i do this :
>
>> return t.name
>  => gives sandy
>
>
>> return t[name]
>  =>  gives **nil**
>
>
>
>> return t["name"]
>   =>  gives sandy !
>
> how can i iterate over my table ? kindly note that both methods work well
> with a simple array like this
>
>> a={"a","b","c","d"}
>
> but i want it to work on my associative array

Long story short: Look up the difference between pairs() and ipairs().

/s/ Adam