lua-users home
lua-l archive

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

Dear Lua list,

I would like to embedded a Lua interpreter in one of our products (a serial 
protocol analyzer, whereas Lua seems the right tool to enhance the program 
with customer definable protocol rules coded in lua.

I have bought and read the Programming in Lua 2nd edition and started very 
quick with good success. So thanks for this fantastic book and the more 
fantastic language. But now I faced some problem which I don't understand. 
Perhaps someone on this list can point me into the right direction or tell me 
what I missed or missunderstand.

For our project it's necessary to add some C functions to the Lua interpreter 
which make the link between our project API and Lua.
The main problem in short is descriped by the following lines (I kept it as 
simple as possible):

#include <iostream>

#include "lua.hpp"

static int zx = 0;

int l_counter( lua_State* L )
    std::cout << "l_counter()" << std::endl;

    lua_pushinteger( L, zx++ );

    return 1;

int main()

    lua_State *L = lua_open();

    lua_register( L, "counter", l_counter );

    if( luaL_loadstring( L, "result=counter()" ) != 0 ) {

	   std::cout << "Error" << std::endl;


    lua_pcall( L, 0, 0, 0 );

    lua_pcall( L, 0, 0, 0 );

    lua_getglobal( L, "result" );

    std::cout << lua_tostring( L, -1 ) << std::endl;

    return 0;

After running this little program it always output:


I'm a little bit confused because I expected something like:


So why l_counter is just called once. Also as precompiled chunk it should 
execute twice (for my little opinion) and therefor increment the counter.
What I need for is some possibility to execute a precompiled chunk with 
alterable arguments whereas the arguments are provide by the calling C 
Is there any other - perhaps easier - way to do this. Or should I put the 
argument on the stack before calling the precompiled chunk via lua_pcall?

Thank you very much for your help and best regards