phpscriptcoder
phpscriptcoder

Reputation: 737

Lua Stack Overflow

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?

Upvotes: 1

Views: 1282

Answers (4)

Kristofer
Kristofer

Reputation: 21

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.

Upvotes: 2

Michal Kottman
Michal Kottman

Reputation: 16753

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.

Upvotes: 2

daurnimator
daurnimator

Reputation: 4311

Try and use tail calls where you can, they don't take up a stack slot:

function foo ( )
    return bar()
end

Upvotes: 0

Rcunn87
Rcunn87

Reputation: 144

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.

Upvotes: 1

Related Questions