Search code examples
luavertical-alignment

Lua add a variable amount of characters to String


I want to add an amount characters to a print, that equals space.

if #input >= 1 then
  for var=1, #input, 1 do
    [...]
    av = "was sent"

    else
      av = "doesn't exist"
    end

    space = 20-string.len(input[var])
    print(var..". '"..input[var].."' "..space..av)
  end
return
end

my goal is to align av vertically. input[var]varies in length.


Solution

  • Assuming you know that 20 is a maximum length of input[var] as your snippet implies, you can directly proceed to padding.

    The straightforward solution would be to use string.rep:

    print(var..". '"..input[var].."' ".. (" "):rep(space)..av)
    

    string.format also allows adding padding left and right; using -x you can add left padding:

    print(("%s. %-22s %s"):format(var, "'" .. input[var] .. "'", av))
    

    Note that I've bumped the padding to 22 since the two single quotes are now included in the calculation.


    How not to do it:

    Bad: Quadratic runtime, many garbage strings, more complex / longer code
    local padding = ""
    for i = 1, space do padding = padding .. " " end
    
    Bad: More overhead, garbage table, more complex / longer code
    local t = {}
    for i = 1, space do t[i] = " " end
    local padding = table.concat(t)
    

    Side note: If input[var] is guaranteed to be a string, you can use #input[var] instead of string.len(input[var]).