lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

> char *t="function foo()\n a=1 \n end\n";
> for (int i=0; i < 10000; i++)
>   lua_dostring(L, t);

This is bad for two reasons.
First, there are the memory issues you describe. A different copy of the 
function is created each time, and remains until the garbage collector runs.

Even more inneficiently, however, this means that lua has to parse and 
compile your script each time you iterate through the loop! This is obviously 
quite a waste.

For things such as this, I suggest you not use dostring. Instead, before the 
loop use something like "loadstring" (I'm afraid I'm not in front of my API 
reference right now), which will stick the function on the stack. Then, in 
your loop, each time call:

lua_pushvalue(L, 1); // duplicates the function
lua_call(L, 0, 0); // calls the duplicate, leaves the original

after your loop, use lua_pop to remove the original.

Since this merely creates references to the same function, rather than 
copies, it should be much more efficient.