Lua Stack Overflow - java

I'm developing a Java application that uses Kahlua for embedded Lua scripting. After calling a lot of functions it always crashes with a stack overflow... is there something I need to do to remove unused call frames from the stack?

In standard Lua, you can use the lua_pop function to remove items from the Lua stack. See this answer for hints on this usage.
If you are calling your code repeatedly, the easiest thing to do is store the height of the stack before the processing and restore it afterwards:
int top = lua_gettop(L);
... /* some processing involving the stack*/
lua_settop(L, top);
Now, I'm not sure how to achieve this in Kahlua. But in the source I see LuaCallFrame.getTop() and LuaCallFrame.setTop() so the code should be similar.

If you're using the Kahlua framework correctly, the stack should automatically get cleaned up when returning from a function. If this is not so, you've found a bug, and I would very much like a bug report on it :)
Best would a (close to) minimal testcase which exposes the problem.

You have to make sure you return out of every method call. For example:
...main(...){
displayMenu();
}
void displayMenu(){
System.out.println("1.Do A. \n2.Do B");
int q = readInt;
if (q==1){
doA();
}else{
doB();
}
}
void doA(){
.....
displayMenu()
}
void doB(){
....
displayMenu();
}
A way to make the stack not blow up is to do something like this:
...main(...){
while(true){displayMenu()};
}
void displayMenu(){
System.out.println("1.Do A. \n2.Do B");
int q = readInt;
if (q==1){
doA();
}else{
doB();
}
}
void doA(){
.....
}
void doB(){
....
}
This way all the calls return back to the base level.

Try and use tail calls where you can, they don't take up a stack slot:
function foo ( )
return bar()
end

Related

How do I fix this stack overflow error in my code below?

I am trying to find the square of a number using the scanner method but keep getting a
stackflow error. I am new to programming will be glad if someone helps me out.
My code is as below
import java.util.Scanner;
interface Number {
int findSqr(int i); // Returns the square of n
}
//a class A which implements the interface Number.
class A implements Number {
public int findSqr(int i) {
return findSqr(i);
}
}
public class Question5_1{
public static void main (String[] args){
A a = new A(); // an object of class A
// Reading a number from the keyboard
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.print(a.findSqr(i));
}
}
Fix the line which invokes the function recursively return findSqr(i) with return i * i as follows --
public int findSqr(int i) {
return i * i;
}
What you did there is an infinite recursion. The bit where it says
public int findScr(int i) {
return findSqr(i)
}
essentially calls the very same method an infinite number of times in the return statement.
What happens is, that you execute the method, and it tries to return an integer. What you wrote though is a return statement that "returns" another call of the same method, so it gets executed again. Then the whole thing starts over again, so you get a StackOverflow.
Since there is no other code present, I have no idea what you are actually trying to do, but the return findSqr(i) line is what causes the problem.
Initially, recursion may be a rather complicated subject to really wrap you head around, I suggest you either avoid it for now (although it enables you to solve many problems in a really elegant way) or try to understand it a bit better maybe. I'd suggest the Wikipedia article about recursion, although it gets complicated quite fast, or any other tutorial on it, just look it up on Google.

Return in else branch of void function

Is it good or bad practice to have an else branch which only returns in a function that returns type void? Such as this code:
public void myFunc() {
if (<some condition>) {
//run some code
} else {
return;
}
}
Note that this topic is opinion based, you will probably see many different preferences from user to user.
For readability and maintainability you should try to reduce the complexity of your code. Therefore you want to also reduce the nesting. Thus my prefered variant would be:
public void myFunc() {
// Directly leave if condition does not hold
if (!condition) {
return;
}
// Now do the rest of the code
}
If you want to stick to your current variant then I would suggest to just drop the else part because it just aggravates the readability in my opinion, so:
public void myFunc() {
if (condition) {
// Do something
}
// You can always leave a comment if you think
// that helps a reader, so you can put "Do nothing
// if condition does not hold" here
}
However as said, I personally prefer the first variant because it reduces the nesting of the overall code.
No, this else statement is not required if you are not doing any operation.
The else statement is basically used to carry out an operation, if the condition of if do not met.The best practice is not to write the else statement, if you are not doing any operation.
public void myFunc() {
if (<some condition>) {
//call FunctionA();
} else {
//call FunctionB();
}
}
In the above case, the use of else is valid. But if you are not doing any operation, then the statement is useless. Please read Clean Code Book by Robert Cecil Martin. It will help you in writing clean code.
From the java.lang.Void class documentation:
The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.
So any of the following would suffice:
Parameterizing with Object and returning new Object() or null.
Parameterizing with Void and returning null.
Parameterizing with a NullObject of yours.
You can't make this method void, and anything else returns something. Since that something is ignored, you can return anything.

Java - stop function from its normal run

Is there any easy way such as break for whiles to stop/skip a running function?
public void a(){
do_this();
//break the function here
do_that(); //do not load this
}
What I want to approach could be done with boolean and if statements as well, but I was wondering if there was some shortcut command in order to do this.
public void a(){
do_this();
if(1==1)
return;
do_that(); //do not load this
}
Just curious, why do you want to write such a code?
let the first function return a boolean that indicates if the calling function should move on:
public void a(){
boolean doContinue = do_this();
if(doContinue) {
do_that();
}
}
i you ALWAYS want to skip the second part, it's dead code. you could just remove it.
Always have in mind that your code should be readable for other programmers!

Java delaying return of variable

How can I delay returning a varaible from a method in Java, or how should I do it if it is something unwanted to do?
Consider this:
public class Transaction {
public int addInsert() {
...
return insertId;
}
public boolean addUpdate() {
...
return updateSuccesful;
}
public void commit() {
/* Calls everything that is inserted via addInsert or addUpdate. */
}
}
Now assume you use the code as:
Transaction transaction = new Transaction();
int insertedId = transaction.addInsert();
boolean updateSuccesful = transaction.addUpdate();
//insertId, updateSuccesful cannot be known yet
transaction.commit();
//now insertId, updateSuccesful should be filled in
So the return may only happen if transaction.commit() has been called.
Any thoughts?
You can achieve this functionality by multithreading and making the threads that are running those two methods .wait() until the commit() method calls .notify() to let them know that they can finish.
However, a better way to structure this is to re-organize your your methods, perhaps by making commit return the insertedID and make it return -1 if it is unsuccessful. That way you can check the boolean by seeing if it is -1 or not, and you can read the ID by reading the return of commit.
You're example looks like the Unit of Work Pattern: http://martinfowler.com/eaaCatalog/unitOfWork.html
Which also shows the answer to your question.
You can't actually call method a, and have it's return value delayed until you call method b without getting into threading, and that's still going to be an overly complicated and very brittle solution to the problem.
Instead call method a, method b etc. However don't actually do the work until the commit happens. Then the commit returns, or you can call a getMethodAStatus() etc.

Implementing Stack's Pop method with Recursion

I am self-studying java. I have been studying data structures for the past couple of days. I am reading the book "Data Structures and Algorithms in Java". there is an exercise that I have problem with. it asks for implementing the pop method with recursion so that when the method is called it should delete all the items at once. can anyone help on this? a pointer on how to do it would be much appreciated. thanks. (following is the pop method currently implemented).
public double pop() // take item from top of stack
{
return stackArray[top--]; // access item, decrement top
}
First IMO you should understand how to implement a non-recursive counterpart of this method.
It can be something like this:
public void popAll() {
while(!stack.isEmpty()) {
stack.pop();
}
}
Once you understand this, the recursive version should be easy:
public void popAllRecursive() {
if(stack.isEmpty()) {
//nothing to remove, return
return;
}
stack.pop(); // remove one stack element
popAllRecursive(); // recursive invocation of your method
}
Since its an exercise I just provide you an idea and leave the implementation to you (you can consider to provide the method in class Stack and use the top counter and stackArray - an implementation of your stack.
Hope this helps
You need to think about the base case where there is nothing in the stack, i.e. stack.pop() == null.
For the recursive case, it is quite intuitive as you just need to recursively call pop() until the base case is met.
Call pop() repeatedly till end of stack.
As you have not mentioned how the data is stored cant help you providing code.
thanks every one, i solved the problem. don't know if efficient, but i did like below:
public void pop()
{
if(isEmpty()){
return;
}
if (top>=0){
stackArray[top] = stackArray[top--];
pop();
}
}

Categories