Convert string to table in lua [duplicate] - string

This question already has answers here:
String to Table in Lua
(2 answers)
Closed 9 years ago.
I am newbie in lua. I need to convert following string to lua table. How could I do this?
str = "{a=1, b=2, c={d=3,e=4} }"
I want to convert this string to lua table, so that I can access it like this:
print(str['a']) -- Output : 1
print(str['c']['d']) -- Output : 3

You could simply add a str = to the beginning of the string and let the interpreter load that string as a chunk for you. Note that loadstring doesn't run the chunk but returns a function. So you add () to call that function right away and actually execute the code:
loadstring("str = "..str)()
This would do the same thing:
str = loadstring("return "..str)()
If you don't generate the string yourself, that can be dangerous though (because any code would be executed). In that case, you might want to parse the string manually, to make sure that it's actually a table and contains no bad function calls.

Related

Why does split() return one extra item? [duplicate]

This question already has answers here:
Why are empty strings returned in split() results?
(9 answers)
Closed 2 years ago.
I have this String and I want to separate it using the specified separator. Why is the length 4 instead of 3?
brain = " Know yourself! Understand yourself! Correct yourself! "
brain = brain.strip()
change = brain.split("yourself!")
print(len(change))
Because of your word that you want to split with that (yourself!) is at the end(or at the first) of your string.
you can try this solution :
def is_not_none(element):
if element is not None:
return element
brain = "know yourself! Understand yourself! Correct yourself! "
brain = brain.strip()
brain = list(filter(is_not_none, brain.rsplit('yourself!')))
print(brain)

Convert a String representation of number to Integer in Java 8+(single line without if) [duplicate]

This question already has answers here:
How do I convert a String to an int in Java?
(47 answers)
Closed 4 years ago.
This sounds simple, but I can't find a way to convert a String value(possibly null) to Integer in single line without using if else in Java 8+. The answer might involve usage of ofNullable and isPresent.
Some things I have tried:
String x = ...;
Integer.valueOf(x); // fails if x is null
Optional.ofNullable(Integer.valueOf(x)).orElse(null); // NullPointerException
int value = Optional.ofNullable(x).map(Integer::parseInt).orElse(0);
This will result in a default value of 0 if the input String is null.
As an alternative, use:
Integer value = Optional.ofNullable(x).map(Integer::valueOf).orElse(null);
which will result in null if the input String is null.
What about using ? operator instead of one line if...else?
Integer value = x != null ? Integer.valueOf(x) : null;

Swift 3.0 String concatenation leaves "Optional" [duplicate]

This question already has an answer here:
Swift 3 incorrect string interpolation with implicitly unwrapped Optionals
(1 answer)
Closed 6 years ago.
Since Swift 3.0 I have some troubles with Strings, especially with concatenation. 1st example would be what I used since I started using Swift to define my url strings.
internal let host: String! = "https://host.io/"
let urlString = "\(host)oauth/access_token"
where host is defined as at the beginning of the class. This worked perfectly until Swift 3.0, now that prints out like this:
Optional("https://host.io/")oauth/access_token
which is very strange. Now I have to write this
let urlString = host + "oauth/access_token"
To get the expected output.
https://host.io/oauth/access_token
Another - I guess similar problem I'm having with Strings is this. I'm again concatenating strings but this time I'm using + ilke with urlString - but this time that doesn't work. Line of code looks like this:
self.labelName.text = currentUser.name + " " + String(describing: ageComponents.year)
which unfortunately produces string like this: "My Name Optional(26)". In this case I don't have a solution String(describing: ageComponents.year) is not an optional and it doesn't allow me to do things like String(describing: ageComponents.year) ?? "whatever"
Anyone seen something similar?
In Swift 3 all properties of the native struct DateComponents are optionals unlike the Foundation NSDateComponents counterparts.
var year: Int? { get set }
You need to unwrap it. If you specified the unit year in ageComponents you can do that safely.

how to convert a variable to string in matlab? [duplicate]

This question already has answers here:
print variable-name in Matlab
(4 answers)
Closed 9 years ago.
I have structure array
some_struct_var=struct( 'filed1', filed1, 'filed2', filed2 ,...)
I want to create a string
str=['The struct variable name is :' , some_struct_var]
with the name of the structure variable in it. The some_struct_var may vary and is not fixed.
Create a function that takes any variable as an input and returns the string equivalent of that variable's name as an ouput like so:
varToStr = #(x) inputname(1);
structVarString = varToStr(some_struct_var)
str = ['The struct variable name is :', structVarString]

repeat string with LINQ/extensions methods [duplicate]

This question already has answers here:
Is there an easy way to return a string repeated X number of times?
(21 answers)
Closed 9 years ago.
Just a curiosity I was investigating.
The matter: simply repeating (multiplying, someone would say) a string/character n times.
I know there is Enumerable.Repeat for this aim, but I was trying to do this without it.
LINQ in this case seems pretty useless, because in a query like
from X in "s" select X
the string "s" is being explored and so X is a char. The same is with extension methods, because for example "s".Aggregate(blablabla) would again work on just the character 's', not the string itself. For repeating the string something "external" would be needed, so I thought lambdas and delegates, but it can't be done without declaring a variable to assign the delegate/lambda expression to.
So something like defining a function and calling it inline:
( (a)=>{return " "+a;} )("a");
or
delegate(string a){return " "+a}(" ");
would give a "without name" error (and so no recursion, AFAIK, even by passing a possible lambda/delegate as a parameter), and in the end couldn't even be created by C# because of its limitations.
It could be that I'm watching this thing from the wrong perspective. Any ideas?
This is just an experiment, I don't care about performances, about memory use... Just that it is one line and sort of autonomous. Maybe one could do something with Copy/CopyTo, or casting it to some other collection, I don't know. Reflection is accepted too.
To repeat a character n-times you would not use Enumerable.Repeat but just this string constructor:
string str = new string('X', 10);
To repeat a string i don't know anything better than using string.Join and Enumerable.Repeat
string foo = "Foo";
string str = string.Join("", Enumerable.Repeat(foo, 10));
edit: you could use string.Concat instead if you need no separator:
string str = string.Concat( Enumerable.Repeat(foo, 10) );
If you're trying to repeat a string, rather than a character, a simple way would be to use the StringBuilder.Insert method, which takes an insertion index and a count for the number of repetitions to use:
var sb = new StringBuilder();
sb.Insert(0, "hi!", 5);
Console.WriteLine(sb.ToString());
Otherwise, to repeat a single character, use the string constructor as I've mentioned in the comments for the similar question here. For example:
string result = new String('-', 5); // -----
For the sake of completeness, it's worth noting that StringBuilder provides an overloaded Append method that can repeat a character, but has no such overload for strings (which is where the Insert method comes in). I would prefer the string constructor to the StringBuilder if that's all I was interested in doing. However, if I was already working with a StringBuilder, it might make sense to use the Append method to benefit from some chaining. Here's a contrived example to demonstrate:
var sb = new StringBuilder("This item is ");
sb.Insert(sb.Length, "very ", 2) // insert at the end to append
.Append('*', 3)
.Append("special")
.Append('*', 3);
Console.WriteLine(sb.ToString()); // This item is very very ***special***

Resources