Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua read beginning of a string

Tags:

(Keep in mind that this is my first question) Hello, 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
like image 830
Albin9000 Avatar asked Apr 03 '14 08:04

Albin9000


2 Answers

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 ...
like image 54
filmor Avatar answered Oct 17 '22 05:10

filmor


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.

like image 21
Oliver Avatar answered Oct 17 '22 05:10

Oliver