I am making an adventure game and I'm trying to make the user input a string and if the string starts with action then it will read the rest of the line in a function.

act=io.read(); if act=="blah" then doSomething(); elseif act=="action"+random string then readRestOfStringAndDoSomethinWwithIt(); else io.write("Unknown action\n"); end 

3 Answers

Have a look at this page :

function string.starts(String,Start) return string.sub(String,1,string.len(Start))==Start end 

Then use

elseif string.starts(act, "action") then ... 
0

Use string.find with the ^ which anchors the pattern at beginning of string:

ss1 = "hello" ss2 = "does not start with hello" ss3 = "does not even contain hello" pattern = "^hello" print(ss1:find(pattern ) ~= nil) -- true: correct print(ss2:find(pattern ) ~= nil) -- false: correct print(ss3:find(pattern ) ~= nil) -- false: correct 

You can even make it a method for all strings:

string.startswith = function(self, str) return self:find('^' .. str) ~= nil end print(ss1:startswith('hello')) -- true: correct 

Just note that "some string literal":startswith(str) will not work: a string literal does not have string table functions as "methods". You have to use tostring or function rather than method:

print(tostring('goodbye hello'):startswith('hello')) -- false: correct print(tostring('hello goodbye'):startswith('hello')) -- true: correct print(string.startswith('hello goodbye', 'hello')) -- true: correct 

Problem with the last line is that syntax is a bit confusing: is it the first string that's the pattern, or second one? Also, the patter parameter ('hello' in the example) can be any valid pattern; if it already starts with ^ the result is a false negative, so to be robust the startswith method should only add the ^ anchor if it is not already there.

2

There are probably a number of different ways to solve this, here's one.

userInput = ... -- however you're getting your cleaned and safe string firstWord = userInput:match("^(%S+)") -- validate firstWord 

You might want to write your own statement parser where you process the string into known tokens, etc.

0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy