Subdiving string doesnt work

hii soo i current have a string called line and this line contains () and inside the parentheses theres words, now the code does replace the references by their value however when its example str…ju itll count that as one word any soultion to that?

local words2 = {}
		local line2 = modifiedLine
		line2 = modifiedLine:gsub("(%b())", function(content)
			local wordInsideParentheses = content:sub(2, -2) 
			local reference = references[wordInsideParentheses]
			if reference then
				return "(" .. reference.value .. ")"
			else
				return content
			end
		end)
1 Like

A viable option is to run gsub() on the content. %w+ is for alphanumerics, but you can always define another pattern.

local references = {x = 10, y = 20}

local line = "coordinates: (x, y, z)"
local modified = line:gsub("%b()", function(content)	
	
	content = content:sub(2, -2):gsub("%w+", function(word)
		return references[word] or word
	end)
	return "("..content..")"
end)
print(modified) --> coordinates: (10, 20, z)
1 Like

it did kinda work however is there any way of making so it scans the whole line after references and not just inside the parentheses?, string functions arent my specialities

Could you please elaborate on what you’re trying to do? The original question was about only replacing values in parenthesis, so I’m not entirely sure what the goal is exactly. An actual example would be really helpful, e.g. value a, value (b)value 1, value 2.

local references = {x0 = 10, y0 = 20, y1 = 40}

local line = "point 1: x0, y0; point 2: (x1, y1)"
local modified = line:gsub("%w+", function(content)
	if references[content] then
		return references[content]
	else
		return content
	end
end)
print(modified) --> point 1: 10, 20; point 2: (x1, 40)

Or should it be something like value a, value (b), value cvalue a, value (2), value 3 with only b and c being evaluated and a ignored?

Update.

You’re welcome! Just in case you or anyone seeing this needed a solution for the other option where only references inside the first parenthesis and after are replaced, I’m adding it as well.

Code
local references = {a = 1, b = 2, c = 3, d = 4}

local line = "value a, value (b, c), value d"

local i, j = string.find(line, "%b().*")
if not i then
	warn("No parenthesis () found")
end

local subLine = string.sub(line, i)

subLine = subLine:gsub("%w+", function(content)
	return references[content] or content
end)
local modified = line:sub(1, i -1) .. subLine

print(modified) --> value a, value (2, 3), value 4

Yeah something like this thank you!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.