Log In  

This code:

x+=x<0 and -100 or 100

doesn't work the way I'd expect; it sets x to either -100 or 100


I assume this happens because that line gets preprocessed to this:

x=x+x<0 and -100 or 100

which gets interpreted like this:

x=(x+x<0) and -100 or 100

but I wish it would be preprocessed to this instead:

x=x+(x<0 and -100 or 100)

Here's a test cart; it currently (0.2.2c) fails the tests:

Cart #zemazebosi-0 | 2021-04-19 | Code ▽ | Embed ▽ | No License
2

P#90818 2021-04-19 22:01

4

You can use a feature of the parser to find out what the final/unrolled code is:

> print([=[x+=x<0 and -100 or 100]=])
x = x + (x) <0  and -100  or 100

And yeah, this clearly doesn't unroll correctly, since it obviously needs to be this:

x = x + (x<0  and -100  or 100)

It looks like the regex that @zep uses to search/replace the expression on the right side of the assignment is simply missing two of the comparison operators: "<" and ">".

Surprisingly, it does work correctly with other comparison operators:

> print([=[x+=x<=0 and -100 or 100]=])
x = x + (x<=0  and -100  or 100)  

> print([=[x+=x==0 and -100 or 100]=])
x = x + (x==0  and -100  or 100)  

> print([=[x+=x>=0 and -100 or 100]=])
x = x + (x>=0  and -100  or 100)  

So yes, there's a bug here.


As a workaround, you could enclose the expression manually:

> print([=[x+=(x<0 and -100 or 100)]=])
x = x + ((x<0  and -100  or 100 ))

You could also flip the condition to use one of the working operators:

> print([=[x+=x>=0 and 100 or -100]=])
x = x + (x>=0  and 100  or -100) 

Or you could use the built-in sgn(x) function, which also compares x<0 and returns -1 or 1:

x=sgn(x)*100

(Note: Unlike C/C++'s sign(x), the PICO-8 sgn(x) does not return 0 when x==0. 0 is considered positive, so it returns 1.)

P#90833 2021-04-20 09:17 ( Edited 2021-04-20 09:20)
2

Thanks @pancelor, @Felice

This is fixed for 0.2.2d. It was caused by some historic junk enum values that were being used for the <, > tokens and causing them to not be recognised in this context.

P#90893 2021-04-21 15:37

Rad trick with the heredoc op, @Felice! very cool!

P#90915 2021-04-22 02:07

@Felice How did you know about the print([=[]=]) thing? I never even knew about it until just now!

P#90959 2021-04-23 00:48
1

@StinkerB06
Ah, someone else told me. I forget, might have been Fred or maybe thisismypassword, maybe someone else. (I has swiss-cheese memory; I apologize to whomever deserves credit!) Edit: It was sam!

P#90964 2021-04-23 04:19 ( Edited 2021-05-01 17:22)
4
P#90997 2021-04-23 19:42

Aha! Yes indeed. All credit to sam for sharing the trick in the first place! :)

P#91273 2021-04-29 02:56 ( Edited 2021-04-29 02:59)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-03-28 09:41:04 | 0.029s | Q:31