I am trying to make a function that would grab a select amount of letters from a string. If you don’t get what I mean, let’s say we have the word DINOSAUR. The function will generate a random number from 1 to 3. For example, let’s say it generated 2. Then, I want it to grab 2 letters from DINOSAUR, so it can only grab DI, IN, NO, OS, SA, AU, UR
I have tried splitting the string into a table, but I don’t know where to go from there.
If anyone could help, that would be great.
local function Split(String, Amount)
local Table = {}
for Sub=1, #String, Amount do
table.insert(Table, string.sub(String, Sub, Sub + 1))
end
return Table
end
print(Split("Dinosaur", math.random(1, 3)))
local function Split(String, Amount)
local Table = {}
for Sub=1, #String, 1 do
table.insert(Table, string.sub(String, Sub, Sub + (Amount - 1)))
end
return Table
end
print(Split("Dinosaur", 2))
No, but I managed to get what I wanted. If anyone needs the function here it is:
function generatePrompt()
local selected
local letters = math.random(1, 3)
repeat
selected = dic[math.random(#dic)] --dic is an array of words
until #selected > letters
selected = string.split(selected, "")
local start = math.random(1, (#selected - (letters - 1)))
local prompt = selected[start]
print(table.concat(selected, ""), letters, start)
if letters == 1 then
return prompt
end
for i = 1, letters - 1 do
prompt ..= selected[start + i]
end
return prompt
end
local str = "DINOSAUR"
local len = 2 -- length of piece to take from above string
local pos = math.random(#str - len + 1) -- picks a position in the string that isn't too far to the right. In this case, from 1 (position of D) to 7 (position of U), but not 8 (position of R, last letter)
local piece = string.sub(str, pos, pos + len - 1) -- extracts [len] consecutive letters from str, confident that pos+len-1 is within the length of the string
print(piece) -- DI, IN, NO, OS, SA, AU or UR, but not R or OSA or anything