lua patterns - Lua parsing a table path string to a table -


i need parse string represents path of table, , turn actual table find value nested inside table structure:

local function strsplit(str, sep)     sep = sep or "%s";     local tbl = {};     local = 1;     str in string.gmatch(str, "([^"..sep.."]+)")         tbl[i] = str;         = + 1;     end     return tbl; end  local function parser(path, tbl)     local value;     local keys = strsplit(path, ".");      _, key in pairs(keys)         value = (value , value[key]) or tbl[key];     end     return value; end  local data = {     colors = {         r = 1, g = 1, b = 1     } }  local red = parser("colors.r", data); print(red); -- prints 1 (correct!) 

this code runs fine expected output. however, alter "parser" function works number index values , not strings keys (the index part of table, not hash table):

local data = {     list = {         50, 40, 30, 20, 10     } }  local value = parser("colors.list[2]", data); print(value); -- should print 40 

when splitting string representing table path, 1 of keys become "list[2]" , should converted real table. therefore, need sort of regex matching solution able identify square brackets , work it's magic; don't know started this.


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -