Page 1 of 1

lua gsub madness (Help pls)

Posted: Thu Apr 18, 2019 7:29 pm
by ownlyme
I'm making an ingame code editor, but i'm not very good at using string.gsub
Here is my problem:

Code: Select all

	--numbers
		result = string.gsub(result,"%f[%d%a]%d+%f[%c%p%s]","[color=255,128,0]%1[/color]")
	--strings
		result = string.gsub(result,"\"[%a%d%s%p]+\"","[color=64,64,64]%1[/color]")
returns:
Screenshot_2.png
Screenshot_2.png (1.92 KiB) Viewed 1082 times
that the number inside quotes is colored is not so critical, but i could really use some help with the quotation bug

edit: i'm now using this piece of madness:

Code: Select all

		abc983=-1
		result = string.gsub(result,"\"",function(input) 
			abc983=abc983+1
			if abc983%2==0 then
				return "quotationopen_"..math.floor(abc983/2).."_983"
			else
				return "quotationclose_"..math.floor(abc983/2).."_983"
			end 
			end)
		for i=0, abc983/2 do
			result = string.gsub(result,"quotationopen_"..i.."_983[%a%d%s%p]+quotationclose_"..i.."_983","[color=64,64,64]%1[/color]")
			result = string.gsub(result,"quotationopen_"..i.."_983","\"")
			result = string.gsub(result,"quotationclose_"..i.."_983","\"")
		end

Re: lua gsub madness (Help pls)

Posted: Thu Apr 18, 2019 9:07 pm
by eduran
I have absolutely no idea what you are trying to achieve. What is your input and desired output?

Re: lua gsub madness (Help pls)

Posted: Thu Apr 18, 2019 10:28 pm
by ownlyme
code highlighting
input:
input.png
input.png (34.88 KiB) Viewed 1062 times
output:
output.png
output.png (41.35 KiB) Viewed 1062 times

Re: lua gsub madness (Help pls)

Posted: Fri Apr 19, 2019 5:49 am
by eduran
Either use single quotes to start and end your pattern strings and include double quotes directly. Or escape the double quotes with \" .
This

Code: Select all

local code_block = [[
  local string_1, string_2 = "Hello World!", "foo"
  local number = 123
  local function foo(arg)
    return tostring(arg) .. "\n"
  end
]]

print(string.gsub(code_block, '".-"', '[color=64,64,64]%1[/color]'))  -- single quotes around double quotes
print(string.gsub(code_block, "\".-\"", '[color=64,64,64]%1[/color]'))  -- escaped double quotes
prints

Code: Select all

local string_1, string_2 = [color=64,64,64]"Hello World!"[/color], [color=64,64,64]"foo"[/color]
local number = 123
local function foo(arg)
  return tostring(arg) .. [color=64,64,64]"\n"[/color]
end

Re: lua gsub madness (Help pls)

Posted: Fri Apr 19, 2019 10:31 am
by ownlyme
thank you, it works!
your solution is way more elegant and also helps me understand the gsub thing better