Created
May 29, 2020 01:43
-
-
Save siasur/b65ea2d96592c8b84a4bd7cc2ddacce3 to your computer and use it in GitHub Desktop.
Lua Splice strings
This file contains 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
-- Copyright (c) 2020 Siasur | |
--[[ | |
This lua function allows you to splice a string (value) into another string (base) at a given location (position) without changing its length. | |
I created this function for a now scrapped project but as I spent a long time figuring out how to do it I decided to make it a public gist. | |
If you need this functionality in your script you are free to use this code as it is. | |
]] | |
local function --[[ String ]] spliceString( --[[ String ]] base, --[[ Number ]] position, --[[ String ]] value) | |
-- checkParam(base, "base", "string") | |
-- checkParam(position, "position", "number") | |
-- checkParam(value, "value", "string") | |
-- We do not want to get a substring from the end so let's fix it in case position was less that 1 | |
if position < 1 then | |
tmp = position * -1 + 2 | |
value = string.sub(value, tmp) | |
end | |
local end_front = math.max(position - 1, 0) | |
local start_back = math.max(position, 1) + #value | |
local value_end = clamp(#base - position + 1, 0, #value) | |
local front = string.sub(base, 0, end_front) | |
local back = string.sub(base, start_back) | |
value = string.sub(value, 0, value_end) | |
return string.format("%s%s%s", front, value, back) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment