First character uppercase Lua
Asked Answered
C

4

24

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.

Churr answered 11/3, 2010 at 0:18 Comment(0)
D
57

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
Dybbuk answered 11/3, 2010 at 0:30 Comment(3)
@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).Dybbuk
Sorry, I just got caught by this gotcha (indeed dangerous). The gsub case is even documented in particular at the end of the section.Patisserie
@Dybbuk 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!Citation
H
14

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

Helbon answered 11/3, 2010 at 0:59 Comment(2)
interjay's version didn't work in LÖVE (love2d), this on the other hand works great.Audrieaudris
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.Citation
C
0

In my case, I wanted to keep it simple but ensuring it worked even if the string was all upper case, so I ended up having to use this solution:

local s = "SHAPE"
print(s:lower():gsub("^%l", string.upper))

Which prints "Shape" no matter what...

Coarsegrained answered 13/11, 2023 at 17:20 Comment(0)
T
0

You can also create a function as an extension to the string library in lua this way:

function string.capitalize(str)
    if str=="" then return end
    local first = str:sub(1,1)
    local last = str:sub(2)
    return first:upper()..last:lower()
end
local String = "mYTestSTring"
print(String:capitalize())
-- returns: Myteststring
Torpedoman answered 24/6 at 13:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.