Reputation: 667
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!
Upvotes: 5
Views: 11121
Reputation: 1403
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.
Upvotes: 4
Reputation: 3103
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
Upvotes: 11