You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Lua的load()加载包含多行字符串的表?

Lua加载含换行符的表字符串解决方案

问题根源:Lua字符串字面量不允许直接包含未转义的换行符,当load()解析包含\n的字符串时,该转义序列会被解析成实际换行,破坏Lua语法结构,导致load()返回nil,调用时触发错误。

解决方法1:转义换行符

生成表的字符串表示时,将字段内的换行符转义为\\n,确保load()能正确识别为字符串内的转义序列:

output = 'return { date="2024-10-23T21:24:27.227996696Z", severity="Normal", category="Hardware", message="line 1\\nline 2", filename="", status="Not Present", source="Atmos-RX-2" }'
event = load(output)()
print(event['message'])

解决方法2:使用Lua长字符串包裹特殊字段

Lua的长字符串([[...]])支持直接包含换行、引号等特殊字符,无需额外转义。将含换行的字段用长字符串标记替换普通引号:

-- 含转义换行的写法
output = 'return { date="2024-10-23T21:24:27.227996696Z", severity="Normal", category="Hardware", message=[[line 1\nline 2]], filename="", status="Not Present", source="Atmos-RX-2" }'

-- 含实际换行的写法
output = 'return { date="2024-10-23T21:24:27.227996696Z", severity="Normal", category="Hardware", message=[[line 1
line 2]], filename="", status="Not Present", source="Atmos-RX-2" }'

event = load(output)()
print(event['message'])

解决方法3:改用JSON序列化与反序列化(更安全)

若字符串来自外部不可信来源,直接解析Lua代码存在安全风险,推荐使用JSON格式处理。以dkjson库为例:

local dkjson = require('dkjson')

-- JSON格式的字符串
local json_str = '{"date":"2024-10-23T21:24:27.227996696Z","severity":"Normal","category":"Hardware","message":"line 1\\nline 2","filename":"","status":"Not Present","source":"Atmos-RX-2"}'

-- 解析为Lua表
local event = dkjson.decode(json_str)
print(event.message)

内容的提问来源于stack exchange,提问作者Elliott B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 02:37:38