[SOLVED] Replacing a variable with a player input

How can I replace a variable value with a player-defined input?
the variable above is

var colorcode = "";

and it can send the message output.
so let’s say that the player types in /color 23, the code recognizes that it starts with /color with a space, but it doesn’t recognize the color code (23), so how do I make it that when the player types /color 23, var colorcode’s value is replaced with 23?

                if (message.startsWith("/color ")) {
                    if (socket.key === devkey || socket.key === betakey || socket.key === seniorkey){
                    player.body.color = colorcode;
                    return 1;

Thanks for reading :slight_smile:


you could go the inefficient route and use a bunch of if's

Something like this, perhaps

You want to get the rest of the message first; the part that’s not "/color ".

One way would be to do a replacement

const restOfMessage = message.replace("/color ", "").trim();
// restOfMessage = "23" string

You might want to convert it from a string to a number (here’s a cheeky technique):

const maybeColorCode = +restOfMessage 

(another way to coerce it to a number is 1* restOfMessage)

Then validate that what you have is a valid colorcode in your system:

// An array of valid codes
const validColorCodes = [23,47,99];

// Check that the array contains the user input (i.e. user input is valid)
if (validColorCodes.indexOf(maybeColorCode) !== -1)
  player.body.color = maybeColorCode;

// Otherwise do nothing - don't change the player's body color.

Hope it helps! :blush:

1 Like

Thank you so Much!
it worked :grinning:
so now I’ve made a few changes so that the messaging system works with it, but it functions perfectly

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.