I am requesting a feature for the LuaU compiler, specifically under the string functions category.
In many programming languages, like Python, there is a string function to delete a character from a string, and then return the item it removed in the string
Why:
Removing items from a string is more complicated than it should be. Sure, it is easy, but in any programming language (like Python), it is built in, and is much more understandable and easy to read.
Fictional example:
local myString = "Hello world."
local pop = string.pop(myString, 7)
print(string)
print(pop)
The output would be:
Hello orld.
w
Use cases:
A text shuffler. You could take every character in a string and shuffle it.
A custom text-box system
Undoing items from strings… and more!
There could be MANY use cases for string.pop(), and although the idea is niche, it is a very common programming fundamental.
Strings are immutable, and that will never change. That makes this feature impractical to implement, at least in the same way you proposed. A better solution would be to keep strings immutable!
-- Proposal (non-functioning code)
local myString = "Hello world."
local newString, popped = string.pop(myString, 7)
print(newString) --> Hello orld.
print(popped) --> w
I dislike how some programming languages, like Python, have a million features built into every single class. Luau is supposed to be simplistic. Unlike Python or other high-level languages, Lua and Luau are meant to be extremely portable (their file sizes are grains of sand compared to Python). They don’t have many keywords, and the built-in libraries are concise and serve a purpose.
Popping elements from strings isn’t very common. It’s also simple enough to implement:
local foo = "foo"
local popIndex = 2
local popped = foo:sub(0, popIndex) .. foo:sub(popIndex + 1)
And, I don’t think many people “pop” from strings enough to warrant a whole built-in that goes against consistency with immutable strings. Consider this a point for bad practices? I’d think that it’s best left for the developers to implement themselves.
I think its better rather to make it a custom method instead of a built-in one, like @VegetationBush mentioned, my code is probably not optimised though:
function pop(str : string, index : number) : (string, string)
assert(typeof(str) == "string", "Provided datatype is not a string")
local len = #str
assert(index >= 1 and index <= len, "Index out of bounds")
local popped = string.sub(str, index, index)
local remaining = str:sub(1, index - 1) .. str:sub(index + 1)
return popped, remaining
end
Can you even pop strings in python? I thought that was for lists only since strings are immutable. You can already achieve similar behavior with table.remove.