Set Variables And Tables With Function

lua-users home
wiki

Showing revision 2
Started with the setfield function from the book "Programming in Lua" chapter 14.1 page 120 here is my final result. For those not familiar with the book, would you please summarize the purpose of this function?

Instead of ensure only the existence of an already created table this function overwrites any given Table/Name - as expected I think.

   function setvar(Table,Name,Value)

-- Table (table, optional); default is _G
-- Name (string); name of the variable e.g. A.B.C ensures the table A and A.B and sets A.B.C to <Value>
--                single dots at the end inserts the value in the last position of the array e.g. A. ensures table A and sets A[table.getn(A)] to <Value>
--                multiple dots are interpreted as a string e.g. A..B. ensures the table A..B
-- Value (any)

      if type(Table)~='table' then
         Table,Name,Value = _G,Table,Name
      end

      local Concat,Key = false,''

      string.gsub(Name,'([^%.]+)(%.*)',function(Word,Delimiter)

                                          if Delimiter=='.' then
                                             if Concat then
                                                Word=Key..Word
                                                Concat,Key = false,''
                                             end
                                             if type(Table[Word])~='table' then
                                                Table[Word]={}
                                             end
                                             Table=Table[Word]
                                          else
                                             Key=Key..Word..Delimiter
                                             Concat=true
                                          end
      
                                       end)

      if Key=='' then
         table.insert(Table,Value)
      else
         Table[Key]=Value
      end

   end


-- the following lines are only for tests

   Test={}

   setvar(Test,'Index',1)
   setvar(Test,'Index.',22)
   setvar(Test,'Index.Index',333)

-- dump content of Test here

   setvar(Test,'Index.Index.',4444)
   setvar(Test,'Index.Index.',4444)
   setvar(Test,'Index..',55555)
   setvar(Test,'Index..Index',666666)
   setvar(Test,'Index..Index.',7777777)
   setvar(Test,'Index..Index..',88888888)

-- dump content of Test here

   setvar(Test,'.Index',999999999)

-- dump content of Test here

   setvar(Test,'',0)

-- dump content of Test and here


RecentChanges · preferences
edit · history · current revision
Edited July 22, 2004 2:43 pm GMT (diff)