you never initialize final. "if final~=nil" will
never be true. I think you meant that to be "if final==nil" which would update final only if it hadn't been set already. As it is now, it sets final only if it
has been been set already, which naturally can never happen!
You must also initialize final to nil before both loops. Because of how globals work in lua, it's currently keeping it's value between runs of the program, so long as the computer isn't rebooted!
first = io.read()
sec = io.read()
final=nil
vowels = {"a", "e", "i", "o", "u"}
for i =1, string.len(first) do
l = string.sub(first, i, i)
for k, v in pairs(vowels) do
if l == v then
if final == nil then --Need this or it will go up to the last vowel
final = string.sub(first, 1, i-1)
end
end
end
end
print(final)
:edit: This is a modified version of the same program that has some suggested improvements, with comments explaining them. For educational purposes.
--// it's a good idea to make all variables local, by prefixing with "local"
--// when you're setting their initial value. Prevents them carrying over to
--// other programs and causing weird results and bugs!
local first = io.read()
local sec = io.read()
local final = nil
--// if you make the vowels keys into a mapped table instead of values in an array table,
--// you can eliminate the inner loop over the vowels
vowels = { ["a"] = true, ["e"] = true, ["i"] = true, ["o"] = true, ["u"] = true, }
--// the # operator returns length of a string or array, shorter than doing string.len
for i = 1, #first do
l = string.sub(first,i,i)
--// with the keyed table, we can just do this
if vowels[l] then
final = string.sub(first,1,i-1)
--// since we only have the one loop now, we can just break out
break
end
end
print(final)
Edited by GopherAtl, 05 March 2015 - 02:22 PM.