This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
AlexDevs's profile picture

Convert string into more tables

Started by AlexDevs, 08 March 2017 - 08:31 PM
AlexDevs #1
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 = {} } }
.
KingofGamesYami #2
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.
FuzzyLitchi #3
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"