4

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!

2 Answers 2

10

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
2
  • 3
    Technically, you should use assert(loadstring(eventData))() to propagate any syntax errors in the provided code (as opposed to just popping an unexplained "attempt to call a nil value" error). May 19, 2011 at 14:40
  • I see a serious security problem here, json and a suitable parser or similar method for lua-like syntax would be the right way to go.
    – dualed
    Aug 21, 2012 at 12:59
3

As of Lua 5.2, load supports strings as arguments. So you can now use Adam's answer above replacing loadstring with load.

Note that load(eventData) creates a chunk of type "function" and load(eventData)() creates a chunk and calls it—thereby creating your table. This had me tripped up for a little while.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.