Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to Table in Lua

Tags:

lua

I am using LuaSocket and http.request to call a remote PHP script that generates a Lua table and outputs it to the browser.

When I store the http.request response in a variable it's a string, which renders the table unusable in my Lua code.

For example:

eventData = http.request("http://www.example.com/events.php")
print( eventData )

--print outputs this "string", that is really a Lua table that PHP generated
months={
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December',
}

If I try calling months[4], for example, it errors out with "attempt to index global 'months' (a nil value)". How can I cast that string as a usable table?

Thanks!

like image 386
Trae Avatar asked Dec 13 '22 20:12

Trae


1 Answers

You can use loadstring to create a lua chunk that you can execute.

eventData = [[
months = {
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December',
}
]]

loadstring(eventData)()
if months then
    print(table.concat(months, ", "))
end
like image 150
Adam Avatar answered Jan 17 '23 07:01

Adam