Skip to content

Instantly share code, notes, and snippets.

@justnom
Created March 27, 2014 19:34
Show Gist options
  • Save justnom/9816256 to your computer and use it in GitHub Desktop.
Save justnom/9816256 to your computer and use it in GitHub Desktop.
Lua table to string
-- Convert a lua table into a lua syntactically correct string
function table_to_string(tbl)
local result = "{"
for k, v in pairs(tbl) do
-- Check the key type (ignore any numerical keys - assume its an array)
if type(k) == "string" then
result = result.."[\""..k.."\"]".."="
end
-- Check the value type
if type(v) == "table" then
result = result..table_to_string(v)
elseif type(v) == "boolean" then
result = result..tostring(v)
else
result = result.."\""..v.."\""
end
result = result..","
end
-- Remove leading commas from the result
if result ~= "" then
result = result:sub(1, result:len()-1)
end
return result.."}"
end
@Deltaspace0
Copy link

line 21: better if result ~= "{" then ...

@Sajgon
Copy link

Sajgon commented Nov 7, 2020

And how to do string to table? Do you have an example of that?

@Torte446
Copy link

And how to do string to table? Do you have an example of that?

You could use a split function like:

function split(inputstr, sep)
        if sep == nil then
                sep = "%s"
        end
        local t={}
        for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
                table.insert(t, str)
        end
        return t
end

@borsuczyna
Copy link

borsuczyna commented Jun 5, 2022

And how to do string to table? Do you have an example of that?

local your_table = loadstring("return " .. code)()

but make sure you are not loading user changed code

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