I’m writing an interpreter for my own programming language. I’m using string.gsub to replace a period with a parentheses based on spacing behind and before it.
This is my code:
print(v, string.match(v, " %."))
local gsub1 = string.gsub(v, " %.", "(")
values[#values + 1] = gsub1
values[#values] = string.gsub(v, "%. ", ")")
-
The print outputs this:

which confirms that the period exists.
-
gsub1 just doesn’t seem to work at all. (even when it’s not a variable it doesn’t work)
-
The second gsub works just fine.
Here’s the finished output:

I’ve been stuck on this for quite a while, so some help would be appreciated. Thanks!
It’s working for me, is it an issue with how you are implementing it in that table?
I’m not sure. Here’s the full code (this project’s gonna be open-source anyway so idc)
local module = {}
local values = {}
function module.Interpret(code)
code = code:split("%")
for i, v in ipairs(code) do
if i % 2 == 0 then
values[#values + 1] = '"' .. v .. '"'
code[i] = "↔remove╣"
elseif string.find(v, "local ") then
if i ~= 1 then
values[#values + 1] = "\n" .. string.sub(v, 2)
else
values[#values + 1] = v
end
code[i] = "↔remove╣"
else
local gsub1 = string.gsub(v, " %.", "(")
values[#values + 1] = gsub1
values[#values] = string.gsub(v, "%. ", ")")
end
end
code = nil
local nvalue = table.concat(values)
print(nvalue)
local r = loadstring(nvalue) -- yes ik this isn't running
end
return module
The text being fed in is this:
local yes is %hello world% local howdy is %howdy% print .yes, howdy.
local gsub1 = string.gsub(v, " %.", "(")
values[#values + 1] = gsub1
values[#values] = string.gsub(v, "%. ", ")")
That last line there is overwriting the line before it. Did you mean to make it +1 or -1 to the table index?
1 Like
No, I want it to gsub both periods. When I +1, it just creates 2 different print statements. I’m assuming I have to pass the whole string through a table or function then?
I’m not entirely sure what your point is with this bit of code since I didn’t fully read over your script. Do you want it to grab everything in between the parentheses too so that it’s just one value in the table?
I think so. Ideally I want it to go from
[5] = print .yes, howdy.
to
[5] = print(yes, howdy)
I was able to emulate this without string.gsub:
local toConcat = string.split(v, ".")
toConcat[1] = toConcat[1] .. "("
toConcat[3] = ")" .. toConcat[3]
values[#values + 1] = table.concat(toConcat)
However, this doesn’t solve the general problem.
Oh I see. I was overcomplicating things. I think you can just get away with this, no?
values[#values+1] = v:gsub(" %.", "("):gsub("%. ", ")")
1 Like