[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Is there a C API that could exchange the values at different index of the stack?
- From: 孙世龙 sunshilong <sunshilong369@...>
- Date: Fri, 22 Jan 2021 17:31:30 +0800
I see, thank you.
>I use abs_index A LOT in my code, it makes things much easier in a lot
>of scenarios, specially when writing helper functions.
I hope to learn it earlier. It really makes things much easier.
On Fri, Jan 22, 2021 at 5:09 PM Francisco Olarte <folarte@peoplecall.com> wrote:
>
> Sunshilong:
>
> On Fri, Jan 22, 2021 at 9:26 AM 孙世龙 sunshilong <sunshilong369@gmail.com> wrote:
> >
> > Thank you so much.
> > > i = lua_absindex(L, i);
> > > j = lua_absindex(L, j); /* In case either of them is negative. */
> > It's a magic!
> > After studying your code, I find that it is easier to achieve this
> > goal (i.e the title) by using positive indexes(or converting negative
> > indexes to positive ones) than directly using negative ones. Am I
> > right?
>
> Negative index on stack-only APIs need to be normalized, or you need a
> lot of special-casing, as they mutate when you push.
>
> Initially I just did the push-replace, then I decided to try to wrap
> it a bit more and added the normalizations, no-op case check and OOM
> checks.
>
> Normalization, making it all positive, makes the NO-OP check easier (
> I may even say possible ). If you skip it you need to check for a lot
> of conditions, which is probably going to end being slower.
>
> Imagine you have a 10 elements stack, i is 3 ( or -7 ) and j is 5 ( or
> -5 ). with positive indexes, push-replace is right.
> With negative indexes ( i=-7, j=-5)
> - after push-copying of i-value, push_value(i= -7) it i-value is now
> at -8=i-1, copied at -1, j-value is now at j-1=-6
> - So you push-copy j-value, push_value(j-1=-6), now i-value is at
> i-2=-9, j-value is at j-1=-7
> - Now pop-copy copied j-value (at -1, implicit) to i-value, so
> replace(i-2=-9), back to step 1, i-value is now at -8=i-1, copied at
> -1, j-value is now at j-1=-6
> - Now pop-copy copied i-value to j-value, so replace(j-1=-6) and
> everything is back to the same indexes.
>
> You could probably generalize it, when i is negative replace to i-2
> (but push from i), when j is negative push and replace to j-1. It
> could be worth the hassle IF abs_index calculations where extremely
> expensive or slow, but given it is a couple of checks plus a couple
> indirections it is not worth it.
>
> I use abs_index A LOT in my code, it makes things much easier in a lot
> of scenarios, specially when writing helper functions.
>
> Francisco Olarte.