0

嗨,我需要在 lua 中创建一个表,每个条目(记录)都可以用唯一的 id 表示

table[p1d2].seq={0,1,2,3} table[p1d2].days={'sun','mon','wed'}
table[p2d2].seq={0,1,2,3,4} table[p2d2].days={'fri','sat','tue'}

print(table.concat(table[p1d2].seq))==> 0123

像这样我想插入和访问请帮助我解决这个谜语

4

2 回答 2

0

我不确定你的要求是什么,因为 Lua 中的表本身就处理字符串索引,例如以下代码段:

tab = {};
tab['one']=1;
print(tab['one']);

打印1...如果这不是您要问的,您能否尝试更准确地解释您想要的行为?

如果这是你的问题,那么这样的代码应该可以工作(我定义了一个Thing类,因为我看到你似乎使用了一个带有seqdays字段的类,但我猜你的代码中已经有了类似的东西,所以我只离开了仅供参考)。

-- class definition
Thing = {seq = {}, days ={}}

function Thing:new (o)
  o = o or {}
  setmetatable(o, self)
  self.__index = self
  return o
end

-- definition of the table and IDs

tab={}
p1d2='p1d2'
p2d2='p2d2'

-- this corresponds to the code you gave in your question

tab[p1d2]=Thing:new()
tab[p2d2]=Thing:new()
tab[p1d2].seq={0,1,2,3}
tab[p1d2].days={'sun','mon','wed'}
tab[p2d2].seq={0,1,2,3,4}
tab[p2d2].days={'fri','sat','tue'}

print(table.concat(tab[p1d2].seq))
-- prints '0123'
于 2021-01-06T13:12:33.777 回答
0

如果您想创建具有唯一 id 的表条目,为什么不简单地使用数字表键?

local list = {}

table.insert(list, {seq={0,1,2,3}, days={"sun", "mon", "wed"}})
table.insert(list, {seq={0,1,2,3,4}, days= {'fri','sat','tue'}})

这样,添加的每个条目都将自动具有唯一的 id,而无需生成一个。然后,您可以稍后使用该索引来处理该条目。

如果这不是您所要求的,您应该提供更多详细信息和示例

于 2021-01-06T15:46:34.317 回答