Search code examples
lualua-tablelua-5.2lua-5.1

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


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


Solution

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