how do I define c style code blocks in lua? - c

is there a way to define {} and blankspace as a lua code block?
something like this..
function()
{
local x = 3
if (x == 1) { print("hi1") }
elseif (x == 2) print("hi2")
else (x == 3) print("hi3")
}
it would also be nice to define things like ++ and += too

Just use do..end. += operator and friends aren't conformant with spirit of Lua. Your code will not run. First of all, you need to understand basic Lua syntax. Example of corrected code:
function f()
local x = 3
if x == 1 then
print("hi1")
elseif x == 2 then
print("hi2")
elseif x == 3 then
print("hi3")
end
end
To create block simply use
do
print('Hello, world!')
end
You can check out Lua manual here, whenever you run to trouble.

Related

Testing intermediate variables in a large file using Frama-c

I am trying to use Frama-c to check some properties of a C function that I have. The function is quite large and there are some intermediate variables that I need to check. (I am following this and this manual)
My program has the following structure:
There are 15 return statements spread throughout the program.
The variables I need to check are assigned values at several places in the program, depending on the path of the program.
my_function(){
intermediate var 1=xx;
//#assert var 1>some_value;
intermediate var 2=yy;
return var 4;
intermediate var 1=xx;
//#assert var 1>some_value;
return var 4;
intermediate var 2=xx;
intermediate var 1=yy;
//#assert var 1>some_value;
return var 4;
}
Explanation: I need to check certain properties related to var 1, var 2 and var 4. I tried 2 approaches.
use assert whenever var 1 is set as above.
Problem with this was that Frama-C checks only the first assert.
use annotations in the beginning.
/*# requires \valid(var 1);
ensures var 1 > some_value;
*/
In this case, Frama-C returns an error.
Question: How can I check the properties for intermediate problems? Is there a sample program?
*I haven't included my original function as it is very long.
As Virgile has mentioned, your question is not very clear, but I assume you are trying to validate some properties of var1 and var2.
This book provides some nice examples and I think the following should help you.
int abs(int val){
int res;
if(val < 0){
//# assert val < 0 ;
res = - val;
//# assert \at(val, Pre) >= 0 ==> res == val && \at(val, Pre) < 0 ==> res == -val;
} else {
//# assert !(val < 0) ;
res = val;
//# assert \at(val, Pre) >= 0 ==> res == val && \at(val, Pre) < 0 ==> res == -val;
}
return res;
}
The author has used the concept of Hoare triples in this scenario, where you check (assert) a certain property by asserting its requirements (pre-condition) for a property and check if a property holds after the corresponding statements are executed.
Hope this helps.

Try/catch in a game loop

I have this little guessing game code. In order to deal with the string input, I used try/catch blocks. Try works perfectly, but catch-block is outside of the loop and I can't seem to make it work inside. So the program stops after catching an exception. What should I do so that my loop continues after catching an exception?
fun main(args: Array<String>) {
val rand = java.util.Random()
val n = 1 + rand.nextInt(100)
var guess: Int
var numberOfTries = 0
println("I guessed a number from 1 до 100. What is it?\n")
try {
do {
guess = readLine()!!.toInt()
var x = Math.abs(n - guess)
numberOfTries++
when (x) {
in 1..3 -> println("А-а-аh! It's burning!")
in 4..7 -> println("Really hot!")
in 8..15 -> println("Warm")
in 16..31 -> println("A bit warm!")
in 32..63 -> println("Pretty cold")
in 64..99 -> println("It's freezing!")
}
} while (guess != n)
} catch (e: NumberFormatException) {
println("Use digits, please!") }
println("Wow! You only used $numberOfTries tries!")
}
As MFazio23 mentioned, you use the try inside the while loop. Otherwise, it will exit the loop if an exception is thrown.
If an exception is thrown, anything inside is halted, which includes further code. if you have a method that throws an exception, no code after it will be executed. The try-catch creates an entry-point for the exception; your code will continue inside the relevant catch block (or exit the program if there is none), which means the loop inside the try-catch will stop.
However, you actually don't need the try-catch at all. Kotlin has a nice extension function called toIntOrNull, which does exactly what you'd expect; it attempts to convert the input to an int, and returns the number, or null if it failed. So, you can do this:
fun main(args: Array<String>) {
val rand = java.util.Random()
val n = 1 + rand.nextInt(100)
var guess: Int?
var numberOfTries = 0
println("I guessed a number from 1 до 100. What is it?\n")
do {
guess = readLine()?.toIntOrNull() // Note that this now uses ?. instead of !!. This is to make the null check useful If it throws an NPE, it kinda defeats the point. If the line is null, it now prints the same message as an invalid number
// numberOfTries++ // move this up here if you want to count invalid guesses as a guess
if(guess == null){
System.out.println("Only use numbers")
continue;
}
val x = Math.abs(n - guess)// I also changed this to a val; it's immutable, so it doesn't need to be a var
numberOfTries++
when (x) {
in 1..3 -> println("А-а-аh! It's burning!")
in 4..7 -> println("Really hot!")
in 8..15 -> println("Warm")
in 16..31 -> println("A bit warm!")
in 32..63 -> println("Pretty cold")
in 64..99 -> println("It's freezing!")
}
} while (guess != n)
println("Wow! You only used $numberOfTries tries!")
}
You can also optimize it further, but using an extension function/variable (I'm not sure what it is, it's a variable declared as an extension function, but since there's a getter too, I'm not sure what to call it) called absoluteValue.
You could also use if-statements, but it is slightly more boilerplate than using this. You cannot call Math.abs with null, because it uses primitives. Primitives in Java can never be null.
Which means anything you pass you the method cannot be null, which in Kotlin means for an instance Int. If it's nullable, it's an Int?, but the method requires non-null from Kotlin. You can't pass Int? to Int (you can do it the other way around, but that's not relevant here).
Under the hood, .absoluteValue calls Math.abs(n), but since it's a call, you can use the null-safe operator (?.)
guess = readLine()?.toIntOrNull()
val x = guess?.absoluteValue
numberOfTries++
when (x) {
in 1..3 -> println("А-а-аh! It's burning!")
in 4..7 -> println("Really hot!")
in 8..15 -> println("Warm")
in 16..31 -> println("A bit warm!")
in 32..63 -> println("Pretty cold")
in 64..99 -> println("It's freezing!")
null -> println("Please only use numbers")
}
And now that x is nullable, you can add null to the when statement (in response to your comment).
Also, if you only want numberOfTries to increment on valid numbers, add an if(x != null) before you call it.
You should be able to add the try...catch block right in your do...while. The only other change needed would be to initialize guess with a value (since it's not guaranteed to be set before the while block is hit):
val rand = java.util.Random()
val n = 1 + rand.nextInt(100)
var guess = 0
var numberOfTries = 0
println("I guessed a number from 1 до 100. What is it?\n")
do {
try {
guess = readLine()!!.toInt()
val x = Math.abs(n - guess)
numberOfTries++
when (x) {
in 1..3 -> println("А-а-аh! It's burning!")
in 4..7 -> println("Really hot!")
in 8..15 -> println("Warm")
in 16..31 -> println("A bit warm!")
in 32..63 -> println("Pretty cold")
in 64..99 -> println("It's freezing!")
}
} catch (e: NumberFormatException) {
println("Use digits, please!")
}
} while (guess != n)
println("Wow! You only used $numberOfTries tries!")

Array.tabulate StackOverFlowError

I'm new to Scala and I was playing around with the Array.tabulate method. I am getting a StackOverFlowError when executing this simplified piece of code snippet (originally a dp problem).
import Lazy._
class Lazy[A](x: => A) {
lazy val value = x
}
object Lazy {
def apply[A](x: => A) = new Lazy(x)
implicit def fromLazy[A](z: Lazy[A]): A = z.value
implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
}
def tabulatePlay(): Int = {
lazy val arr: Array[Array[Lazy[Int]]] = Array.tabulate(10, 10) { (i, j) =>
if (i == 0 && j == 0)
0 // some number
else
arr(0)(0)
}
arr(0)(0)
}
Debugging, I noticed that since arr is lazy and when it reaches the arr(0)(0) expression it tries to evaluate it by calling the Array.tabulate method again -- infinitely over and over.
What am i doing wrong? (I updated the code snippet since I was basing it off the solution given in Dynamic programming in the functional paradigm in particular Antal S-Z's answer )
You have effectively caused an infinite recursion. You simply can't reference a lazy val from within its own initialization code. You need to compute arr(0)(0) separately.
I'm not sure why you are trying to access arr before it's built, tabulate seems to be used to fill the array with a function - calling arr would always result in infinite recursion.
See Rex's example here (and a vote for him), perhaps that will help.
In a multidimensional sequence created with tabulate, is the innermost seq the 1. dimension?
I was able to solve this by wrapping arr(0)(0) in Lazy so it is evaluated as a call-by-name parameter, thereby not evaluating arr in the tabulate method. The code that I referenced was automatically converting it using implicits (the binary + operator), so it wasn't clear cut.
def tabulatePlay(): Int = {
lazy val arr: Array[Array[Lazy[Int]]] = Array.tabulate(10, 10) { (i, j) =>
if (i == 0 && j == 0)
1 // some number
else
new Lazy(arr(0)(0))
}
arr(0)(0)
}
Thanks all.

Arrays in Processing

I'm quite new to programming and have recently started in Processing.
In my code, the collide function sets the touch boolean to be true but by arraying it, it only tests true for the final array and not the ones before it. Where am I going wrong here? I hope my question is clear enough.
edit:
Sorry, let me try again.
I guess my problem is finding out how to array the collide function properly. I cant seem to add a [i] for the collide in the array.
At the moment, the code works but it only tests true for the last array and not for the ones before it.
The array code:
for(int i = 0 ; i < lineDiv; i++){
collide(xPts[i], yPts[i], vecPoints.xPos, vecPoints.yPos, myDeflector.Thk, vecPoints.d);
The collide function:
void collide(float pt1x, float pt1y, float pt2x, float pt2y, int size1, int size2){
if (pt1x + size1/2 >= pt2x - size2/2 &&
pt1x - size1/2 <= pt2x + size2/2 &&
pt1y + size1/2 >= pt2y - size2/2 &&
pt1y - size1/2 <= pt2y + size2/2) {
touch = true;
}
else{
touch=false;
}
Your "touch" variable is global. Every time you call the collide() function, it overwrites whatever it was set to before. Perhaps you just want to test if touch is true after calling collide(), then exit the for loop?
Alternatively, you may want to make collide() return the touch boolean, avoiding the global.
It looks like what you want to do is to run through a loop, run the function on that element of the array and return a value if any of them are true. This is my best guess, you might want to edit your question to clarify what you are looking to do. So assuming this:
1) change you method to a function
boolean collide(float pt1x, float pt1y, float pt2x, float pt2y, int size1, int size2){
if (pt1x + size1/2 >= pt2x - size2/2 &&
pt1x - size1/2 <= pt2x + size2/2 &&
pt1y + size1/2 >= pt2y - size2/2 &&
pt1y - size1/2 <= pt2y + size2/2) {
return true;
}
else{
return false;
}
2) change your loop and how you are calling it
touch = false; // if you don't set this to false before the loop, it will be the last value taken
for(int i = 0 ; i < lineDiv; i++){
if (collide(xPts[i], yPts[i], vecPoints.xPos, vecPoints.yPos, myDeflector.Thk, vecPoints.d)) touch = true;
Before the action would be that touch might cycle between true and false as you iterate through the array and in processing (because you would likely draw out the data) it is unlikely that you would want this behavior because you wouldn't be able to do anything with it unless you packed that data in another structure like an array.
So now, the "touch" is set to false and will change to true if any function calls return a true. If all are false, it will stay false.
note: you might consider using either xPts.length() or yPts.length() vs lineDiv. This would reduce the possibility of a array out of bounds exception assuming xPts and yPts have the same # of elements.

How would I return a value from a function which iterates over a for loop in F#

I am trying loop over an array and return a value as shown below. But this gives me an error on the line after the if statement. It says "This expression was expected to have type unit but has type int"
let findMostSignificantBitPosition (inputBits:System.Collections.BitArray) =
for i = inputBits.Length - 1 to 0 do
if inputBits.[i] then
i
done
How would I do this? I am in the middle of recoding this with a recursive loop, as it seems to be the more accepted way of doing such loops in functional languages, but I still want to know what I was doing wrong above.
for loops are not supposed to return values, they only do an operation a fixed number of times then return () (unit). If you want to iterate and finally return something, you may :
have outside the loop a reference where you put the final result when you get it, then after the loop return the reference content
use a recursive function directly
use a higher-order function that will encapsulate the traversal for you, and let you concentrate on the application logic
The higher-function is nice if your data structure supports it. Simple traversal functions such as fold_left, however, don't support stopping the iteration prematurely. If you wish to support this (and clearly it would be interesting in your use case), you must use a traversal with premature exit support. For easy functions such as yours, a simple recursive function is probably the simplest.
In F# it should also be possible to write your function in imperative style, using yield to turn it into a generator, then finally forcing the generator to get the result. This could be seen as a counterpart of the OCaml technique of using an exception to jump out of the loop.
Edit: A nice solution to avoid the "premature stop" questions is to use a lazy intermediate data structure, which will only be built up to the first satisfying result. This is elegant and good scripting style, but still less efficient than direct exit support or simple recursion. I guess it depends on your needs; is this function to be used in a critical path?
Edit: following are some code sample. They're OCaml and the data structures are different (some of them use libraries from Batteries), but the ideas are the same.
(* using a reference as accumulator *)
let most_significant_bit input_bits =
let result = ref None in
for i = Array.length input_bits - 1 downto 0 do
if input_bits.(i) then
if !result = None then
result := Some i
done;
!result
let most_significant_bit input_bits =
let result = ref None in
for i = 0 to Array.length input_bits - 1 do
if input_bits.(i) then
(* only the last one will be kept *)
result := Some i
done;
!result
(* simple recursive version *)
let most_significant_bit input_bits =
let rec loop = function
| -1 -> None
| i ->
if input_bits.(i) then Some i
else loop (i - 1)
in
loop (Array.length input_bits - 1)
(* higher-order traversal *)
open Batteries_uni
let most_significant_bit input_bits =
Array.fold_lefti
(fun result i ->
if input_bits.(i) && result = None then Some i else result)
None input_bits
(* traversal using an intermediate lazy data structure
(a --- b) is the decreasing enumeration of integers in [b; a] *)
open Batteries_uni
let most_significant_bit input_bits =
(Array.length input_bits - 1) --- 0
|> Enum.Exceptionless.find (fun i -> input_bits.(i))
(* using an exception to break out of the loop; if I understand
correctly, exceptions are rather discouraged in F# for efficiency
reasons. I proposed to use `yield` instead and then force the
generator, but this has no direct OCaml equivalent. *)
exception Result of int
let most_significant_bit input_bits =
try
for i = Array.length input_bits - 1 downto 0 do
if input_bits.(i) then raise (Result i)
done;
None
with Result i -> Some i
Why using a loop when you can use high-order functions?
I would write:
let findMostSignificantBitPosition (inputBits:System.Collections.BitArray) =
Seq.cast<bool> inputBits |> Seq.tryFindIndex id
Seq module contains many functions for manipulating collections. It is often a good alternative to using imperative loops.
but I still want to know what I was
doing wrong above.
The body of a for loop is an expression of type unit. The only thing you can do from there is doing side-effects (modifying a mutable value, printing...).
In F#, a if then else is similar to ? : from C languages. The then and the else parts must have the same type, otherwise it doesn't make sense in a language with static typing. When the else is missing, the compiler assumes it is else (). Thus, the then must have type unit. Putting a value in a for loop doesn't mean return, because everything is a value in F# (including a if then).
+1 for gasche
Here are some examples in F#. I added one (the second) to show how yield works with for within a sequence expression, as gasche mentioned.
(* using a mutable variable as accumulator as per gasche's example *)
let findMostSignificantBitPosition (inputBits: BitArray) =
let mutable ret = None // 0
for i = inputBits.Length - 1 downto 0 do
if inputBits.[i] then ret <- i
ret
(* transforming to a Seq of integers with a for, then taking the first element *)
let findMostSignificantBitPosition2 (inputBits: BitArray) =
seq {
for i = 0 to inputBits.Length - 1 do
if inputBits.[i] then yield i
} |> Seq.head
(* casting to a sequence of bools then taking the index of the first "true" *)
let findMostSignificantBitPosition3 (inputBits: BitArray) =
inputBits|> Seq.cast<bool> |> Seq.findIndex(fun f -> f)
Edit: versions returning an Option
let findMostSignificantBitPosition (inputBits: BitArray) =
let mutable ret = None
for i = inputBits.Length - 1 downto 0 do
if inputBits.[i] then ret <- Some i
ret
let findMostSignificantBitPosition2 (inputBits: BitArray) =
seq {
for i = 0 to inputBits.Length - 1 do
if inputBits.[i] then yield Some(i)
else yield None
} |> Seq.tryPick id
let findMostSignificantBitPosition3 (inputBits: BitArray) =
inputBits|> Seq.cast<bool> |> Seq.tryFindIndex(fun f -> f)
I would recommend using a higher-order function (as mentioned by Laurent) or writing a recursive function explicitly (which is a general approach to replace loops in F#).
If you want to see some fancy F# solution (which is probably better version of using some temporary lazy data structure), then you can take a look at my article which defines imperative computation builder for F#. This allows you to write something like:
let findMostSignificantBitPosition (inputBits:BitArray) = imperative {
for b in Seq.cast<bool> inputBits do
if b then return true
return false }
There is some overhead (as with using other temporary lazy data structures), but it looks just like C# :-).
EDIT I also posted the samples on F# Snippets: http://fssnip.net/40
I think the reason your having issues with how to write this code is that you're not handling the failure case of not finding a set bit. Others have posted many ways of finding the bit. Here are a few ways of handling the failure case.
failure case by Option
let findMostSignificantBitPosition (inputBits:System.Collections.BitArray) =
let rec loop i =
if i = -1 then
None
elif inputBits.[i] then
Some i
else
loop (i - 1)
loop (inputBits.Length - 1)
let test = new BitArray(1)
match findMostSignificantBitPosition test with
| Some i -> printf "Most Significant Bit: %i" i
| None -> printf "Most Significant Bit Not Found"
failure case by Exception
let findMostSignificantBitPosition (inputBits:System.Collections.BitArray) =
let rec loop i =
if i = -1 then
failwith "Most Significant Bit Not Found"
elif inputBits.[i] then
i
else
loop (i - 1)
loop (inputBits.Length - 1)
let test = new BitArray(1)
try
let i = findMostSignificantBitPosition test
printf "Most Significant Bit: %i" i
with
| Failure msg -> printf "%s" msg
failure case by -1
let findMostSignificantBitPosition (inputBits:System.Collections.BitArray) =
let rec loop i =
if i = -1 then
i
elif inputBits.[i] then
i
else
loop (i - 1)
loop (inputBits.Length - 1)
let test = new BitArray(1)
let i = findMostSignificantBitPosition test
if i <> -1 then
printf "Most Significant Bit: %i" i
else
printf "Most Significant Bit Not Found"
One of the options is to use seq and findIndex method as:
let findMostSignificantBitPosition (inputBits:System.Collections.BitArray) =
seq {
for i = inputBits.Length - 1 to 0 do
yield inputBits.[i]
} |> Seq.findIndex(fun e -> e)

Resources