Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lua - how to initialize a table using a string

Tags:

lua

I have the following string:

 mystring = "a=test;b=12345"

I would like to know how to initialize a table in one shot, assign it the value of the string. The string originates from another external application, and if possible I want to avoid having to split it up. Something like this:

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

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

Here's what I've tried and the respective 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 end up with an array / table where like this:

key   value
a       123
b       2345
like image 626
Happydevdays Avatar asked Dec 14 '22 07:12

Happydevdays


2 Answers

-- 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"}
like image 119
Egor Skriptunoff Avatar answered Jan 14 '23 01:01

Egor Skriptunoff


Try this, which lets Lua do the hard work:

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

Note that this executes the code in the given string, which may be dangerous if it comes from an untrusted source. On the other hand, the damage is limited because the code is executed in an empty environment and so cannot affect existing variables. Malicious code may contain infinite loops or consume all memory, though.

like image 25
lhf Avatar answered Jan 14 '23 00:01

lhf