Check if Number is 1 in as Little Code as Possible?

Since you are trying to make it print “This has 2 quotation mark” or “This has 2 quotation marks

local Message = "This has 2 quotation mark%s"
local FormattedMessage
local Number = -- Number?
if Number > 1 then
   FormattedMessage = string.format(Message, "s")
else
   FormattedMessage = string.format(Message, "")
end

print(FormattedMessage)

Maybe something like this though not sure if it will work or not

No, sorry that was just an example.

Right now my code uses 5 lines and I’m trying to reduce it to 1.

But that’s what you are trying to do, correct?
A sentence that prints singular or plural items.

Not sure why you need to do it that way? but you can still put everything on one line if you need to. The only issue is it will be hard to read.

Yeah, but I was just hoping something shorter would work to make it easier to read.

You don’t need to reduce it, it does not matter how many lines of code there, your script will still run as expected. Also making it shorter is actually harder to read due to there being less spaces.

The code will be closely replicated around 50 times eventually though.

Edit: And 1 * 50 is 50 but 5 * 50 is 250 which is a big difference.

It’s easier to read when it’s not one line, honestly.

If this code was on one line, it would look like this:

local number = 1 local str = "This has 2 quotation mark" if number == 1 then print(str.."s!") else print(str) end

(Which isn’t as readable, vs this:)

local number = 1
local str = "This has 2 quotation mark"

if number == 1 then
    print(str.."s!")
else
    print(str)
end

I don’t get what you are trying to do. Please tell us in a more detailed manner.

local Message = "This has 2 quotation mark"..(Number > 1 and "s" or "")

This could also work, though I haven’t tested it but I don’t see a reason why it shouldn’t work.

6 Likes

Make a function, like this:

local str = "This has 2 quotation mark"

local function Check(number)
    if number == 1 then
        print(str.."s!")
    else
        print(str)
    end
end

Check(5)
Check(10)

@CommanderRanking I know that’s why I’m trying to get shorter code.

@2jammers I’m just wanting to know if there’s a shorter way to write my code.

str is a constant, please move it out of the function.

Good catch, thanks! (I just copied the code and pasted it in the function, lol.)

Thank you, this is exactly what I was looking for!

1 Like

FYI, the solution used ternary operators, its a useful concept that you will for sure find yourself using alot

I’ve heard of ternary operators before it’s just my mind goes :exploding_head: when I try to figure out what’s happening there. I have a slight idea of how they work but I will read this, thank you.

1 Like
local function FormatPlurality(String, Number)
	if Number > 1 then String..="s" end
	return String
end