Search code examples
lua

Replace last comma on string Lua


I have this string

Apples, Oranges, Grapes

How can i replace last comma for and?

Havent learn enough of patterns but i've tried several ways such as

str:gsub(",$", "and", 1)

Isnt supposed that magic character $ reads string from end --> begin?

My problem becomes because im concatenating an array using table.concat


Solution

  • Your table:

    local t = {"Apples", "Oranges", "Grapes"}
    

    Method #1: Concatenate the last item using "and":

    local s = #t > 1 
              and table.concat(t, ", ", 1, #t-1).." and "..t[#t] 
              or  table.concat(t, ", ")
    print(s)  --> Apples, Oranges and Grapes
    

    Method #2: Replace the last comma:

    local s = table.concat(t, ", ")
    s = s:gsub("(.*),", "%1 and")
    print(s)  --> Apples, Oranges and Grapes