how to get the field names for a table

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

how to get the field names for a table

Honglei Tu
Hello,
Thank you for the answer of previous question.
LHF.
Another one:
If I have a Lua table which is
color["red" = 1 "green" =5 "blue" =6].
I wonder how to get the field names and put them
in a set. I want to get ["red" "green" "blue"].
I will write a Lua function to get them.
But is there any way to do that ?

Thank you
Honglei

Reply | Threaded
Open this post in threaded view
|

RE: how to get the field names for a table

Ashley Fryer-2
Here's one way to do what you want.

Regards,
ashley

----

function get_field_names(t)
    local names = {}
    local i,v=next(t,nil)
    while i do
        tinsert(names,i)
        i,v=next(t,i)
    end
    return names
end


>color = { red = 1, green = 5, blue = 6 }

>names = get_field_names( color )

>print(names[1],names[2],names[3])

green   red     blue


> -----Original Message-----
> From: Honglei Tu
> Sent: Tuesday, March 06, 2001 3:47 PM
> Subject: how to get the field names for a table
> 

> If I have a Lua table which is
> color["red" = 1 "green" =5 "blue" =6].
> I wonder how to get the field names and put them
> in a set. I want to get ["red" "green" "blue"].
> I will write a Lua function to get them.
> But is there any way to do that ?
> 



Reply | Threaded
Open this post in threaded view
|

Re: how to get the field names for a table

Jean-Claude Wippler
In reply to this post by Honglei Tu
Honglei Tu <[hidden email]> wrote:

>Another one:
>If I have a Lua table which is
>color["red" = 1 "green" =5 "blue" =6].
>I wonder how to get the field names and put them
>in a set. I want to get ["red" "green" "blue"].
>I will write a Lua function to get them.
>But is there any way to do that ?

There are no sets in Lua, is the following what you want?

    color={red=1,green=5,blue=6}
    s={}
    for k,v in color do tinsert(s,k) end
    print(s[1],s[2],s[3])

-jcw