Roblox 2009 Lua:获取 Loadstring 的错误

我已经制作了一个2009脚本构建器几个小时了,但我无法弄清如何打印出错误。如果我执行print(loadstring("a")),它会在 roblox 的输出中打印出nil [string "s"]:1: '=' expected near '<eof>',这个等于 nil。我想要得到的是它在结尾报告的错误: '=' expected near '<eof>',类型是 nil,所以我不知道怎么获取它。如果有人可以帮忙,那将不胜感激!

点赞
用户2616735
用户2616735

参考 Lua 5.1 手册,它会指向 load 的文档:

如果有错误,... 将返回 nil 和错误消息。

Lua 通常将错误消息作为第二个返回值返回:

local f, err = loadstring(mycode)
if not f then
    print("There was an error: `" .. err .. "`")
end

这个 err哪里 发生错误开始,并且对 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..."]:
2018-06-20 23:06:43