jsonstringfileluaset

How do I convert a string to a table in Lua?


I have a string like such: {a="foo", b="bar", c=12345} (imported & read from a file)

How do I convert this into a table/set with those contents? Or how can I save tables/sets in a file without having to use strings as a middleman?

I am using a program which uses Lua as its base, but doesn't easily let me use libraries (CC:Tweaked) so things like dkjson aren't a real option, and I cant find anything else to help me on here or in the documentation.

I am a beginner with Lua, so would greatly prefer something simple.


Solution

  • You can use the table interpreter within Lua to interpret your string using load (formerly known as loadstring):

    local s = [[{a="foo", b="bar", c=12345}]]
    local t = load("return "..s)()
    print(t.a) -- foo
    print(t.b) -- bar
    print(t.c) -- 12345
    

    This works as long as your table has the same syntax as a valid Lua table.