Something about the Nashorn JS API & coding tips
-
First of all, I wanna say that the ScriptAPI which LiquidBounce used is based on the Nashron JS, which runs at JS standard ES5. (It means that there are no
Map
,=>
orclass
in your script) Let me tell you something about the features of this unique API, which differs from the JS running on this page.
NOTE: Some of following codes will be regarded as syntax error (in VS Code), please ignore them1. You can't use Kotlin standrad library and extensions in your scripts
Many of us are enjoyed with Kotlin Lib and Extensions such asmap
,filter
andsorted
toIterable<T>
. They are not avilable in your scripts. Instead, you can use akin JS functions to implement such actions.2. You can bypass getters and setters in some particular contexts
You can read data inArrayList
s like JSArray
:arrayList[0] = 1;
You can use alike method in any classes which implements
java.io.Serializable
such asLinkedList
andHashMap
.
Unfortunately, it seems that Mojang doesn't like to implement this interface. As a result of that, we can only useblockPos.getX()
instead of directly get x coordinates like a paramter. Oops!3. You can use JS functions where needs Java 8 Fuctions(API)
It means that you can usefunction () { [native code] }
with Java 8 Stream API. Meanwhile, single line function can be written like this:[1, 2, 3].map(function(x) x * x).forEach(function(x) Chat.print(x));// out 149
It will return the result of this line.
4. You can use useful syntactic sugar which normal ES5 not included
- Java-like for each
for each (var entity in mc.theWorld.loadedEntityList) //...
- Directly use some Java Classes
var particles = new java.util.LinkedList(); var healthMap = new java.util.HashMap(); java.lang.Math.signum(0.5 - Math.random())//first Math is Java's, second is JavaScript's
- some function extensions
string.trimLeft() string.trimRight() //only for js str
5. It is possible to add guarded catch clauses that only execute if the specified condition is true
try { throw "BOOM"; } catch (e if typeof e === 'string') { print("String thrown: " + e); } catch (e) { print("this shouldn't happen!"); }
More informations: https://www.baeldung.com/java-nashorn
Enjoy
-
@konoha-scarlet good tutorial but still for a new user who sees this its not understandable
-
@konoha-scarlet Very good tips Would be useful but i barely use lb anymore
-
@ali00035 said in Something about the Nashorn JS API & coding tips:
good tutorial but still for a new user who sees this its not understandable
For these users, I suggest to read MCP code (to be familiar with MC) rather than directly write scripts