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?
-
3Please give more information, we can't answer this.orlp– orlp2011-01-10 23:12:24 +00:00Commented Jan 10, 2011 at 23:12
-
I'm sorry you had trouble understanding. I'm using my own event system; scripts can use the link() global function to add a hook. When an event needs to be called, the program goes through all the Lua functions that are linked to it and calls them using the appropriate arguments. However, after calling too many events, the Lua library (not Java) complains about stack overflow.phpscriptcoder– phpscriptcoder2011-01-11 00:10:31 +00:00Commented Jan 11, 2011 at 0:10
-
1Why is this question tagged luaj if it is about Kahlua?PhiLho– PhiLho2012-10-23 11:42:36 +00:00Commented Oct 23, 2012 at 11:42
4 Answers
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.
Comments
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.
1 Comment
Try and use tail calls where you can, they don't take up a stack slot:
function foo ( )
return bar()
end