Log In  

Trying to use shifts instead of multiplication, I noticed an odd thing:

work_ram = 0x4300

printh(work_ram +  2*32) -- result: 17216
printh(work_ram +  2<<5) -- result: 24640  + has higher precedence than shift, is this correct? 
printh(work_ram + (2<<5))-- result: 17216
printh(work_ram |  2*32) -- result: 17216
printh(work_ram |  2<<5) -- result: 17216
printh(work_ram | (2<<5))-- result: 17216

pico-8 version: pico-8_0.2.1b_windows

Am I missing something and this is an intended behavior or there's an operator precedence inconsistency?

P#80287 2020-08-03 02:18 ( Edited 2020-08-03 10:25)

so, going through just using print() on the command line with the same version, I get these results in order:
17384
24640
17216
17384
17216
17216

I want to mention that first, because I'm not sure just from your post which part you're pointing out as inconsistent. If it's printh giving different values, then that's probably a bug.

If you're referring to the precedence of "|" and "<<", those are consistent with the precedence of operators in C, which is a good default in the absence of Lua specification.

To explain why they'd be that way, consider the main usage: bitmasking. "&" and "|" are typically used to check and set the values of specific bits, usually with an expression such as this:

value = flag & 1 << offset;

In C, if value is a boolean, then it would result in true if that bit was 1. this is not the case in Lua, but Lua wasn't designed for this anyway. Now, admittedly, the reasoning falls apart if you consider "==" as well, but that's for historical reasons apparently.

If you mean it's strange that "<<" and ">>" aren't treated like multiplication, that's also because of their intended use. They do result in doubling and halving, but they are fundamentally bitwise operations rather than arithmetic operations. This matters because they usually drop edge bits rather than wrapping around like arithmetic doubling would do. Also, if they were associated with normal arithmetic, that would raise the question of whether they should be multiplication or exponentiation.

P#80295 2020-08-03 05:50 ( Edited 2020-08-03 05:57)

Thanks, i reformatted the code because the asterisks were missing but yiu got the idea. I was expecting the shift to be higher precedence than sum, so the inconsistent for me was the line with 24640 as result.
My confusion comes from the phrase tib the manual, that they behave exactly the same as the functions so i imagined they'd always be executed first

P#80298 2020-08-03 08:56 ( Edited 2020-08-03 09:13)
1

If it helps, a couple of us have tested and documented PICO-8's precedence/order-of-operations on the community wiki:

https://pico-8.fandom.com/wiki/Lua#Operator_priorities

P#80306 2020-08-03 10:08 ( Edited 2020-08-03 10:15)

Thanks, @Felice that clarifies my confusion.

P#80307 2020-08-03 10:24

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2022-12-02 22:10:17 | 0.012s | Q:15