slang-users mailing list

[2022 Date Index] [2022 Thread Index] [Other years]
[Thread Prev] [Thread Next]      [Date Prev] [Date Next]

[slang-users] Surprising behavior of array_swap


Hi,

I was struck by a wired behavior of 'array_swap' (I think). Given an array and two different indices the function does what it claims to do: swapping the entries and return nothing. However, given the same indices, i.e., 'array_swap(a, 0,0)' does not change the array (as expected), but also leaves the array on the stack.

   variable a = [1,2,3];
   array_swap(a, 0,1);

   print(a);
   2
   1
   3

   variable b = array_swap(a, 0,0);
   b[0] = 5;

   print(a);
   5
   1
   3

It seems that this is intended, at least according to the comment in slarrfun.c. But I was wondering about the rationale. It makes my Fisher-Yates shuffle two lines longer than should be necessary (or its output very hard to predict) and the (a[i],a[j]) = (a[j],a[i]) a cleaner option.

In case this is not intended I added a patch popping the array regardless of the given arguments.

Thanks,
Jakob


From 08635b31e44d0d40f1a2031f5f12e79e66bb39d4 Mon Sep 17 00:00:00 2001
From: Jakob Stierhof <jakob.stierhof@xxxxxx>
Date: Mon, 24 Jan 2022 11:22:19 +0100
Subject: [PATCH] Fix array_swap for returning nothing in all cases

When used with the same indices for swapping array_swap left
the array on stack. This requires an additional check for the
arguments in slang which is done again in the implementation
for array_swap.

This patch removes the array from the stack for all inputs.
---
 src/slarrfun.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/src/slarrfun.c b/src/slarrfun.c
index 0422458..3927650 100644
--- a/src/slarrfun.c
+++ b/src/slarrfun.c
@@ -1559,11 +1559,14 @@ static void array_swap (void)
        || (-1 == SLang_pop_integer (&i)))
      return;
 
-   if (i == j)
-     return;			       /* leave array on stack */
+  if (-1 == pop_writable_array (&at))
+     return;
 
-   if (-1 == pop_writable_array (&at))
+   if (i == j) {
+     /* nothing needs to be done */
+     SLang_free_array(at);
      return;
+   }
 
    if (have_dim)
      {
-- 
2.25.1


[2022 date index] [2022 thread index]
[Thread Prev] [Thread Next]      [Date Prev] [Date Next]