在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
答案 0 :(得分:3)
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