With string.pack how would I make it so the data pads zeros until given offset?
I’ve tried ![n] and Xop, they didnt seem to work but I am likely using them wrong.
With string.pack how would I make it so the data pads zeros until given offset?
I’ve tried ![n] and Xop, they didnt seem to work but I am likely using them wrong.
Give this a try
function Padding(_string, offset, character)
return string.rep( character or " ", offset - #_string) .. _string
end
print(Padding("Hello World!", 20, "-") --> --------Hello World!
This function would add whatever character to the the string if the offset is larger then the string. Aka id the string is 12 chars long and the offset is 20, then it should add 8 characters to the left side of the string. You can try passing number into it, but if it doesn’t work, you can just tostring it then pass it into the function
This isn’t really what I wanted. I was looking for a string.pack option I can add to my pattern to have it pad until given position.
oh mb I really didnt understood what you ment about in the post
print(Padding(“Hello World!”, 20, “-”) → --------Hello World!
I expected the output to not have any spaces, but the actual output is it has spaces.
The problem is this line:
return string.rep( character or " ", offset - #_string) … _string
If the offset
is bigger than the length of _string
, then you end up with offset - #_string
spaces in front of the string.
Instead you should write:
return _string … string.rep( character or " ", offset - #_string)
I didn’t need a string padding function, I needed a string pattern for string.pack that will pad the output until given position.