Reputation: 83
Hi I need to create a table in lua with each entry(record) can be represented by unique 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
like that i want to insert and access please help me in solving this riddle
Upvotes: 0
Views: 1409
Reputation: 86
I'm not sure to understand what you're asking for, since tables in Lua natively handle string indexes, for example the following snippet:
tab = {};
tab['one']=1;
print(tab['one']);
prints 1
...if that is not what you're asking, could you please try to explain more precisely what behavior you want?
And if that was your question, a code like this one should work (I defined a Thing
class since I see you seem to use a class with seq
and days
fields, but I guess you already have something of the kind in your code, so I only left it for informational purposes).
-- 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'
Upvotes: 0
Reputation: 28950
If you want to create table entries with a unique id why not simply use numeric table keys?
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'}})
That way each entry added will have a unique id automatically without having to generate one. You can then use that index to address the entry later.
If that is not what you're asking for you should provide more detail and examples
Upvotes: 0