luaroblox

Roblox 2009 Lua: Get Loadstring's error


I've been making a 2009 script builder for a few hours now, and I can't figure out how to make it print errors. If I do print(loadstring("a")) it prints into the roblox output nil [string "s"]:1: '=' expected near '<eof>', which == nil. What I want to get is the error it reports at the end : '=' expected near '<eof>', type type is nil, so I have no idea how to get it. If anyone could help that would be greatly appreciated!


Solution

  • Refer to the Lua 5.1 manual, which will point you to the documentation for load:

    If there [are] errors, ... returns nil plus the error message.

    It's typical for Lua to return error messages as a second return value:

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

    This err begins with where the error happened, which unhelpfully quotes the input to loadstring.

    For example, for the input code "hello there", the error is

    [string "hello there"]:1: '=' expected near 'there'
    

    Lua appears to cut the quote off at the first newline or 63 character, whichever is less:

    For "hello\there" the error is

    [string "hello..."]:2: '=' expected near 'there'
    

    For "helloooooooooooooooooooooooooooooooooooooooooooooooooooooo there" the error is

    [string "helloooooooooooooooooooooooooooooooooooooooooooooooooooooo ther..."]:1: '=' expected near 'there'
    

    If you're sure there's no "]: in the first 63 characters/first line of your script, you can just search for that sequence to find where it stops:

    local location, message = err:match('^(%[string ".*"%]:%d+:%s+)(.*)$')
    

    This won't be right if your code is, for example, "hello\"]:1: there", which you may want to address.

    The simplest way to address it would be to take user control away from the first line that is quoted: prepend the code with your own first line that is nice (and make sure to adjust the line number of the error if you display it to the user:)

    local f, err = loadstring("--code\n" .. mycode)
    print(err)
    

    Now the error message should always begin

    [string "--code..."]: