lua-users home
lua-l archive

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

> I'm fiddling with an embedded lua 5.0.2 interpreter for a 
> little game I'm 
> writing.  I can make the embedding work and such, but somehow I missed
> something important.
> It appears that lua puts values on the lua stack via "return" 
> and I can 
> pop those off the stack from C with no problem.  (Is there a 
> better way
> for lua to put values on the stack for C to get at?)

You can pass values from Lua to C by:
Setting Lua global variables and retrieving them from C.
Passing arguments from Lua to C functions.
Returning values from Lua functions called from C.

> It's going the other way that I have trouble. I put values on the lua 
> stack from C with lua_push(whatever), but how do I get at 
> them from my lua 
> script when it is run from within the C program?  I'm sort of 
> expecting
> something like perl's "$arg1=shift($_)"

You can pass values from C to Lua by:
Setting Lua global variables from C.
Passing arguments from C to a Lua function.
Returning values from C functions called from Lua.

> BTW, I'm using "lua_dofile" from C to handle my lua script.  
> I'd really
> like to split this into something that loads the lua file and then 
> something that calls functions from that lua file later.  Is there
> a way to do this from the C api so I don't have the cost of 
> "lua_dofile"
> every turn of the game?  


Simple example:

function doSomething( num )
    print( num )

    return 1

//Compile and run test.lua.
lua_dofile( L, "test.lua" );

while( running )
    //retrieve function
    lua_pushstring( L, "doSomething" );
    lua_gettable( L, LUA_GLOBALSINDEX );

    //push argument
    lua_pushnumber( L, 23 );

    //call function
    lua_call( L, 1, 1 );

    //retrieve return value
    lua_Number num = lua_tonumber( L, -1 );

All of this and more is very well explained in the Lua documentation:

and in the book "Programming in Lua":