arraysstringlualua-table

How can I convert a String that is formatted like a table, into a table?


I did find a version of this for a string into a table that splits up the letters of the string, but I have a table, that I turn into a string to remove the first part of it, and now I want it back as a table so I can do a for loop through it to get the data inside.

This is the kind of table I'm talking about – the string currently looks something like this:

{
   Item1 = InstanceInput {
      Name = "Name",
      SourceOp = "SourceOp",
   },
   Item2 = InstanceInput {
      Name = "Name",
      SourceOp = "SourceOp",
   }
}

I'm scripting in Davinci Resolve, and I bet that relates to a small subset of you, but it has an operation to turn something into "userdata" and I tried that, but it returned it as nil.

I have tried to use the pretty.read() function. But I cannot use utils due to the way Davinci Resolve handles require.


Solution

  • If you have access to the load function you can turn the string into a table (assuming the string will always be valid Lua syntax)

    local importedTable = load("return " .. tableToImport:gsub("InstanceInput", ""))()
    
    print(importedTable["Item1"].Name) --> "Name"
    

    How it works is the string passed to load is compiled as a Lua function chunk, which you then can call like any other function which is why you prefix it with return so that when called it returns the Lua table.