【问题标题】:How can I use single and normal quotation marks in the same string?如何在同一个字符串中使用单引号和普通引号?
【发布时间】:2020-06-06 23:23:16
【问题描述】:

我正在做一个项目,在该项目中,您输入您的输入句子,并且我需要能够在句子中使用 " 和 ',例如 Input = "I said, "Hi what's up?" print(Input) 出现错误。如果有人知道如何解决这个问题,那就太好了。

【问题讨论】:

  • 在 Lua 中忘记提及了

标签: lua


【解决方案1】:

见https://www.lua.org/pil/2.4.html。 Lua 有一个非常有趣的特性,可以用方括号声明字符串:

input = [[I said, "Hi what's up?"]]
input = "I said, \"Hi what's up?\""
input = 'I said, "Hi what\'s up?"'

【讨论】:

    【解决方案2】:

    除了上面@Darius 说的以外,我还会说一些事情

    当您尝试在字符串中添加一个引号时,lua 解释器会感到困惑,并在下一个引号之后中断您的字符串而没有到达行尾。这就是错误的原因。

    试着通过下面的代码理解一下

    str = "Hello I"m somebody" -- here the interpreter will think str equals to "Hello I" at first, and then it will find some random characters after which may make it confused (as m somebody is neither a variable nor a keyword)"
    
    -- you can also see the way it got confused by looking at the highlighted code
    
    --What you can do to avoid this is escaping the quotes
    str = "Hello I\"m somebody" -- here the interpreter will treat \" as a raw character (") and parse the rest.
    
    

    您还可以将转义字符 () 与其他字符一起使用,例如 \'、\"、\[、\n(换行符)、\t(制表符)等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-18
      • 2016-02-10
      • 2023-04-02
      • 2019-06-01
      • 1970-01-01
      相关资源
      最近更新 更多