Fix up lua variable writing and reading for regex

This commit is contained in:
2025-03-24 20:49:39 +01:00
parent 1ff139ef15
commit 56ac0c7101
2 changed files with 12 additions and 11 deletions

View File

@@ -57,9 +57,6 @@ func (p *RegexProcessor) ToLua(L *lua.LState, data interface{}) error {
// Try to convert to number and set v1, v2, etc.
if val, err := strconv.ParseFloat(captures[i], 64); err == nil {
L.SetGlobal(fmt.Sprintf("v%d", i), lua.LNumber(val))
} else {
// For non-numeric values, set v to 0
L.SetGlobal(fmt.Sprintf("v%d", i), lua.LNumber(0))
}
}
@@ -80,15 +77,19 @@ func (p *RegexProcessor) FromLua(L *lua.LState) (interface{}, error) {
vLuaVal := L.GetGlobal(vVarName)
sLuaVal := L.GetGlobal(sVarName)
// First check string variables (s1, s2, etc.) as they should have priority
if sLuaVal.Type() != lua.LTNil {
// If our value is a number then it's very likely we want it to be a number
// And not a string
// If we do want it to be a string we will cast it into a string in lua
// wait that wouldn't work... Casting v to a string would not load it here
if vLuaVal.Type() == lua.LTNumber {
modifications[i] = vLuaVal.String()
continue
}
if sLuaVal.Type() == lua.LTString {
modifications[i] = sLuaVal.String()
continue
}
// Then check numeric variables (v1, v2, etc.)
if vLuaVal.Type() != lua.LTNil {
modifications[i] = vLuaVal.String()
}
}
return modifications, nil

View File

@@ -224,7 +224,7 @@ func TestMultipleMatches(t *testing.T) {
<name>Mary_modified</name>
</data>`
result, mods, matches, err = p.ProcessContent(content, `<name>([A-Za-z]+)</name>`, `s1 = s1 .. "_modified"`)
result, mods, matches, err = p.ProcessContent(content, `<name>([A-Za-z]+)</name>`, `s1 = s1 .. "_modified"`)
if err != nil {
t.Fatalf("Error processing content: %v", err)
@@ -457,7 +457,7 @@ func TestStringAndNumericOperations(t *testing.T) {
luaExpr := BuildLuaScript(tt.luaExpression)
// Process with our function
result, modCount, _, err := p.ProcessContent(tt.input, pattern, luaExpr)
result, modCount, _, err := p.ProcessContent(tt.input, pattern, luaExpr)
if err != nil {
t.Fatalf("Process function failed: %v", err)
}