20

Does Lua provide a function to make the first character in a word uppercase (like ucfirst in php) and if so, how to use it?

I want keywords[1] to be first letter uppercase. I've read that string.upper does it but it made the whole word uppercase.

0

2 Answers 2

50

There are some useful string recipes here, including this one. To change the first character in a string to uppercase, you can use:

function firstToUpper(str)
    return (str:gsub("^%l", string.upper))
end
3
  • 2
    @GrasDouble Please do not edit other people's code unless it's just a formatting change. Your edit (removing the parentheses) changes the behavior of the function and makes it incorrect (it makes the function return two values instead of one).
    – interjay
    Sep 24, 2017 at 22:06
  • Sorry, I just got caught by this gotcha (indeed dangerous). The gsub case is even documented in particular at the end of the section. Sep 24, 2017 at 22:23
  • @interjay What I LOVE about your answer is the use of %l (lowercase ASCII letters). This ensures that it doesn't attempt to uppercase any UTF8 byte sequences, since those will never match the "string starts with lowercase letter" rule you have here. This ensures that your function WON'T corrupt UTF8 strings. Fantastic idea, since Lua doesn't support UTF8 (and yeah there's some libraries, especially in Lua 5.3, but that UTF8 support is external and doesn't exist in string.gsub(), string.upper() and other core Lua functions). The %l is a perfect safeguard. It also improves the speed! Mar 21, 2022 at 0:02
11

This also works: s:sub(1,1):upper()..s:sub(2)

2
  • interjay's version didn't work in LÖVE (love2d), this on the other hand works great. Jan 20, 2018 at 1:06
  • Everyone: This answer is very dangerous if you ever have UTF8 data/byte sequences in your strings. This answer will corrupt your UTF8 strings by randomly chopping/truncating UTF8 multibyte sequences. Read my comment on @interjay's answer for the full explanation. Mar 21, 2022 at 0:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.