MEDIUM: lua: Add `ifexist` parameter to `set_var`
As discussed in GitHub issue #624 Lua scripts should not use
variables that are never going to be read, because the memory
for variable names is never going to be freed.
Add an optional `ifexist` parameter to the `set_var` function
that allows a Lua developer to set variables that are going to
be ignored if the variable name was not used elsewhere before.
Usually this mean that there is no `var()` sample fetch for the
variable in question within the configuration.
diff --git a/src/hlua.c b/src/hlua.c
index 0ce57c7..f0d7e0f 100644
--- a/src/hlua.c
+++ b/src/hlua.c
@@ -3475,7 +3475,8 @@
size_t len;
struct sample smp;
- MAY_LJMP(check_args(L, 3, "set_var"));
+ if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
+ WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
/* It is useles to retrieve the stream, but this function
* runs only in a stream context.
@@ -3489,7 +3490,12 @@
/* Store the sample in a variable. */
smp_set_owner(&smp, s->be, s->sess, s, 0);
- lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
+
+ if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
+ lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
+ else
+ lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
+
return 1;
}
@@ -3953,7 +3959,8 @@
size_t len;
struct sample smp;
- MAY_LJMP(check_args(L, 3, "set_var"));
+ if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
+ WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
/* It is useles to retrieve the stream, but this function
* runs only in a stream context.
@@ -3967,7 +3974,12 @@
/* Store the sample in a variable. */
smp_set_owner(&smp, s->be, s->sess, s, 0);
- lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
+
+ if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
+ lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
+ else
+ lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
+
return 1;
}
@@ -5040,7 +5052,8 @@
size_t len;
struct sample smp;
- MAY_LJMP(check_args(L, 3, "set_var"));
+ if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
+ WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
/* It is useles to retrieve the stream, but this function
* runs only in a stream context.
@@ -5053,7 +5066,12 @@
/* Store the sample in a variable. */
smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
- lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
+
+ if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
+ lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
+ else
+ lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
+
return 1;
}