Search code examples
lua

Lua parsed output in one line


how do i get an output from something parsed into one line?

for example:

local input  = "56303031"
length = string.len(input)

for i = 1, length, 2 do 
  d = string.sub(input, i , i+1)
  a = string.char(tonumber(d, 16))
  print(a)
end

this prints out: enter image description here

But I want it to print it out like this: V001 -> in one line.

how can i do this?


Solution

  • print adds a linebreak. Use io.write instead.

    local input  = "56303031"
    local length = string.len(input)
    
    for i = 1, length, 2 do 
      local d = string.sub(input, i , i+1)
      local a = string.char(tonumber(d, 16))
      io.write(a)
    end
    

    Alternatively compose a string and print it at the end:

    local input  = "56303031"
    local length = string.len(input)
    local str = ""
    for i = 1, length, 2 do 
      local d = string.sub(input, i , i+1)
      local a = string.char(tonumber(d, 16))
      str = str .. a
    end
    print(a)
    

    Or you simply use gsub to modify the string befor printing:

    local input  = "56303031"
    print((input:gsub("%x%x", function (x) return string.char(tonumber(x, 16)) end)))
    

    This will replace each set of 2 hexadecimal characters in input by the character that number represents.