Programming Fundamentals/Strings/Lua

strings.lua

edit
-- This program splits a given comma-separated name into first and last name
-- components and then displays the name.
--
-- References:
--     https://www.mathsisfun.com/temperature-conversion.html
--     https://www.lua.org/manual/5.1/manual.html

function get_name()
    local name
    local index
    
    repeat
        io.write("Enter name (last, first):\n")
        name = io.read()
        index = string.find(name, ",")
    until index ~= nil
    return name
end

function get_last(name)
    local last
    local index
    
    index = string.find(name, ",")
    if index == nil then
        last = ""
    else
        last = string.sub(name, 0, index - 1)
    end
    return last
end

function get_first(name)
    local first
    local index
    
    index = string.find(name, ",")
    if index == nil then
        first = ""
    else
        first = string.sub(name, index + 1, string.len(name))
        first = ltrim(first)
    end
    return first
end

function display_name(first, last)
    io.write("Hello " .. first .. " " .. last .. "!\n")
end

function ltrim(text)
    while string.sub(text, 1, 1) == " " do
        text = string.sub(text, 2, string.len(text))
    end
    return text
end

function main()
    name = get_name()
    last = get_last(name)
    first = get_first(name)
    display_name(first, last)
end
    
main()

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own Lua compiler / interpreter / IDE.

See Also

edit