質問

In Lua, how do I insert a new column on a table like the one below?

table t = {
{name = "John", age = 19, sex = "M"},
{name = "Susan", age = 20, sex = "F"},
{name = "Paul", age = 18, sex = "M"}
}

I want to put a column id before the name, so the table could be like this:

table t = {
{id = 1, name = "John", age = 19, sex = "M"},
{id = 2, name = "Susan", age = 20, sex = "F"},
{id = 3, name = "Paul", age = 18, sex = "M"}
}

PS: the data of this table is coming from a file like the one below:

entry {name = "John", age = 19, sex = "M"}
entry {name = "Susan", age = 20, sex = "F"}
entry {name = "Paul", age = 18, sex = "M"}

and I'm using this code to insert this data into the table:

data = {}
text = file:read()
do
    function entry(entrydata)
        table.insert(data, entrydata)
    end
    thunk = load(text, nil, nil, {entry = entry})
    thunk()
end
役に立ちましたか?

解決

for i,v in ipairs(t) do
    v.id=i
end

Alternately, you could set the value during loading:

data = {}
text = file:read()
do
    local index=1
    function entry(entrydata)
        entrydata.id=index
        index=index+1
        table.insert(data, entrydata)
    end
    thunk = load(text, nil, nil, {entry = entry})
    thunk()
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top