-2

I have been trying to convert a string into a table for example:

local stringtable = "{{"user123","Banned for cheating"},{"user124","Banned for making alt accounts"}}"

Code:

local table = "{{"user123","Banned for cheating"},{"user124","Banned for making alt accounts"}}"

print(table[1])

Output result:

Line 3: nil

Is there any sort of method of converting a string into a table? If so, let me know.

Lavacat
  • 11
  • 4

1 Answers1

1

First of all, your Lua code will not work. You cannot have unescaped double quotes in a string delimited by double quotes. Use single quotes(') within a "-string, " within '...' or use heredoc syntax to be able to use both types of quotes, as shall I in the example below.

Secondly, your task cannot be solved with a regular expression, unless your table structure is very rigid; and even then Lua patterns will not be enough: you will need to use Perl-compatible regular expressions from Lua lrexlib library.

Thirdly, fortunately, Lua has a Lua interpreter available at runtime: the function loadstring. It returns a function that executes Lua code in its argument string. You just need to prepend return to your table code and call the returned function.

The code:

local stringtable = [===[
{{"user123","Banned for cheating"},{"user124","Banned for making alt accounts"}}
]===]

local tbl_func = loadstring ('return ' .. stringtable)
-- If stringtable is not valid Lua code, tbl_func will be nil:
local tbl = tbl_func and tbl_func() or nil

-- Test:
if tbl then
    for _, user in ipairs (tbl) do
        print (user[1] .. ': ' .. user[2])
    end
else
    print 'Could not compile stringtable'
end
Alexander Mashin
  • 3,892
  • 1
  • 9
  • 15