Search code examples
luascripting

Splitting a String into two variables? LUA


So in a LUA driver I am writing I am constantly receiving RS232 strings eg; ZAA1, ZO64, D1 etc. etc. I am after a solution for finding where the string ends, and the Int starts and putting it into two different variables? I currently am using a while loop with a string.match method inside. is there a better way? Current Shortened code below;

s = "ZO29"
j = 1
while j <= 64 do
    if (s == string.format("ZO%d", j)) then
        print("Within ZO message")
        inputBuffer = ""
        sendACK()
        break
        
    elseif (s == string.format("ZC%d", j)) then
        inputBuffer = ""
        sendACK() 
        break
    end
    j = j + 1
end

Solution

  • Try this:

    a,b=s:match("(.-)(%d+)$")
    

    This captures the digits at the end of the string into b and the preceding text into a.