【问题标题】:How would I convert a string into a table?如何将字符串转换为表格?
【发布时间】:2021-04-06 00:28:51
【问题描述】:

我一直在尝试将字符串转换为表格,例如:

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

代码:

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

print(table[1])

输出结果:

Line 3: nil

有什么方法可以将字符串转换为表格吗?如果有,请告诉我。

【问题讨论】:

标签: lua lua-table


【解决方案1】:

首先,您的 Lua 代码将不起作用。您不能在由双引号分隔的字符串中包含未转义的双引号。在"-string 中使用单引号('),在'...' 中使用" 或使用heredoc 语法来使用这两种类型的引号,如下例所示。

其次,你的任务不能用正则表达式来解决,除非你的表结构很死板;即使这样,Lua 模式也不够:您需要使用 Lua lrexlib 库中与 Perl 兼容的正则表达式。

第三,幸运的是,Lua 有一个运行时可用的 Lua 解释器:函数loadstring。它返回一个在其参数字符串中执行 Lua 代码的函数。您只需在表格代码前加上return 并调用返回的函数。

代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多