【问题标题】:Adding a column to an existing table in Lua向 Lua 中的现有表添加列
【发布时间】:2014-06-21 07:25:30
【问题描述】:

在 Lua 中,如何在如下表中插入新列?

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

我想在名称前放一列id,所以表格可能是这样的:

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:此表的数据来自如下文件:

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

我正在使用此代码将此数据插入到表中:

data = {}
text = file:read()
do
    function entry(entrydata)
        table.insert(data, entrydata)
    end
    thunk = load(text, nil, nil, {entry = entry})
    thunk()
end

【问题讨论】:

    标签: insert lua lua-table


    【解决方案1】:
    for i,v in ipairs(t) do
        v.id=i
    end
    

    或者,您可以在加载期间设置值:

    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
    

    【讨论】:

    • 哇!我认为它会比这更复杂,但它奏效了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 2013-02-11
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    相关资源
    最近更新 更多