1. Create a win32 console application.
2. Set the include directory.
3. Set the Lib directory
4. keep an copy of lua5.1.dll in the project folder.
Call an function in lua
Call C++ function in lua
#include "stdafx.h"
#include <stdio.h>
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
/* Lua interpreter */
lua_State* L;
int luaadd ( int x, int y )
{
int sum;
/*Get the function name */
lua_getglobal(L, "add");
/*Pass the first argument */
lua_pushnumber(L, x);
/* Pass second argument */
lua_pushnumber(L, y);
/* call the function with 2
arguments, return 1 result */
lua_call(L, 2, 1);
/* get the result */
sum = (int)lua_tonumber(L, -1);
lua_pop(L, 1);
return sum;
}
int GetArrage(lua_State *L)
{
int n = lua_gettop(L);
float sum = 0;
int i;
for(i=0; i<=n;++i)
{
sum += lua_tonumber(L,i);
}
lua_pushnumber(L,sum/n);
lua_pushnumber(L,sum);
return 2;
}
int main ( int argc, char *argv[] )
{
/* Initial Lua */
L = lua_open();
/* load Lua base lib*/
luaL_openlibs(L);
lua_register(L,"arr", GetArrage);
/* run script */
luaL_dofile(L, "test.lua");
int result = luaadd(1,2);
printf("The result is %d /n", result);
/* clear Lua */
lua_close(L);
printf( "Press enter to exit…" );
getchar();
return 0;
}
lua:
function add(x,y)
a1, a2 = arr(12,32,54,33)
print ("Sum is ", a2)
print ("arrage is ", a1)
return x+y
end