So I know that if I define a const Nim will evaluate whatever I assign to it at compile time, so I could do something like this:
proc compileTimeCode: bool =
# Put code here
return true
const _ = compileTimeCode()
and then I could put my code in the compileTimeCode proc.
This works, but seems messy, overcomplicated and unintuitive. It also requires more typing than it should, and is difficult to DRY up.
What's the question? If there is a better way to run code at compile time?
static:
# Put code here
Reference
Related
I need to test a feature that includes this line:
if $translate-nl && $*DISTRO.is-win
I have tried to reassign a value to $*DISTRO,
$*DISTRO='Windows 10';
but it says:
Cannot modify an immutable Distro (debian (9.stretch))
$*DISTRO is a dynamic variable, and it makes sense that it's not modified. That said, is there any other way that code can be tested (other than going to Windows, of course)
my $*DISTRO = ...
Hopefully modifying the original is unnecessary. It's generally unreasonable action-at-a-distance -- almost certainly so if someone has arranged for it to be an immutable value. This is the reason why global variables got such a bad reputation.
To elaborate on raiph's answer: the * in $*DISTRO marks it as a dynamic variable. You can re-declare it any scope, and code called from there will see the redeclared value:
{
my $*DISTRO = ...;
# coded called from here sees the redeclared value
}
# code called from here sees the original value
Now, the question remains, what do you put in place of these pesky ...?
In the simplest case, a mock that just has whatever the code under test needs:
{
my class Distro { has $.is-win }
my $*DISTRO = Distro.new( :is-win );
# call your test code here
}
If the code needs more attributes in Distro, just add them to the mock Distro class.
If the code needs a "real* Distro object, for some reason, you can instantiate the built-in one. The constructor .new isn't really documented, but the source code makes it pretty obvious what arguments it expects.
OK, I got the answer relatively fast. $*DISTRO is actually a read-only alias of PROCESS::<$DISTRO>
So we only need to do:
my $*DISTRO = Distro.new(:is-win,:release<11>,:path-sep('|||'),:auth<unknown>,:name<mswin32>,:desc<Test>,:version<v11>);
say $*DISTRO.is-win; #OUTPUT: «True»
In the process of learning Rust, I am getting acquainted with error propagation and the choice between unwrap and the ? operator. After writing some prototype code that only uses unwrap(), I would like to remove unwrap from reusable parts, where panicking on every error is inappropriate.
How would one avoid the use of unwrap in a closure, like in this example?
// todo is VecDeque<PathBuf>
let dir = fs::read_dir(&filename).unwrap();
todo.extend(dir.map(|dirent| dirent.unwrap().path()));
The first unwrap can be easily changed to ?, as long as the containing function returns Result<(), io::Error> or similar. However, the second unwrap, the one in dirent.unwrap().path(), cannot be changed to dirent?.path() because the closure must return a PathBuf, not a Result<PathBuf, io::Error>.
One option is to change extend to an explicit loop:
let dir = fs::read_dir(&filename)?;
for dirent in dir {
todo.push_back(dirent?.path());
}
But that feels wrong - the original extend was elegant and clearly reflected the intention of the code. (It might also have been more efficient than a sequence of push_backs.) How would an experienced Rust developer express error checking in such code?
How would one avoid the use of unwrap in a closure, like in this example?
Well, it really depends on what you wish to do upon failure.
should failure be reported to the user or be silent
if reported, should one failure be reported or all?
if a failure occur, should it interrupt processing?
For example, you could perfectly decide to silently ignore all failures and just skip the entries that fail. In this case, the Iterator::filter_map combined with Result::ok is exactly what you are asking for.
let dir = fs::read_dir(&filename)?;
let todos.extend(dir.filter_map(Result::ok));
The Iterator interface is full of goodies, it's definitely worth perusing when looking for tidier code.
Here is a solution based on filter_map suggested by Matthieu. It calls Result::map_err to ensure the error is "caught" and logged, sending it further to Result::ok and filter_map to remove it from iteration:
fn log_error(e: io::Error) {
eprintln!("{}", e);
}
(|| {
let dir = fs::read_dir(&filename)?;
todo.extend(dir
.filter_map(|res| res.map_err(log_error).ok()))
.map(|dirent| dirent.path()));
})().unwrap_or_else(log_error)
I like to try to optimize my code, and I would like to measure the time taken by a function.
I have a class named Chrono. So I just have to add chrono.start at the beginning of the function, and chrono.stop at the end. My class chan also add the times it measure in a list, to then have average time, total time...
It works. Only problem is when there is exit sub or return in the middle of the function. Not really a problem, I just add a Try at the begginf of the function, and put my chrono.stop in the finally portion. I'm not sure it's really efficient, but it works.
So here is my question : I would like to have a function taking function name as parameter, that will automatically launch and stop my class when this function is called. I have heard of Reflection, but I have no idea how to use it. And it's really hard to search for this question in the internet (because the words are too common : "do something at the end of a function")
To resume, my code works, no problem. It's just constraining to add code to a function for just a short period of time (and sometimes forgot to remove it).
Thx (I'm french and hope I'm understandable)
This is how you can use reflection to call a method by name:
using System.Reflection;
public int InvokeMethod(string name)
{
int time1 = 1; //call your chrono.start here.
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(name);
theMethod.Invoke(this, new object[] { 1 });
int time2 = 10; //call your chrono.end here.
return time2 - time1;
}
However, there is a problem. How will you know what parameters to pass to the function? In the code above, I'm passing the integer 1 (new object[] { 1 }) just for example. So this code cannot be automated, but if you run it manually against each function one by one, then you can change that line to pass the correct arguments and make it work without having to modify your function.
This is to answer your question as how to call a function by name using reflection. However, it is much easier to call it using a delegate (or Fuc<T, tRsult> in .Net v3.5 and higher).
I'm working with a program that has standard Lua 5.1 embedded and am trying to write a module I can call functions from but have had no avail.
The current environment is quite picky, and if I make mistakes the scripts will break but will not get any errors, so here we go:
I have something like this (inside moduletests.lua):
local _ = {}
function _.prints()
HUD.AddUpdateBoxText("Hello World!", 200) --Equivalent to print()
end
I would then attempt to require this and call it with:
mts = require 'moduletests' --seems to cause no issues
mts.prints() --breaks the scripts
Normally if the require function is incorrect, the scripts will break. The scripts work fine with the require, so I assume it is correct, but on any attempt to call the print function it will break.
On the other hand, I have another lua module installed and have been able to successfully require it and call a function and it is what I modeled my module after. This is the module's code.
Here is how I used it:
moses = require 'moses' --Works
local bok = moses.isInteger(6)
HUD.AddUpdateBoxText(tostring(bok), 700); --Works, outputs "true"
And this worked fine, perfectly as intended. Can someone tell me what is different or wrong with my module, or have any suggestions on how I could make a better functional version of this?
Thank you to everyone, I sincerely appreciate the help!
Much appreciated!
In Lua modules, you have to return something. The reason your code isn't working is because you are trying to call a method from whatever is returned by the module, but since nothing is being returned, an error can only be expected. Try returning the table:
local ar = {}
function ar.prints()
HUD.AddUpdateBoxText("Hello World!", 200) --Equivalent to print()
end
return ar
I recently got into Computer Craft (Mod for Minecraft) you can code the computers with lua.
I want to go "water status" and it will load "water" and then set a variable to "status" or any other word/string in its place so I can use it for anything. I guess you would call that a parameter?
os.run( environment, prgmpath, arguments )
I don't understand what environment is. prgmpath is water and the argument would be status?
I'm just unsure how to grab those arguments from that.
So yeah, I'm quite confused =/
Tried to explain it best I could, thanks,
Jazza
After searching around, I think I found my answer.
lua water arg1
Goes in the command line
derp = arg[2]
Goes in the file?
EDIT: After lurking around some more, I found out that:
derp = ...
print(derp)
In the file and:
file hi
It printed hi, so I guess that works, but I can't seem to add any more D=
os.run is an extension to the os library written specifically for that mod. according to the documentation on the wiki:
environment is the metatable to set up the state for the script you're running at prgmpath
arguments is whatever you want to pass to the code you're calling located in the script at prgmpath
so basically, if you had some code set up to do something specific in path/to/file.lua, but it depended on some outside state, you'd set up that state in your calling file, and pass the environment (or a subset of it) to the code in file.lua by passing it as a table to the first param in os.run().
arguments is supposed to be a table of arguments you wanted to pass to the function you'd be calling in file.lua. so if in file.lua you had...
function doSomething(arg1, arg2, arg3)
...
end
you'd pass arg1, arg2, and arg3 to doSomething by creating a table and passing it like this...
local args = {"arg1Val", {}, 1234}
os.run({}, '/path/to/file.lua', args)
os.run would then set up an empty environment for function doSomething() in file.lua, and pass the 3 values in args to the function.
make sense?