Programming Fundamentals/Strings/Lua: Difference between revisions

From Wikiversity
Jump to navigation Jump to search
Content deleted Content added
Creating
(No difference)

Revision as of 15:09, 26 February 2017

strings.lua

-- This program splits a given comma-separated name into first and last name
-- components and then displays the name.

function get_name()
    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)
    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)
    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 .. "!")
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

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