Albin9000
Albin9000

Reputation: 413

Lua read beginning of a string

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

Upvotes: 31

Views: 63944

Answers (3)

Oliver
Oliver

Reputation: 29621

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.

Upvotes: 24

chrisp
chrisp

Reputation: 2259

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.

Upvotes: 5

filmor
filmor

Reputation: 32298

Have a look at this page http://lua-users.org/wiki/StringRecipes:

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

Then use

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

Upvotes: 45

Related Questions