Skip to content

Instantly share code, notes, and snippets.

@sofish
Created August 24, 2020 06:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sofish/19cce9f29a58584f389198edc39d332b to your computer and use it in GitHub Desktop.
Save sofish/19cce9f29a58584f389198edc39d332b to your computer and use it in GitHub Desktop.
read str and parse it as table
function s2t(str)
local t = {}
local l = string.len(str)
local key = ''
local val = ''
local oe = 0
for i = 1, l do
local s = string.sub(str, i, i)
if s ~= ' ' then
if oe % 2 ~= 1 then
key = key..s
else
val = val..s
end
end
if s == ' ' or i == l then
oe = oe + 1
if oe % 2 == 0 then
t[key] = val
key = ''
val = ''
end
end
end
return t
end
local str = 'world000 -2000 he-llo-0 1'
print(s2t(str)) -- { ["he-llo-0"] = 1, ["world000"] = -2000, }
@sofish
Copy link
Author

sofish commented Aug 24, 2020

-- dump lua table
function dump(o)
   if type(o) == 'table' then
      local s = '{ '
      for k,v in pairs(o) do
         if type(k) ~= 'number' then k = '"'..k..'"' end
         s = s .. '['..k..'] = ' .. dump(v) .. ','
      end
      return s .. '} '
   else
      return tostring(o)
   end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment