Lua - how to initialize a table with a row

I have the following line:

 mystring = "a=test;b=12345"

I would like to know how to initialize a table with one shot, assign it a row value. The string is taken from another external application, and if possible, I want to avoid splitting it. Something like that:

  mytable = {mystring:gsub(";",",")}

Is it possible to do something like this? I know how to do this in a few steps ... but just wondering if it's possible to do it all at once.

Here is what I tried and the corresponding output:

> mystring = "a=123;b=2345"
> myarray = {mystring:gsub(";",",")}
> for key,value in pairs(myarray) do print(key,value) end
1   a=123,b=2345
2   1
> 

whereas I was hoping to get an array / table, for example:

key   value
a       123
b       2345
+4
source share
3 answers
mytable = {}
for key, value in string.gmatch("a=123;b=456", "(%w+)=(%w+)") do
    mytable[key] = value
end

print(mytable.a, mytable.b)

Returns:
123
456

as was expected. This works, of course, only in alphanumeric and without punctuation.

+2
source

, Lua :

function parse(s)
    local t={}
    load(s,"",nil,t)()
    return t
end

mytable=parse("a=123;b=2345")
for k,v in pairs(mytable) do print(k,v) end

, , , . , , . .

+5
-- Lua 5.2+ required
function string_to_table (str)
   local result = {}
   load(str, '', 't', setmetatable({}, {
      __index = function(t,k) return k end,
      __newindex = result
   }))()
   return result
end

mytable = string_to_table("a=test;b=12345;c=a")  -- {a="test", b=12345, c="a"}
+5
source

All Articles