Convert String to Tables

Asked

Viewed 166 times

2

local items = {}
local t = "7 2182, 4 2554, 5 9908"

I wanted to convert using this string and let the table come out like this:

local items = {{7,2182},{4,2554},{5,9908}}

is there any way? using gsub maybe?

1 answer

2


Try the code below:

local items = {}
local t = "7 2182, 4 2554, 5 9908"
local n = 0
for a,b in t:gmatch("(%d+)%s+(%d+)") do
        n = n + 1
        items[n] = {a,b}
end
for k,v in ipairs(items) do print(k,v[1],v[2]) end

The pattern in t:gmatch captures two sequences of digits separated by spaces.

  • Similar solution to http://stackoverflow.com/questions/42710798/convert-table-string-to-the-actual-table.

  • Also gives with gsub(): t:gsub(pattern, fn) (Anyway, I guess it doesn’t make much difference in size).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.