请参阅 Lua 5.1 手册,该手册将指向 load 的文档:
如果有 [are] 错误,... 返回 nil 和错误消息。
Lua 通常会将错误消息作为第二个返回值返回:
local f, err = loadstring(mycode)
if not f then
print("There was an error: `" .. err .. "`")
end
err 以 where 错误发生的位置开头,这无助地引用了 loadstring 的输入。
例如输入代码"hello there",错误为
[string "hello there"]:1: '=' expected near 'there'
Lua 似乎在第一个换行符或 63 个字符处截断了引号,以较少者为准:
对于"hello\there",错误是
[string "hello..."]:2: '=' expected near 'there'
对于"helloooooooooooooooooooooooooooooooooooooooooooooooooooooo there",错误是
[string "helloooooooooooooooooooooooooooooooooooooooooooooooooooooo ther..."]:1: '=' expected near 'there'
如果您确定脚本的前 63 个字符/第一行中没有 "]:,您只需搜索该序列即可找到它停止的位置:
local location, message = err:match('^(%[string ".*"%]:%d+:%s+)(.*)$')
如果您的代码是 "hello\"]:1: there",这将是不正确的,您可能想要处理它。
解决此问题的最简单方法是将用户控制权从引用的第一行中移开:在代码前面加上您自己的第一行,这很好(并确保在显示时调整错误的行号它给用户:)
local f, err = loadstring("--code\n" .. mycode)
print(err)
现在错误消息应该总是开始
[string "--code..."]: