I am working on a script that allows user entry of Lua (specifically, boolean conditionals), and I am trying to provide a feature that will perform a quick error check for the script that is entered.
It's easy enough to throw an error if loadstring() fails, so syntax issues are readily handled.
However, if variables are improperly entered, it is harder to detect a problem.
Let's say the user enters the following:
value.custom_value_1 == 1 and valse.custom_value_2 ~= 1
As far as the syntax goes, loadstring() is quite satisfied -- it adds 'return ' as a prefix to that string.
My next step is to check for errors when we execute what was entered by the user. The problem is, when value.custom_value_1 ~= 1, the logic will short-circuit since we're dealing with and - there's no point in going further, we already have false on the left-hand side.
What I would like is to find a way to cause Lua to completely evaluate the expression, rather than short-circuiting. If it did so, the spelling error valse would be caught (regardless of value.custom_value_1's value) and I can provide an error message to the end user.
Any thoughts?
My current best idea is to filter through the user input, sorting out every value entered (basically, whatever's not an a conditional or, and, ...) and just doing it manually. But I thought it's worth checking to see if there's a better way.
Preventing short-circuit evaluation is not something you would want to / could do. That's just the way it works.
What you could do instead is something like:
if(logic1 and logic2)
{
// code on success
}
else
// check what kind of error we have
{
if(~logic1)
{
// throw error type 1
}
if(~logic2)
{
// throw error type 2
}
}
If you don't mind parsing the string up-front you could use a library like https://github.com/stravant/LuaMinify/blob/master/ParseLua.lua to parse the source into an AST, modify the short-circuiting notes into function calls like
function my_and(x, y)
return x and y
end
Then you compile this AST to check for the errors.
Seems a lot hassle though just to catch trivial errors.
I'm not sure if anyone's answer was accurate, but the literal question was 'can you prevent short-circuit evals' and I was not able to find a way to do that.
I ultimately chopped up the user input and tested each component individually, gathering those errors and feeding them back to the user. Seems okay for now.
Related
I am doing a number of business logic checks within the mutateAndGetPayload function of a relay mutation using the graphql-relay library. For any of these checks that fail I have an else clause that will throw an error, ig throw('You do not have permission to delete this resource');, however, when that happens, I get the error Cannot set property 'clientMutationId' of undefined returned to the frontend instead of the error I'm trying to return. It seems that I'm seeing this error because I'm not returning something this mutation cares about (or a promise that resolves to one), so I'm a little stumped ... what's the proper way to throw/return errors back to the client here?
One way is to use the GraphQLError Type
Working in NodeJS on the back end we have used the following library:
https://github.com/graphql/graphql-js/tree/master/src/error
However, what we have ended up using is a library that provides more flexibility:
https://github.com/kadirahq/graphql-errors
Either of these would be the best place to start.
Hi I'm trying to verify the user email with parse, I been searching the entire web for hours and have found nothing. Everything else with parse is working great! but when I trying to check if the email verification is true, I get this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
basically I'm trying to check that first so I can change to a different viewController, the code that I'm using right now is this...
if user.objectForKey("emailVerified")!.boolValue == true
{
performSegueWithIdentifier("tarjetaCredito",sender: self)
}
I been trying all type of code and I always get the same error, any help? I'm using Xcode 7.0 beta 6
When you see “unexpectedly found nil” in Swift, you can trace it to an exclamation point. (Whether it’s a bare ! or as! or try!, the exclamation point essentially says, “Hey compiler, I know you think an error could happen here, but I know it will never actually happen, so don’t force me to deal with the error case.”)
In your code, the ! is right here:
if user.objectForKey("emailVerified")!.boolValue == true
⬆︎
…which means that the result of the expression user.objectForKey("emailVerified") must be nil. Figure out why that expression is nil, and you’ll have your answer.
If user is a Dictionary, then perhaps there is no value for the key "emailVerified", and perhaps you are using the wrong key string. (Aside: you may be able to say user["emailVerified"] instead, depending on what the type of user is.)
Whatever the cause, printing out the value of user on the line before the crash is likely to help you diagnose the problem:
print("----------> user = ", user)
if user.objectForKey("emailVerified")!.boolValue == true
...
In general, it is often good practice in Swift to avoid using ! — or at least carefully consider why you are using it. If you determine that it is sometimes valid for that expression to evaluate to nil — for example, it might be nil if the email is not validated yet — then you might use ? instead; for example:
if user.objectForKey("emailVerified")?.boolValue == true
Please note I'm using a nightly build of Rust 0.13.0
First off, I'm a beginner to Rust and am still in the process of consuming as much information as possible on the language. Throughout my consumption the one topic I've been able to find very little on is error handling. So, when I first attempted to use an external library in my code I became quickly stumped at how I should be using the material being returned to me.
To help explain my confusion, I will be referencing the rust-url library. Here is some sample code found in the documentation:
use url::{Url, InvalidIpv6Address};
assert!(Url::parse("http://[:::1]") == Err(InvalidIpv6Address))
This is pretty straight-forward to me. However, my next question was: what about the other errors? I looked further into the ParseError enum and found 15+ other types of errors that could be potentially produced by a malformed URL.
So, my question is, what is considered the proper way to handle all of these various conditions? Should I have a lengthy match that alerts out specialized messages for each one? Is there a way to consume them all at once?
I apologize if there is not a single answer to this question, but Google was not making it clear and I would prefer to have feedback on this before I proceed coding the rest of my project the wrong way.
The ParseError enum implements the Show trait, with a custom useful message for each variant, so when you get to the final step of actually handling the parse error (e.g. after manipulating the Result in whatever ways you see fit), you can just treat the error possibilities as a black box:
fn download(s: &str) {
match Url::parse(s) {
Ok(url) => { ... }
Err(e) => {
println!("Could not parse '{}'. {}.", s, e);
}
}
}
will print things like Could not parse 'http://[:::1]'. Invalid IPv6 address..
(I filed #43 about making the Show message lower-cased, so that it flows better in more complicated error messages.)
Url::parse returns ParseResult<Url> which is defined as Result<Url, ParseError>, so you can make use of generic Result methods:
use url::{Url, InvalidIpv6Address};
assert!(Url::parse("http://[:::1]").is_err());
Result is Rust's preferred method for error handling, and has many convenience methods under the hood. For example, if you don't expect the failure you can use .unwrap() to make any failure fatal. When they don't suit your needs, you can also match against the Result.
I've been poring over this subject for the past 12 hours, and I simply cannot seem to get anywhere. I do not even know if this is possible, but I'm hoping it is because it would go a long way to continuing my project.
What I am attempting to do is create coroutines so the particular program I use does not freeze up due to its inability to perform asynchronous http requests. I've figured out how to do that part, even though my understanding of coroutines is still in the "Huh? How does that work?" phase. My issue now is being able to respond to multiple requests with the correct information. For instance, the following should produce three separate responses:
foo(a)
foo(b)
foo(c)
where foo initiates a coroutine with the parameters inside. If all requested separately, then it returns the proper results. However, if requested as a block, it will only return foo(c)'s result. Now, I understand the reasoning behind this, but I cannot find a way to make it return all three results when requested as a block. To help understand this problem a bit, here's the actual code:
function background_weather()
local loc = url.escape(querystring)
weatherpage = http.request("http://api.wunderground.com/api/004678614f27ceae/conditions/q/" .. loc .. ".json")
wresults = json.decode(weatherpage)
--process some stuff here, mainly datamining
end
--send datamined information as a response
coroutine.yield()
end
And the creation of the coroutine:
function getweather ()
-- see if backgrounder running
if background_task == nil or
coroutine.status (background_task) == "dead" then
-- not running, create it
background_task = coroutine.create (background_weather)
-- make timer to keep it going
AddTimer ("tickler", 0, 0, 1, "",
timer_flag.Enabled + timer_flag.Replace,
"tickle_it")
end -- if
end -- function
The querystring variable is set with the initial request. I didn't include it here, but for the sake of testing, use 12345 as the querystring variable. The timer is something that the original author of the script initialized to check if the coroutine was still running or not, poking the background every second until done. To be honest, I'm not even sure if I've done this correctly, though it seems to run asynchronously in the program.
So, is it possible to receive multiple requests in one block and return multiple responses, correctly? Or is this far too much a task for Lua to handle?
Coroutines don't work like that. They are, in fact, blocking.
The problem coroutines resolve is "I want to have a function I can execute for a while, then go back to do other thing, and then come back and have the same state I had when I left it".
Notice that I didn't say "I want it to keep running while I do other things"; the flow of code "stops" on the coroutine, and only continues on it when you go back to it.
Using coroutines you can modify (and in some cases facilitate) how the code behaves, to make it more evident or legible. But it is still strictly single-threaded.
Remember that what Lua implements must be specified by C99. Since this standard doesn't come with a thread implementation, Lua is strictly single-threaded by default. If you want multi-threading, you need to hook it to an external lib. For example, luvit hooks Luajit with the libuv lib to achieve this.
A couple good references:
http://lua-users.org/wiki/CoroutinesTutorial
http://lua-users.org/wiki/ThreadsTutorial
http://lua-users.org/wiki/MultiTasking
http://kotisivu.dnainternet.net/askok/bin/lanes/comparison.html
Chapter 9.4 of Programming in Lua contains a fairly good example of how to deal with this exact problem, using coroutines and LuaSocket's socket.select() function to prevent busylooping.
Unfortunately I don't believe there's any way to use the socket.http functions with socket.select; the code in the PiL example is often all you'll need, but it doesn't handle some fairly common cases such as the requested URL sending a redirect.
I'm currently creating a search function in lua which basically just goes through a list of items and processes the items that match the input string in a specific way.
I use string.find(sourceString, inputString) to identify the items.
The function is called whenever a user types something into a text field so if he tries to enter a pattern it happens that when using sets or captures the function is called when the search string just contains a [ or a ( without the closing equivalent which of cause throws an error.
The best way to go around this problem I think is to validate the input as beeing a valid pattern, but I've got no idea how to do this. Lua itself doesn't seem to contain a method for this and I am a bit confused of how to check it in a more or less performant way myself. Thanks for your help and ideas in advance :)
You should wrap the call to string.find with pcall to capture the error.
local status, result = pcall(string.find, sourceString, inputString)
if not status then
-- bad pattern logic, error message is in result
else
-- good pattern logic, result contains the start index
end
See this for pattern escape function (taken from somewhere in Lua Users wiki, I think). You may convert it to the validation function if you need.