Difference between ' and " within Lua - lua

I just have a general question.
Is there any difference using single and double quote marks within Lua?
Example:
require('test.lua')
require("test.lua")
When I programmed in PAWN, a language similar to C, single quote marks could be used for characters, but not strings of text, you had to use double quote marks for them.
And if there is no difference, which one is recommended to be used?
This question has most likely been answered already, however I failed to find a topic already answered.
Thank you.

Nope. No difference, except that you can enclose the other inside the ones that you are using.
-- No difference between these
myStr = "Hi!!"
myStr = 'Hi!!'
myStr = [[Hi!!]] -- The 'weird' way to make a string literal IMO...
-- Double quotes enclosed in single quotes
myStr = 'My friend said: "Hi!!"'
-- Single quotes enclosed in double quotes
myStr = "My friend said: 'Hi!!'"
-- Single and double quotes enclosed in double brackets
myStr = [[My friend said: "What's up?"]]
See: Strings in Lua for more information.

There is no difference between the two in Lua, so you can use whichever you like. I tend to differentiate between them semantically:
I use "double quotes" for user-visible strings and text, basically whatever appears on the output or in files
I use 'single quotes' for option-like strings for passing to methods and generally in code, like io.stdout:setvbuf('no')

You can find out about Lua strings easily enough by searching the internet for "lua strings".
Here is one result: http://www.lua.org/pil/2.4.html
You are free to choose your own quote style, as it makes no difference, but you should be consistent so that your code is nicer to read.
As a matter of preference, I would normally use double-quotes because Lua uses C-style escape-codes. Many script languages (Perl, for example) and command shells do make the distinction between single- and double-quoted strings, and it would be nice to be a little consistent with these quasi-standard practices.
I mean that when I see a single-quoted string I have to actually think about what language I'm reading, and whether or not escape-codes are substituted in that string. With double-quoted strings I don't have to think about it, because as a general rule any language that substitutes C-style escape-codes in a string will do that in a double-quoted string.

Related

How do I declare a string with both single and double quotes in YAML?

I'm internationalizing an application and cannot figure out how to declare a translation string that contains both single and double quotes. Here's an example of the en.yml string that I am trying to
en:
my_string: When you're using double quotes, they look like "this"
With the above string, I get the following error:
can not load translations from /vagrant/config/locales/en.yml,
expected it to return a hash, but does not
If there were just double quotes, I would wrap it in single quotes and vise-versa. How do I handle both double and single quotes though?
escaping should be done like this
"When you're using double quotes, they look like \"this\""
Actually I can’t figure out why do you need obsolete typewriter quotes in translation strings. There is 2013 around and we are not stuck to ASCII-7 anymore. The typography rules dictate their demands to use unicode quotation marks.
That’s the best practice ever: map those within 3rd keyboard level (or, eventually, sed your yml):
"When you’re using double quotes, they look like “this”"
With such an approach you’ll never run into troubles with escaping and your clients will definitely say “oh, neat.”
Sorry, if this seems a little bit off-topic, but since the question was about translation strings, I still consider it to be the best solution.
See if this works for you, it works perfectly for me in my spring boot applications where I needed to pass JSON values in:
Using YAML pipe style:
app.json:
values: |
{"key": "value"}
Your case would be:
en:
my_string: |
When you're using double quotes, they look like "this"
Folded style might work too but I haven't tried.
See more here: http://symfony.com/doc/current/components/yaml/yaml_format.html#strings

Why everyone use double quotes instead of simple quote?

In ruby using a single quote is faster than double quotes as we can see in the message : Is there a performance gain in using single quotes vs double quotes in ruby?.
So why does everyone use double quotes (or both)???
Some examples :
https://github.com/rails/rails/blob/master/activerecord/test/models/company.rb
https://github.com/sinatra/sinatra/blob/master/test/routing_test.rb
https://github.com/jnicklas/capybara/blob/master/spec/rack_test_spec.rb
(I know, it's not everyone but the majority.)
EDIT 1 : Interpolation is not a reason!
Double quotes are not always with interpolation or anything special like this, in Sinatra :
it "defines HEAD request handlers with HEAD" do
Double quotes allows you to do interpolation : "Number of users : #{#count_user}"
Plus taking a look at the benchmarks, I'd say that at best it doesn't matter, the overhead is very small, and some benchmarks are actually faster with double quotes ...
Double quotes allow for string interpolation, single quotes will not evaluate anything within them while the double quotes will. For example, the double quotes will allow you to have escape characters and single quotes won't!
"he said \n hello"
will result in 2 lines while
'he said \n hello'
will result in a string with '\n' in the middle of it
One reason is that string interpolation is supported in double quotes but not single quotes.
For example:
some_var = 15
"I have #{some_var} cats"
# => "I have 15 cats"
'I have #{some_var} cats"
# => "I have \#{some_var} cats"
I personally prefer single quotes when possible because I think they look cleaner. But string interpolation is one very important reason to use double quotes.
With respect to the performance issue, it's so negligible that it's really a matter of preference rather than performance.
I don't know if you actually read that thread properly but #zetetic actually found that using double quotes is slightly faster. Nonetheless this test was done over 1 million assignments and thus in that regard they'r both basically the same speed.
It all comes down to preference. A lot of people come from languages where single quotation are just not possible and so they are used to double quotations. Its all a matter of preference.
It's been answered and accepted, and some of these are repeating others, but my 2¢ worth.
Using double quotes means that if you ever do want to add something that needs interpolation into a string later, you can just do so without having to change the quotes.
Consistency between strings that do require interpolation and those that don't.
Being able to include all English in a string, eg. "don't", "Jim's" without having to escape it, or change the quotes.
Embedding \ escape chars in strings like \n and \t

Is there any advantage to _ever_ using a single quote around a string in Ruby/Rails?

I understand the functional difference between single and double quotes in Ruby, but I'm wondering what concrete reasons people have for varying between the two. In my mind it seems like you should just always use a double quote, and not think about it.
A couple rationales that I've read in researching the topic...
Use a single quote unless a double quote is required.
There's a very, very minor performance advantage to a single quotes.
Any other interesting thoughts out there? (Or maybe this is a case of the freedom or Ruby leaving the door open for no One Right Way to do something...)
I usually follow the following rule:
never use double quotes (or %Q or %W) if you don't interpolate
The reason for this is that if you're trying to track down an error or a security bug, you immediately know when looking at the beginning of the string that there cannot possibly any code inside it, therefore the bug cannot be in there.
However, I also follow the following exception to the rule:
use double quotes if they make the code more readable
I.e. I prefer
"It's time"
over
'It\'s time'
%q{It's time}
It is technically true that single quoted strings are infinitesimally faster to parse than double quoted strings, but that's irrelevant because
the program only gets parsed once, during startup, there is no difference in runtime performance
the performance difference really is extremely small
the time taken to parse strings is irrelevant compared to the time taken to parse some of Ruby's crazier syntax
So, the answer to your question is: Yes, there is an advantage, namely that you can spot right away whether or not a string may contain code.
I can think of three reasons to use single quoted strings:
They look cleaner (the reason I use them)
They make it easier to create a string you'd otherwise have to escape ('he said "yes"' vs "he said \"yes\"")
They are slightly more performant.
I would assume using a single-quoted string is faster, since double quotes allow string interpolation, and single-quoted strings do not.
That's the only difference I know of. For that reason, it's probably best to only use a single-quoted string unless you need string interpolation:
num = 59
"I ate #{num} pineapples"`
Well, there are a lot of fuzz about the "performance gain" of single quoted strings vs double quoted strings.
The fact is that it doesn't really matter if you don't interpolate. There are a lot of benchmarks around the web that corroborate that assertion. (Some here at stackoverflow)
Personally, I use double for strings that have interpolation just for the sake of readability. I prefer to see the double quotes when I need them. But in fact there are methods in ruby for interpolating strings other than "double quoting" them:
%q{#{this} doesn't get interpolated}
%Q{#{this} is interpolated}
1.9.2-p290 :004 > x = 3
=> 3
1.9.2-p290 :005 > "#{x}"
=> "3"
1.9.2-p290 :006 > '#{x}'
=> "\#{x}"
In any other case, i prefer single quotes, because it's easier to type and just makes the code less overbloated to my eyes.
Since asking this question I've discovered this unofficial Ruby Style Guide that addresses this, and many many more styling questions I've had floating around in my head. I'd highly recommend checking it out.
I found that when putting variables in a string using #{} did not work in single quotes, but did work in double quotes as below.
comp_filnam and num (integer) are the variables I used to create the file name in the file path:
file_path_1 = "C:/CompanyData/Components/#{comp_filnam}#{num.to_s}.skp"

is it ever appropriate to localize a single ascii character

When would it be appropriate to localize a single ascii character?
for instance /, or | ?
is it ever necessary to add these "strings" to the localization effort?
just want to give some people the benefit of the doubt and make sure there's not something I didn't think of.
Generally it wouldn't be appropriate to use something like that except as a graphic element (which of course wouldn't be I18N'd in the first place, much less L10N'd). If you are trying to use it to e.g. indicate a ratio then you should have something like "%d / %d" instead, and localize the whole thing.
Yes, there are cases where these individual characters change in localization. This is not a comprehensive list, just examples I happen to know.
Not every locale uses , to separate thousands and . for the decimal. (However, these will usually be handled by your number formatter. If you do so yourself, you're probably doing it wrong. See this MSDN blog post by Michael Kaplan, Number format and currency format are not always the same.)
Not every language uses the same quotation marks (“, ”, ‘ and ’). See Wikipedia on Non-English Uses of Quotation Marks. (Many of these are only easy to replace if you use full quote marks. If you use the " and ' on your keyboard to mark both the start and end of sentences, you won't know which of two symbols to substitute.)
In Spanish, a question or exclamation is preceded by an inverted ? or !. ¿Question? ¡Exclamation! (Obviously, you can't fix this with a locale substitution for a single character. Any questions or exclamations in your application should be entire strings anyway, unless you're writing some stunningly intelligent natural language generator.)
If you do find a circumstance where you need to localize these symbols, be extra cautious not to accidentally localize a symbol like / used as a file separator, " to denote a string literal or ? for a search wildcard.
However, this has already happened with CSV files. These may be separated by ,, or may be separated by the local list separator. See What would happen if you defined your system's CSV delimiter as being a quotation mark?
In Greek, questions end with a semicolon rather than ?, so essentially the ? is replaced with ; ... however, you should aim to always translate the question as a complete string including question mark anyway.

What is the proper Lua pattern for quoted text?

I've been playing with this for an hour or tow and have found myself at a road block with the Lua pattern matching utilities. I am attempting to match all quoted text in a string and replace it if needed.
The pattern I have come up with so far is: (\?[\"\'])(.-)%1
This works in some cases but, not all cases:
Working: "This \"is a\" string of \"text to\" test with"
Not Working: "T\\\"his \"is\' a\" string\" of\' text\" to \"test\" wit\\\"h"
In the not working example I would like it to match to (I made a function that gets the matches I desire, I'm just looking for a pattern to use with gsub and curious if a lua pattern can do this):
string
a" string" of
is' a" string" of' text
test
his "is' a" string" of' text" to "test" wit
I'm going to continue to use my function instead for the time being, but am curious if there is a pattern I could/should be using and i'm just missing something with patterns.
(a few edits b/c I forgot about stackoverflows formating)
(another edit to make a non-html example since it was leading to assumptions that I was attempting to parse html)
Trying to match escaped, quoted text using regular expressions is like trying to remove the daisies (and only the daises) from a field using a lawnmower.
I made a function that gets the matches I desire
This is the correct move.
I'm curious if a lua pattern can do this
From a practical point of view, even if a pattern can do this, you don't want to. From a theoretical point of view, you are trying to find a double quote that is preceded by an even number of backslashes. This is definitely a regular language, and the regular expression you want would be something like the following (Lua quoting conventions)
[[[^\](\\)*"(.-[^\](\\)*)"]]
And the quoted string would be result #2. But Lua patterns are not full regular expressions; in particular, you cannot put a * after a parenthesized pattern.
So my guess is that this problem cannot be solved using Lua patterns, but since Lua patterns are not a standard thing in automata theory, I'm not aware of any body of proof technique that you could use to prove it.
The issue with escaped quotes is that, in general, if there's an odd number of backslashes before the quote, then it's escaped, and if there's an even number, it's not. I do not believe that Lua pattern-matching is powerful enough to represent this condition, so if you need to parse text like this, then you should seek another way. Perhaps you can iterate through the string and parse it, or you could find each quote in turn and read backwards, counting the backslashes until you find a non-backslash character (or the beginning of the string).
If you absolutely must use patterns for some reason, you could try doing this in a multi-step process. First, gsub for all occurrences of two backslashes in a row, and replace them with some sentinel value. This must be a value that does not already occur in the string. You could try something like "\001" if you know this string doesn't contain non-printable characters. Anyway, once you've replaced all sequences of two backslashes in a row, any backslashes left are escaping the following character. Now you can apply your original pattern, and then finally you can replace all instances of your sentinel value with two backslashes again.
Lua's pattern language is adequate for many simple cases. And it has at least one trick you don't find in a typical regular expression package: a way to match balanced parenthesis. But it has its limits as well.
When those limits are exceeded, then I reach for LPeg. LPeg is an implementation of a Parsing Expression Grammer for Lua, and was implemented by one of Lua's original authors so the adaptation to Lua is done quite well. A PEG allows specification of anything from simple patterns through complete language grammars to be written. LPeg compiles the grammar to a bytecode and executes it extremely efficiently.
you should NOT be trying to parse HTML with regular expressions, HTML and XML are NOT regular languages and can not be successfully manipulated with regular expressions. You should use a dedicated HTML parser. Here are lots of explanations why.

Resources