How can i skip a section of code lua? - lua

It is my first lua project and i have a trouble with skipping part of my code. I want the code to stop after part "Cool". So if i write good and it answers cool i want the rest of the code to stop since after that the next question is not relative anymore.
How it works:
Code says: Hello
You say: anything
Code says: How are you?
You say: good
after you say good it will say cool.
If you say anything other than good it will ask "Why?"
e.g. you say: bad
Code says: It will be alright
I want it to stop after "cool" and skip out the further part of the code.
os.execute(" cls ")
print("Hello")
odp = io.read()
if odp == string then
end
tof = true or false
print("How are you?")
odp2 = io.read()
if odp2 == "good" then print("Cool") tof = true
else print("Why?") tof = false
if tof == true then os.execute(" pause ")
end
end
odp3 = io.read()
if odp3 ~= math then print("It will be alright")
print("Okay, I have to go see you.")
end
os.execute(" pause ")

When you compile code, it becomes the body of a function. The prototypical way of exiting a function is with a return statement. A function can have zero or more return statements.
But, since you want to exit the program, you can instead call os.exit().

You've just got to nest your "if" statements differently. All you need to do is put the rest of the code into the "else" part of your "if" statement, like this:
os.execute(" cls ")
print("Hello")
odp = io.read()
if odp == string then
end
tof = true or false
print("How are you?")
odp2 = io.read()
if odp2 == "good" then
print("Cool")
tof = true
else
print("Why?")
tof = false
if tof == true then
os.execute(" pause ")
end
-- You had an "end" here.
odp3 = io.read()
if odp3 ~= math then
print("It will be alright")
print("Okay, I have to go see you.")
end
os.execute(" pause ")
end -- You literally just need to move it here.
That way, it only gets input from the user after it asks for it, and only if the user doesn't answer, "good" to the "How are you?" question.
Note that I re-indented the code, but it's still the same code in the same order. I just made it more standard-looking and easier to visually see the structure of the program.

Related

How to recieve number AND strings using only one io.read()?

I want to do a program that tells the user if what kind of information is he telling...
that's what I have for now, but as you can see, it is missing the IF function to identify if it is a number, but I don't know how to get a number not using io.read('*number)
a = io.read()
if a == string.lower(a) then
print('It's a lower string')
end
if a == string.upper(a) then
print('It's an upper string')
end
pls help
Keep reading with a = io.read() and try to convert to a number:
a = io.read()
if tonumber(a) then
print("It's a number")
elseif a == string.lower(a) then
print("It's a lowercase string")
elseif a == string.upper(a) then
print("It's an uppercase string")
end

Lua code elseif not working

This is all about accepting input from user and searching with that particular text.
Playing with string.gsub.
io.write("ENTER ANY STORY :-D ")
story=io.read()
io.write("\t OKAY!, THAT'S NICE :-D ")
io.write("\t DO YOU WANT TO REPLACE ANY TEXT:? ")
accept=io.read()
if accept=="YES" or "yes" then
io.write("\t WHICH TEXT TO REPLAE? ")
replace=io.read()
--HERE IS THE REPLACING TEXT
io.write("\t WITH WHAT:? ")
with=io.read()
result=string.gsub(story,replace,with)
print("\t THE REPLACED TEXT IS: ",result)
elseif accept=="NO" or "no" then
print(result)
end
Bug: The elseif loop isn't working!!
== and or work like mathematical operators in that they are evaluated one at a time, with the == being evaluated first. If accept is 'no', accept=="YES" or "yes" will be evaluated like this:
(accept == "YES") or "yes"
('no' == "YES") or "yes"
false or "yes"
"yes"
In Lua, all values except nil and false are truthy, so your if block will always run instead of your elseif block.
As said in the comments, accept:upper()=="YES" will fix it. accept:upper() returns a string where all the letters of accept are converted to upper case, so then you only have to compare it to one value.
Try this..
io.write("ENTER ANY STORY :-D ")
story=io.read()
io.write("\t OKAY!, THAT'S NICE :-D ")
io.write("\t DO YOU WANT TO REPLACE ANY TEXT:? ")
accept=io.read()
if accept=="YES" or accept == "yes" then
io.write("\t WHICH TEXT TO REPLAE? ")
replace=io.read()
--HERE IS THE REPLACING TEXT
io.write("\t WITH WHAT:? ")
with=io.read()
result=string.gsub(story,replace,with)
print("\t THE REPLACED TEXT IS: ",result)
elseif accept=="NO" or accept == "no" then
print(result)
end

Code stops working after first run

Hello stack overflow users, I have some code here:
local input = nil
print("What file do you want to access?")
input = io.read();
local file = io.open(input, "r")
function infiniteLoop()
print("What do you want to know more about?")
input = io.read();
while true do
line = file:read()
if line == nil then break end
if string.find(line, input) then
print(line)
end
end
end
repeat
infiniteLoop()
until false
As you could guess from the title, it works the first run, but the second time it won't print out what you want, regardless of it being in the file.
Example here
You need reset file pointer. try add file:seek(0) in the begining of function

Lua "or" statement issue

I'm very new to Lua, and I'm doing a very simple text based adventure thing, but it wont work. My code is as follows:
while input ~= ("leave cave" or "leave") do
print("What do you want to do?")
input = io.read()
if input == "inspect" then
print("You are in a cave")
elseif input == "leave cave" or "leave" then
print("You leave the cave")
elseif input == "inv" then
for i,v in pairs(inv) do
print(i, v)
end
else
print("You didn't write a valid command...")
end
end
-- leave cave
input = ""
print("What do you want to do?")
input = io.read()
while input ~= "follow path" do
if input == "inspect" then
print("You are at the base of a hill. There is a path.")
elseif input == "follow path" then
print("You follow the path. There is a gate.")
elseif input == "inv" then
for i,v in pairs(inv) do
print(v)
end
else
print("That's not a valid command...")
end
end
What I'm trying to do is have it so whenever the user types leave, or leave cave, it proceeds to the next segment (the path one), however, when I type "leave" and then type "inspect" again it says "I am in a cave" rather than what it should be saying which is saying that you left, and you see a path. And when I type leave cave, and then inspect, it spams "You are at the base of a hill. THERE IS A PATH" over and over, indefinitely.
And when I type "inv" it doesn't print my inventory, and instead prints "You left the cave," but doesn't actually leave.
a or b can't make a value that means "either a or b" -- that would be too complicated.
In fact, if you ask it to choose between two strings, it will just pick the first:
print("leave cave" or "leave") --> leave cave
or is only meant to be used on booleans -- you have to combine it on multiple full conditions:
while (input ~= "leave cave") and (input ~= "leave") do
In this case, a repeat ....... until <condition> loop might serve you better:
repeat
print("What do you want to do?")
input = io.read()
-- <do stuff>
until input == "leave" or input == "leave cave"
While or cannot accomplish such a complex operation, it is possible to recreate the effect yourself with some hacky metatable code.
Please note I do not reccomend using this code in any serious professional or commercial programs, or really at all for that matter, this code is inefficient and unecessary, however it is a fun piece of code to do exactly what you're looking for. It's just a fun way to experiment with the power of Lua.
local iseither
iseither = setmetatable({},{
__sub = function(arg1,arg2)
if arg2 == iseither then
arg2.Value = arg1
return arg2
else
if type(arg2) ~= "table" then
error("Second operator is -iseither- was not a table",2)
else
for i,v in ipairs(arg2) do
if arg1.Value == v then
arg1.Value = nil
return true
end
end
arg1.Value = nil
return false
end
end
end
})
print(1 -iseither- {1,2,3,4,5})

Multi-threading functions in Computer Craft

I'm working on a project where I want to update the clock on screen say every 5 seconds unless the user inputs something. This is the code I have so far,
function thread1()
term.clear()
term.setCursorPos(1,1)
write (" SteveCell ")
local time = os.time()
local formatTime = textutils.formatTime(time, false)
write (formatTime)
print ("")
print ("")
for i=1,13 do
write ("-")
end
print("")
print ("1. Clock")
print ("2. Calender")
print ("3. Memo")
print ("4. Shutdown")
for i=1,13 do
write ("-")
end
print ("")
print ("")
write ("Choose an option: ")
local choice = io.read()
local choiceValid = false
if (choice == "1") then
-- do this
elseif (choice == "2") then
-- do that
elseif (choice == "3") then
-- do this
elseif (choice == "4") then
shell.run("shutdown")
else
print ("Choice Invalid")
os.sleep(2)
shell.run("mainMenu")
end
end
function thread2()
localmyTimer = os.startTimer(5)
while true do
local event,timerID = os.pullEvent("timer")
if timerID == myTimer then break end
end
return
end
parallel.waitForAny(thread1, thread2)
shell.run("mainMenu")
Unfortunately it's not working. If someone could help me with this, I would really appreciate it. Thanks :)
You want to do something like this (Im not doing the correct on screen drawing, only the time)
local function thread1_2()
-- both threads in one!
while true do
local ID_MAIN = os.startTimer(5)
local ID = os.startTimer(0.05)
local e = { os.pullEvent() }
if e[1] == "char" then
-- Check all the options with variable e[2] here
print( string.format( "Pressed %s", e[2] ) )
break -- Getting out of the 'thread'
elseif e[1] == "timer" and e[2] == ID then
ID = os.startTimer(0.05) -- shortest interval in cc
redrawTime() -- Redraw and update the time in this function!!!
elseif e[1] == "timer" and e[2] == MAIN_ID then
break
end
end
end
Also, ask this in the proper forum, you have more chance getting an answer there!
Another note, get more into event handling, it really helps.
FYI Lua doesn't have 'multi-threading' as in executing multiple routines simultaneously. What it does have is 'thread parking.' You can switch between routines (yielding) and switch back and it will resume where it left off, but only a single routine will be active at any given time.
This is my go-to Lua reference, which explains in detail:
http://lua-users.org/wiki/CoroutinesTutorial

Resources