Lua and C call each other

 

Lua provides a powerful API for interacting with C, and the transfer of values ​​between the two is achieved through a virtual stack.

 

1. Implement the Lua interpreter

 

/**
 * Lua interpreter
 */
int main( int argc, char **argv )
{
	// initialize the interpreter
	lua_State * pl = luaL_newstate ();
	// Load basic libraries, including io, os, math, etc.
	luaL_openlibs( pl );

	// execute lua script
	luaL_dofile( pl, "./hello.lua" );
	
	lua_close( pl );
	return 0;
}

 

 

The above little code implements the lua interpreter, running and printing hello world.

 

2. C calls Lua functions

2.1 Lua function implementation

 

-- add
function add( x, y )
        return x + y
end

 

 

2.2 Calling Lua functions

 

/**
 * lua passes values ​​through the virtual stack
 *
 */
int luaadd (lua_State * l, int x, int y)
{	
	// via add() in lua
	lua_getglobal( l, "add" );
	
	// parameter x is pushed onto the stack
	lua_pushnumber (l, x);
	// push y to the stack
	lua_pushnumber (l, y);
	
	// call, nargs=2, nresults=1
	lua_call (l, 2, 1);
	
	// coercion (the top element of the stack)
	int sum = (int) lua_tointeger (l, -1);
	
	// stack balance
	lua_setglobal( l, "add );
	return sum;
}

/**
 * C call lua test
 *
 */
int Calllua_test()
{
	// init
	lua_State * l = luaL_newstate ();
	luaL_openlibs(l);

	// execute lua script
	luaL_dofile( l, "./add.lua" );

	// call lua's add()
	int sum = luaadd(l, 10, 15);
	printf( "Lua add: %d\n", sum );

	lua_close( l );
	return 0;
}

 

Results of the:

Moon add: 25

 

3. Lua calls C

3.1 Lua calling code

-- average

function main()
        local avg, sum = average( 2, 2, 3, 5 )
        print( "avg: ", avg )
        print( "sum: ", sum )
end
main()

 

3.2 C Mean Realization

/**
 * get the average
 */
static int average( lua_State *l )
{
	// get the number of parameters
	int n = lua_gettop (l);
	
	double sum = 0;
	
	int i = 0;
	for( i=1; i<=n; i++ )
	{
		sum += lua_tonumber(l, i);
	}
	
	// push the average
	lua_pushnumber(l, sum/n);
	// push and
	lua_pushnumber(l, sum);
	
	// return the number of values
	return 2;
}

/**
 * Lua calls C tests
 *
 */
int Callc_test()
{
	// init
	lua_State * l = luaL_newstate ();
	luaL_openlibs(l);

	// register
	lua_register( l, "average", average );
	
	// do
	luaL_dofile( l, "./avg.lua" );

	lua_close( l );
	return 0;
}

 

Results of the:

avg:    3.0
sum:    12.0

 

 

Parameter link:

http://www.lua.org/manual/5.3/manual.html

http://www.jb51.net/article/72661.htm

 

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326578154&siteId=291194637