Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

SugarCube Simple Function Issue

So after taking a look through the forums, I've gotten (perhaps a little to much) brazen, and decided to fiddle around with JavaScript functions. I tried to emulate a users example function "ShootYourself".

Here is what I have in my script passage -
window.ShootMyself = function(Player, Gun) {
D = Gun.Damage;
if (D < 1) D = 1;
Player.Health -= D;
Gun.Ammo --;
};
And this is the setter link for the function -
[[Shoot Yourself|Camp][ShootMyself($Player, $Gun)]]
I wasn't to surprised when it didn't work, however, I was very surprised when I switched my story format to SugarCane (previously SugarCube), and it did work. I've already done so much in SugarCube and really enjoy the features, so I don't want to abandon it just for this small thing. But I really want to know what I'm doing wrong. 

Comments

  • You're not declaring the variable D (with the var keyword), which means that due to a JavaScript misfeature it gets created as an auto-global.  Auto-globals are dangerous and not permitted in SugarCube.

    Try this:

    window.ShootMyself = function (Player, Gun) {
    var D = Gun.Damage;
    if (D < 1) D = 1;
    Player.Health -= D;
    Gun.Ammo--;
    };
    Also, I would suggest not separating the increment/decrement operators and the variables/properties they modify (as you did with "Gun.Ammo --").  While you can, technically, it's not idiomatic.

    PS: You should have received a reference error about D (something about it being "undeclared" or "not defined"), but those errors are currently being sent to a black hole.  I'll correct that for the next release.

    PPS: If you plan to use something like that in production, rather than merely as some test, you should also add a range check on your ammo, so the gun won't shoot if it's empty.
Sign In or Register to comment.