'How to truncate text but backwards?

I want to achieve something like this: 1

I give function a string that should be trunctated and a maximum number of characters.

local function TruncateBackwards(str, maxChars)
  --Code
end

print(TruncateBackwards("this text should be truncated", 15)) -- ld be truncated
lua


Solution 1:[1]

You can use string.sub for this:

local function TruncateBackwards(str, maxChars) return str:sub(-maxChars) end
print(TruncateBackwards("this text should be truncated", 15)) -- ld be truncated

this also makes your own function, TruncateBackwards, pretty obsolete:

print(("this text should be truncated"):sub(-15)) -- ld be truncated

no index math is needed as Lua indices are one-indexed and string.sub supports negative indices relative to the end of the string.

Solution 2:[2]

With gsub() you can do this with the pattern: '..%s%w+%s%w+$'
...or with 15 Dots before the $: '...............$'
...or with 15 repetitions of a dot before the $: ('.'):rep(15) .. '$'

local txt, count = ("this text should be truncated"):gsub('..%s%w+%s%w+$', '')
print(txt)
-- That replaces the capture 'ld be truncated' with nothing
-- Output: this text shou
-- With match() and same pattern you can do the opposite
print(("this text should be truncated"):match('..%s%w+%s%w+$'))
-- Output: ld be truncated

See: https://www.lua.org/manual/5.1/manual.html#5.4.1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LMD
Solution 2