【问题标题】:Lua read beginning of a stringLua 读取字符串的开头
【发布时间】:2014-05-14 22:21:23
【问题描述】:

(请记住,这是我的第一个问题) 你好,我正在制作一个冒险游戏,我试图让用户输入一个字符串,如果字符串以 action 开头,那么它将读取函数中的其余行。

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

【问题讨论】:

    标签: string lua


    【解决方案1】:

    看看这个页面http://lua-users.org/wiki/StringRecipes

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

    然后使用

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

    【讨论】:

      【解决方案2】:

      使用string.find^ 将模式锚定在字符串的开头:

      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
      

      你甚至可以让它成为所有字符串的方法:

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

      请注意"some string literal":startswith(str) 不起作用:字符串文字没有string 表函数作为“方法”。您必须使用tostring 或函数而不是方法:

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

      最后一行的问题是语法有点混乱:是第一个字符串是模式,还是第二个?此外,模式参数(示例中的“hello”)可以是任何有效模式;如果它已经以^ 开头,则结果为假阴性,因此为了稳健,startswith 方法应该只添加^ 锚点(如果它不存在)。

      【讨论】:

      • 这里只是一个评论:如果你使用这样的函数 self:find('^' .. str) 或 sub/gsub、match 等,你必须手动转义正则表达式字符,否则将无法工作你会有特殊的字符,比如 /*.+ 等等。
      • find的问题是你需要转义str中的正则表达式特殊字符。
      【解决方案3】:

      可能有很多不同的方法可以解决这个问题,这里有一个。

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

      您可能想编写自己的语句解析器,在其中将字符串处理为已知标记等。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-28
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多