Last active
April 19, 2019 13:17
-
-
Save Srlion/7e416e3cb67fc06a4b7e78b17400f84e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| --[[ | |
| local str = "Hi" | |
| print(ChangeLine(str, "OwO", 1)) -- output: OwO | |
| print(ChangeLine(str, " Srlion!", 1, true)) -- output: Hi Srlion! | |
| print(ChangeLine(str, "Srlion ", 1, false)) -- output: Srlion Hi | |
| ]] | |
| -- Localize functions so accessing them becomes more faster | |
| local sub = string.sub | |
| local rep = string.rep | |
| local find = string.find | |
| local function ChangeLine(str, new_str, line, pos) | |
| local len, st, en | |
| len, st, en = str.length, 0, 0 | |
| for i = 1, line do | |
| -- try to find next new line | |
| en = find(str, "\n", en + 1, true) | |
| if (!en) then | |
| if (line == i) then | |
| st = len - 1 | |
| else | |
| -- if we didn't reach the line we need to change then we have to add new lines till we reach the one we need to change | |
| str = str .. (rep("\n", line - i)) | |
| st = len + line - i | |
| end | |
| en = st + 2 | |
| break | |
| end | |
| if (i != line) then | |
| st = en | |
| end | |
| end | |
| -- if pos is true then we will add the new string to the old one | |
| if (pos == true) then | |
| new_str = sub(str, st + 1, en - 1) .. new_str | |
| -- if pos is false then we will add the new string before the old one | |
| elseif (pos == false) then | |
| new_str = new_str .. (sub(str, st + 1, en - 1)) | |
| end | |
| return sub(str, 1, st) .. new_str .. sub(str, en, len) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment