nml icon indicating copy to clipboard operation
nml copied to clipboard

Document procedures for switches and random switches

Open andythenorth opened this issue 4 years ago • 7 comments

Procedures were added in https://github.com/OpenTTD/nml/pull/66

NML docs need updated to cover procedures.

Maybe directly in these pages? https://newgrf-specs.tt-wiki.net/wiki/NML:Switch https://newgrf-specs.tt-wiki.net/wiki/NML:Random_switch

andythenorth avatar Apr 26 '20 07:04 andythenorth

Procedures Procedures are a technique for using a switch chain where normally a variable would be used. The switch chain is called like a variable, runs whatever logic is required, and returns a result to the calling switch. The calling switch can also pass parameters to the procedure.

Benefits of procedures

  1. Remove duplicate code. For example a vehicle grf might use complex rules for choosing the sprites for a vehicle. There might be 20 vehicles with similar switches in the graphics chains. These can't all share the same switch because they need to return the correct unique sprites. Using procedures, each vehicle can use a single switch, which calls a procedure containing the complex rules. This returns a result to the vehicle, which switches to the appropriate sprites. Removing the duplicate code:
  • makes it easier for the author to write and maintain the nml code, because reusable code is written once instead of many times
  • usually will compile faster
  • reduces filesize (not a big deal, but still useful)
  1. Simplify complex expressions in switches. It's possible to write very complex expressions for the switch variable, for example stacking up ternary operations. These don't format well in nml and are hard to read and make sense of. By moving the logic to a chain of switches, it can be easier to read and understand the code.

  2. Creating fake custom variables. IS IT REALLY WISE TO EXPLAIN THIS?

To use: switch_name() or switch_name(parameter_1, parameter_2, ... parameter_n)

Explain the declaration of parameters in the procedure (callee).

andythenorth avatar Jul 01 '21 20:07 andythenorth

Looks like a good start :)

glx22 avatar Jul 06 '21 17:07 glx22

Tyler has some real-world examples which are much better than any of mine.

https://github.com/2TallTyler/improved_town_layouts/blob/master/src/functions.nml

andythenorth avatar Jul 07 '21 18:07 andythenorth

Don't forget to put a note about the 15bit return value :)

glx22 avatar Aug 15 '21 12:08 glx22

Oof adventures in 15 bit values yes.

andythenorth avatar Aug 15 '21 21:08 andythenorth

Did we ever discuss var 1C?

From the nfo docs: Because callback results are limited to 15 bits, to access the full 32 bit result you can read variable 1C instead (e.g. by and-ing the 7E result with 0 and then adding var. 1C).

andythenorth avatar May 09 '22 08:05 andythenorth

Var 1C is last_computed_result in NML.

glx22 avatar May 09 '22 10:05 glx22