In my lua program, i want to stop and ask user for confirmation before proceeding with an operation. I'm not sure how to stop and wait for user input, how can it be done?
local answer
repeat
io.write("continue with this operation (y/n)? ")
io.flush()
answer=io.read()
until answer=="y" or answer=="n"
Take a look at the io library, which by default has standard-input as the default input file:
http://www.lua.org/pil/21.1.html
I've worked with code like this. I will type this in a way it will work:
io.write("continue with this operation (y/n)?")
answer=io.read()
if answer=="y" then
--(put what you want it to do if you say y here)
elseif answer=="n" then
--(put what you want to happen if you say n)
end
I use:
print("Continue (y/n)?")
re = io.read()
if re == "y" or "Y" then
(Insert stuff here)
elseif re == "n" or "N" then
print("Ok...")
end
try to use folowing code
m=io.read()
if m=="yes" then
(insert functions here)
end
print("Continue (y/n)?")
re = io.read()
if re == "y" or "Y" then
(Insert stuff here)
elseif re == "n" or "N" then
print("Ok...")
end
From the bit of lua that I've done (not a lot), I'm going to say that using both uppercase and lowercase letters is redundant if you use string.sub.
print("Continue? (y/n)")
local re = io.read()
--[[Can you get string.sub from a local var?
If so, this works. I'm unfamiliar with io(game
lua uses GUI elements and keypresses in place of the CLI.]]
if re.sub == "y" then
--do stuff
if re.sub == "n" then
--do other stuff
end
That should work.
Related
I am trying to move my i location forward and backward if a certain string arrives kind of like assembly code, is this possible using lua?
something like this:
local array = {"Hi", "Goodbye", "Cat"}
for i in pairs(array) do
if string.find(array[i], "Hi") then
move_to(3) -- so it will basically skip over "Goodbye" but I need this on a large scale so it can jump from 3 to 234 and then jump back to 1 etc etc
elseif array[i] == "Cat" then
print("Cat")
end
end
Also I cannot just make a variable to check if a jump is in progress and just ignore the other values until I am at the descried location, because then I cannot jump backwards
Thanks!
You cannot use a numeric for loop or a generic for loop with the standard iterator functions to do this. You cannot properly control their state from inside. Just use a while loop.
while notDoneCondition do
-- do stuff that may trigger the jumpCondition
if jumpCondition then
pos = jumpTarget
end
end
I'm very new to coding and right now my code is really bulky and I want to know if there is a way to make a more compact function to check answers, right now I just have if then statements copied and pasted over and over with the variable capitalized and spelled a different way every time, for example, for no I have if then statements for N,n,no,NO,No,nO.
local men = io.read()
if men == "N" then
print(" You decide that you're fine with getting pushed around for your whole life, so you continue like that until you are old and die. THE END")
return
end
if men == "NO" then
print(" You decide that you're fine with getting pushed around for your whole life, so you continue like that until you are old and die. THE END")
return
end
if men == "no" then
print(" You decide that you're fine with getting pushed around for your whole life, so you continue like that until you are old and die. THE END")
return
end
if men == "No" then
print(" You decide that you're fine with getting pushed around for your whole life, so you continue like that until you are old and die. THE END")
return
end
if men == "n" then
print(" You decide that you're fine with getting pushed around for your whole life, so you continue like that until you are old and die. THE END")
return
end
You can use patterns. They are very similar to regular expressions which are used across most programming languages. Here I test the answer string to see if it matches the pattern you're looking for. Here's an explanation of pattern:
^ - match the start of the string, don't allow any characters before this. If you don't include this then it could find 'no' later in the string, i.e. abcdNO
[nN] - the [] let you include a list of acceptable characters, so here the first character needs to be n or N
[oO]? - the next character has to be o or O, but the ? means it is optional, it can occur 0 or 1 times.
$ matches the end of the string, so it will not match 'NOabcd` because there can't be anything after your pattern.
In all that means the string has to start with 'n' or 'N', possibly have a single 'o' or 'O', and have nothing else after that.
string.find(string, pattern) will see if string is matched by pattern and return the position it was found in the string, or nil if not found.
local answer = 'No'
local pattern = '^[nN][oO]?$'
if (string.find(answer, pattern) ~= nil) then
print('found!')
else
print('not found!')
end
You can use a set then you check if the input is a member of the set. a simple set in Lua can be defined like so:
local no = {
N = true,
n = true,
no = true,
NO = true,
No = true,
nO = true
}
and you use it just by indexing it like any table:
local men = io.read()
if no[men] then
print(" You decide that you're fine with getting pushed around for your whole life, so you continue like that until you are old and die. THE END")
return
end
a nil in lua will be treated as a false in this context, and you will get nil from any value that is not a key in the set
I'm adding another answer to offer a simpler change. You should generally try to find a way to avoid duplicate code. The same 'print' statement is repeated several times.
One thing you can do is use the or operator and combine all your tests into one expression.
local men = io.read()
if men == "N" or men == "NO" or men == "no" or men == "No" or men == "n" then
print(" You decide that you're fine with getting pushed around for your whole life, so you continue like that until you are old and die. THE END")
return
end
That is the best method for the setup you have, but if you don't have a simple condition like this and want to reuse the code you could create a function with the duplicated code and call it instead. Say if you wanted to do something ELSE as well depending on certain values:
function badEnding()
print(" You decide that you're fine with getting pushed around for your whole life, so you continue like that until you are old and die. THE END")
-- NOTE: return is not required, the default return value will be nil
end
local men = io.read()
if men == "N" then return badEnding() end
if men == "NO" then
print("Hey, no need to shout!")
return badEnding()
end
if men == "no" then return badEnding() end
if men == "No" then return badEnding() end
if men == "n" then return badEnding() end
You can put your options into a list and than ask through a for-loop if your input is equal to a statement in your list. If not there isn't a mistake.
For example if you have list like:
l_words = ["N","n","no","NO","N0","nO"]
inp = input("Your input: ")
for i in l_words:
if inp != i:
print("true input")
else:
print("false input")
I need to check if something has children in ROBLOX Lua. I know of FindFirstChild(string) which finds the first child with a name matching string, and I have been using that to see if the instance has a certain child in it, but now I want to see if it has ANY at all. I was hoping for something like:
if Instance:GetChildren() then
--Do something
end
How do I do something like that?
This method will get a table of the Instance's children and check if it is more than 0, meaning it has children.
if #Instance:GetChildren() >0 then
--It has children!
end
I suggest using the hashtag operator or table.getn
-- Hashtag
if(table.getn(Instance:GetChildren()) > 0) then
-- ...
end
if(#Instance:GetChildren() > 0) then
-- ...
end
if Object.GetChildren() then
--code here
end
here's one way you could find that out:
x = 0
for i, v in pairs(script:GetChildren()) do
x += 1
end
if x > 0 then
print("it has children")
end
it's not the most efficent but it's pretty simple and works
I'm trying to find out a way to use a multiline comment on a batch of code, but it keeps mistaking some syntax in it as a ]] and thinking I want it to end there, which I don't!
--[[
for k,v in pairs(t) do
local d = fullToShort[k]
local col = xColours[v[1]] -- It stops here!
cecho(string.format(("<%s>%s ", col, d))
end
--]]
I thought I read somewhere it was possible to do use a different sort of combination to avoid those errors, like --[=[ or whatnot... Could someone help?
As you can see in Strings tutorial there is a special [===[ syntax for nesting square braces. You can use it in block comments too. Just note, that number of = signs must be the same in open and close sequence.
For example 5 equals will work.
--[=====[
for k,v in pairs(t) do
local d = fullToShort[k]
local col = xColours[v[1]] -- It stops here!
cecho(string.format(("<%s>%s ", col, d))
end
--]=====]
You can use the following to create multiline comments past ]]'s:
--[[
codes
]]
Im a amatuer at coding. So, mind me if i face palmed some things.
Anyways, im making a alpha phase for a OS im making right? I'm making my installer. Two questions. Can i get a code off of pastebin then have my lua script download it? Two. I put the "print" part of the code in cmd. I get "Illegal characters". I dont know what went wrong. Here's my code.
--Variables
Yes = True
No = False
--Loading Screen
print ("1")
sleep(0.5)
print("2")
sleep(0.5)
print("Dowloading OS")
sleep(2)
print("Done!")
sleep(0.2)
print("Would you like to open the OS?")
end
I see a few issues with your code.
First of all, True and False are both meaningless names - which, unless you have assigned something to them earlier, are both equal to nil. Therefore, your Yes and No variables are both set to nil as well. This isn't because true and false don't exist in lua - they're just in lowercase: true and false. Creating Yes and No variables is redundant and hard to read - just use true and false directly.
Second of all, if you're using standard lua downloaded from their website, sleep is not a valid function (although it is in the Roblox version of Lua, or so I've heard). Like uppercase True and False, sleep is nil by default, so calling it won't work. Depending on what you're running this on, you'll want to use either os.execute("sleep " .. number_of_seconds) if you're on a mac, or os.execute("timeout /t " .. number_of_seconds) if you're on a PC. You might want to wrap these up into a function
function my_sleep_mac(number_of_seconds)
os.execute("sleep " .. number_of_seconds)
end
function my_sleep_PC(number_of_seconds)
os.execute("timeout /t " .. number_of_seconds)
end
As for the specific error you're experiencing, I think it's due to your end statement as the end of your program. end in lua doesn't do exactly what you think it does - it doesn't specify the end of the program. Lua can figure out where the program ends just by looking to see if there's any text left in the file. What it can't figure out without you saying it is where various sub-blocks of code end, IE the branches of if statements, functions, etc. For example, suppose you write the code
print("checking x...")
if x == 2 then
print("x is 2")
print("Isn't it awesome that x is 2?")
print("x was checked")
lua has no way of knowing whether or not that last statement, printing the x was checked, is supposed to only happen if x is 2 or always. Consequently, you need to explicitly say when various sections of code end, for which you use end. For a file, though, it's unnecessary and actually causes an error. Here's the if statement with an end introduced
print("checking x...")
if x == 2 then
print("x is 2")
print("isn't it awesome that x is 2?")
end
print("x was checked")
although lua doesn't care, it's a very good idea to indent these sections of code so that you can tell at a glance where it starts and ends:
print("checking x...")
if x == 2 then
print("x is 2")
print("isn't it awesome that x is 2?")
end
print("x was checked")
with regards to your "pastebin" problem, you're going to have to be more specific.
You can implement sleep in OS-independent (but CPU-intensive) way:
local function sleep(seconds)
local t0 = os.clock()
repeat
until os.clock() - t0 >= seconds
end