How do you read a variable from another variable - variables

Horse_Apple = "Happy Horse"
local var = Animal() .. "_" .. Food()
print(var)
I hope someone here understands the problem i'm trying to solve here. Animal() returns "Horse" and Food() returns "Apple".
What i'm attempting to do is read the variable 'var' and read its value 'Horse_Apple' as a variable which should return "Happy Horse". As much as im trying to find the solution to this im failing big time, Thank you.

You can access a global variable by a dynamic name using _G, i.e.:
print(_G[var])
Normally this isn't considered good design: It's better to make Horse_Apple a key in some table and access that table instead, like this:
values = { Horse_Apple="Happy Horse" }
local var = Animal() .. "_" .. Food()
print values[var]

Related

DBArrayList to List<Map> Conversion after Query

Currently, I have a SQL query that returns information to me in a DBArrayList.
It returns data in this format : [{id=2kjhjlkerjlkdsf324523}]
For the next step, I need it to be in a List<Map> format without the id: [2kjhjlkerjlkdsf324523]
The Datatypes being used are DBArrayList, and List.
If it helps any, the next step is a function to collect the list and then to replace all single quotes if any [SQL-Injection prevention]. Using:
listMap = listMap.collect() { "'" + Util.removeSingleQuotes(it) + "'" }
public static String removeSingleQuotes(s) {
return s ? s.replaceAll(/'"/, '') : s
}
I spent this morning working on it, and I found out that I needed to actually collect the DBArrayList like this:
listMap = dbArrayList.collect { it.getAt('id')}
If you're in a bind like I was and restrained to a specific schema this might help, but #ou_ryperd has the correct answer!
While using a DBArrayList is not wrong, Groovy's idiom is to use the db result as a collection. I would suggest you use it that way directly from the db:
Map myMap = [:]
dbhandle.eachRow("select fieldSomeID, fieldSomeVal from yourTable;") { row ->
map[row.fieldSomeID] = row.fieldSomeVal.replaceAll(/'"/, '')
}

Getting the name of the variable as a string in GD Script

I have been looking for a solution everywhere on the internet but nowhere I can see a single script which lets me read the name of a variable as a string in Godot 3.1
What I want to do:
Save path names as variables.
Compare the name of the path variable as a string to the value of another string and print the path value.
Eg -
var Apple = "mypath/folder/apple.png"
var myArray = ["Apple", "Pear"]
Function that compares the Variable name as String to the String -
if (myArray[myposition] == **the required function that outputs variable name as String**(Apple) :
print (Apple) #this prints out the path.
Thanks in advance!
I think your approach here might be a little oversimplified for what you're trying to accomplish. It basically seems to work out to if (array[apple]) == apple then apple, which doesn't really solve a programmatic problem. More complexity seems required.
First, you might have a function to return all of your icon names, something like this.
func get_avatar_names():
var avatar_names = []
var folder_path = "res://my/path"
var avatar_dir = Directory.new()
avatar_dir.open(folder_path)
avatar_dir.list_dir_begin(true, true)
while true:
var avatar_file = avatar_dir.get_next()
if avatar_file == "":
break
else:
var avatar_name = avatar_file.trim_suffix(".png")
avatar_names.append(avatar_name)
return avatar_names
Then something like this back in the main function, where you have your list of names you care about at the moment, and for each name, check the list of avatar names, and if you have a match, reconstruct the path and do other work:
var some_names = ["Jim","Apple","Sally"]
var avatar_names = get_avatar_names()
for name in some_names:
if avatar_names.has(name):
var img_path = "res://my/path/" + name + ".png"
# load images, additional work, etc...
That's the approach I would take here, hope this makes sense and helps.
I think the current answer is best for the approach you desire, but the performance is pretty bad with string comparisons.
I would suggest adding an enumeration for efficient comparisons. unfortunately Godot does enums differently then this, it seems like your position is an int so we can define a dictionary like this to search for the index and print it out with the int value.
var fruits = {0:"Apple",1:"Pear"}
func myfunc():
var myposition = 0
if fruits.has(myposition):
print(fruits[myposition])
output: Apple
If your position was string based then an enum could be used with slightly less typing and different considerations.
reference: https://docs.godotengine.org/en/latest/tutorials/scripting/gdscript/gdscript_basics.html#enums
Can't you just use the str() function to convert any data type to stirng?
var = str(var)

Rust Arc/Mutex Try Macro Borrowed Content

I'm trying to do several operations with a variable that is shared across threads, encapsulated in an Arc<Mutex>. As not all of the operations may be successful, I'm trying to use the try! macro, or the ? operator, to auto-propagate the errors.
Here's a minimum viable example of my code:
lazy_static! {
static ref BIG_NUMBER: Arc<Mutex<Option<u32>>> = Arc::new(Mutex::new(Some(174)));
}
pub fn unpack_big_number() -> Result<u32, Box<Error>> {
let big_number_arc = Arc::clone(&BIG_NUMBER);
let mutex_guard_result = big_number_arc.lock();
let guarded_big_number_option = mutex_guard_result?;
let dereferenced_big_number_option = *guarded_big_number_option;
let big_number = dereferenced_big_number_option.unwrap();
// do some subsequent operations
let result = big_number + 5;
// happy path
Ok(result)
}
You will notice that in the line where I declare guarded_big_number_option, I have a ? at the end. This line is throwing the following compiler error (which it does not when I replace the ? with .unwrap():
error[E0597]: `big_number_arc` does not live long enough
--> src/main.rs:32:30
|
7 | let mutex_guard_result = big_number_arc.lock();
| ^^^^^^^^^^^^^^ borrowed value does not live long enough
...
17 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
Now the thing is, it is my understanding that I'm not trying to use big_number_arc beyond its lifetime. I'm trying to extract a potential PoisonError contained within the result. How can I properly extract that error and make this propagation work?
Additionally, if it's any help, here's a screenshot of the type annotations that my IDE, CLion, automatically adds to each line:
lock() function returns LockResult<MutexGuard<T>>. Documentation says the following:
Note that the Err variant also carries the associated guard, and it can be acquired through the into_inner method
so you're essentially trying to return a reference to a local variable (wrapped into PoisonError struct), which is obviously incorrect.
How to fix it? You can convert this error to something with no such references, for example to String:
let guarded_big_number_option = mutex_guard_result.map_err(|e| e.to_string())?;

Stata: for loop for storing values of Gini coefficient

I have 133 variables on income (each variable represents a group). I want the Gini coefficients of all these groups, so I use ineqdeco in Stata. I can't compute all these coefficients by hand so I created a for loop:
gen sgini = .
foreach var of varlist C07-V14 {
forvalue i=1/133 {
ineqdeco `var'
replace sgini[i] = $S_gini
}
}
Also tried changing the order:
foreach var of varlist C07-V14 {
ineqdeco `var'
forvalue i=1/133 {
replace sgini[i] = $S_gini
}
}
And specifying i beforehand:
gen i = 1
foreach var of varlist C07-V14 {
ineqdeco `var'
replace sgini[i] = $S_gini
replace i = i+1
}
}
I don't know if this last method works anyway.
In all cases I get the error: weight not allowed r(101). I don't know what this means, or what to do. Basically, I want to compute the Gini coefficient of all 133 variables, and store these values in a vector of length 133, so a single variable with all the coefficients stored in it.
Edit: I found that the error has to do with the replace command. I replaced this line with:
replace sgini = $S_gini in `i'
But now it does not "loop", so I get the first value in all entries of sgini.
There is no obvious reason for your inner loop. If you have no more variables than observations, then this might work:
gen sgini = .
gen varname = ""
local i = 1
foreach var of varlist C07-V14 {
ineqdeco `var'
replace sgini = $S_gini in `i'
replace varname = "`var'" in `i'
local i = `i' + 1
}
The problems evident in your code (seem to) include:
Confusion between variables and local macros. If you have much experience with other languages, it is hard to break old mental habits. (Mata is more like other languages here.)
Not being aware that a loop over observations is automatic. Or perhaps not seeing that there is just a single loop needed here, the twist being that the loop over variables is easy but your concomitant loop over observations needs to be arranged with your own code.
Putting a subscript on the LHS of a replace. The [] notation is reserved for weights but is illegal there in any case. To find out about weights, search weights or help weight.
Note that with this way of recording results, the Gini coefficients are not aligned with anything else. A token fix for that is to record the associated variable names alongside, as done above.
A more advanced version of this solution would be to use postfile to save to a new dataset.

how to make a function that prints a variable number of parameters in pascal?

I want to let the user give me a variable number of strings (as virables).
example :
begin
cout('Hello').(' ').('world')
end.
this will print: "Hello world"
I know I just can let him input a string but I want to this code to work...
I think a record will help nut I dont know how
thank you
Im not sure what is that code example you have written ... but i try to help you.
Program test;
uses crt;
var string1,string2,string3:string;
begin
write("Write to first string : "); readln(string1);
write("Write to second string: "); readln(string2);
write("Write to third string : "); readln(string3);
String2:= string1 +" "+ string3; // it will add first with third string to one with one space
String3:= string2 +" "+ string1;// also 2.+ 1.
clrscr; //clearscreen (in CRT)
writeln("1. = 1.");
writeln("2. = 1. + 3.");
writeln("3. = 2. + 1.");
writeln;
writeln(string1);
writelm(string2);
writeln(string3);
I havent tested this (i have written it now for you) i think you will read it and learn how to addict or how to do simple with strings.