【问题标题】:Roblox 2009 Lua: Get Loadstring's errorRoblox 2009 Lua:获取 Loadstring 的错误
【发布时间】:2018-11-30 03:32:29
【问题描述】:

我已经制作 2009 年的脚本生成器几个小时了,但我不知道如何让它打印错误。如果我这样做 print(loadstring("a")) 它会打印到 roblox 输出 nil [string "s"]:1: '=' expected near '<eof>',这 == nil。我想得到的是它最后报告的错误: '=' expected near '<eof>',类型类型为nil,所以我不知道如何得到它。如果有人可以提供帮助,将不胜感激!

【问题讨论】:

    标签: lua roblox


    【解决方案1】:

    请参阅 Lua 5.1 手册,该手册将指向 load 的文档:

    如果有 [are] 错误,... 返回 nil 和错误消息。

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

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

    errwhere 错误发生的位置开头,这无助地引用了 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..."]:
    

    【讨论】:

    • OP 可能想要err:match(": (.*)")
    • 他们说“type is nil”,所以看起来他们不知道第二个返回值。但是,是的,我会做一些关于处理错误的广告
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 2015-08-19
    • 1970-01-01
    • 2023-02-02
    • 2018-12-29
    • 2022-10-20
    • 2020-07-02
    相关资源
    最近更新 更多