簡體   English   中英

如何創建具有唯一 ID 的表條目並使用該 ID 訪問它們..?

[英]How to create table entries with unique id and access them using that id..?

嗨,我需要在 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

像這樣我想插入和訪問請幫助我解決這個謎語

我不確定您的要求是什么,因為 Lua 中的表本身就可以處理字符串索引,例如以下代碼段:

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

打印1 ...如果這不是您要問的,您能否嘗試更准確地解釋您想要的行為?

如果這是您的問題,那么這樣的代碼應該可以工作(我定義了一個Thing class 因為我看到您似乎使用了帶有seqdays字段的 class ,但我猜您的代碼中已經有了類似的東西,所以我只留下它以供參考)。

-- 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'

如果您想創建具有唯一 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,而無需生成一個。 然后,您可以稍后使用該索引來處理該條目。

如果這不是您所要求的,您應該提供更多詳細信息和示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM