Jump to content




Convert string into more tables


2 replies to this topic

#1 AlexDevs

  • Members
  • 72 posts
  • Location~

Posted 08 March 2017 - 09:31 PM

I need to find a way to convert this string
"test/foo/bar"
into this table
test = { foo = { bar = {} } }
.

#2 KingofGamesYami

  • Members
  • 3,002 posts
  • LocationUnited States of America

Posted 08 March 2017 - 10:40 PM

You could do this with a simple pattern and the gmatch function. Try that and ask more specific questions if you get stuck.

#3 FuzzyLitchi

  • Members
  • 34 posts

Posted 09 March 2017 - 07:20 PM

function getTable(words)
  local newTable = {}
  
  if #words > 1 then
    newTable[words[1]] = getTable({unpack(words, 2, #words)})
  else
    newTable[words[1]] = {}
  end
  
  return newTable
end

function makeTable(string)
  local words = {}
  
  for w in (string .. "/"):gmatch("([^/]*)/") do table.insert(words, w) end

  return getTable(words)
end

assert(makeTable("test/foo/bar"), {test = { foo = { bar = {} } } })

This is almost what you asked for, though if you want to make a global variable named test, you can do so dynamically by doing the following

nameOfVariable = "test"

_G[nameOfVariable] = "value"

this is the same as
test = "value"






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users