Lua中的字符串到表 [英] String to Table in Lua

查看:352
本文介绍了Lua中的字符串到表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用LuaSocket和http.request调用一个远程PHP脚本,该脚本会生成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.

当我将http.request响应存储在变量中时,它是一个字符串,这使该表在我的Lua代码中不可用.

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

例如:

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',
}

例如,如果我尝试调用months [4],则会出现尝试索引全局'months'(nil值)"的错误. 如何将该字符串转换为可用表?

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?

谢谢!

推荐答案

您可以使用

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

这篇关于Lua中的字符串到表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆