Fix up lua variable writing and reading for regex

This commit is contained in:
2025-03-24 20:49:39 +01:00
parent fd81861a64
commit 0f7ee521ac
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. // Try to convert to number and set v1, v2, etc.
if val, err := strconv.ParseFloat(captures[i], 64); err == nil { if val, err := strconv.ParseFloat(captures[i], 64); err == nil {
L.SetGlobal(fmt.Sprintf("v%d", i), lua.LNumber(val)) 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) vLuaVal := L.GetGlobal(vVarName)
sLuaVal := L.GetGlobal(sVarName) sLuaVal := L.GetGlobal(sVarName)
// First check string variables (s1, s2, etc.) as they should have priority // If our value is a number then it's very likely we want it to be a number
if sLuaVal.Type() != lua.LTNil { // 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() modifications[i] = sLuaVal.String()
continue
} }
// Then check numeric variables (v1, v2, etc.)
if vLuaVal.Type() != lua.LTNil {
modifications[i] = vLuaVal.String()
}
} }
return modifications, nil return modifications, nil

View File

@@ -224,7 +224,7 @@ func TestMultipleMatches(t *testing.T) {
<name>Mary_modified</name> <name>Mary_modified</name>
</data>` </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 { if err != nil {
t.Fatalf("Error processing content: %v", err) t.Fatalf("Error processing content: %v", err)
@@ -457,7 +457,7 @@ func TestStringAndNumericOperations(t *testing.T) {
luaExpr := BuildLuaScript(tt.luaExpression) luaExpr := BuildLuaScript(tt.luaExpression)
// Process with our function // 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 { if err != nil {
t.Fatalf("Process function failed: %v", err) t.Fatalf("Process function failed: %v", err)
} }