lua

How to load multiline string with Lua load()?


In Lua script, I have a variable containing the string representation of a table. I want to load it into a table so that I can access each property. This works well unless the table contains a line break inside one of its elements. Working example:

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

If one of the strings contains a line break, it fails:

> 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)()
stdin:1: attempt to call a nil value
stack traceback:
    stdin:1: in main chunk
    [C]: in ?

Solution

  • Because \n will be interpreted as a line break, and this string will be interpreted as:

    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" }
    

    This is incorrect in syntax.

    If you want the value of message to include a line break, you should escape the backslash:

    message="line 1\\nline 2"