新建windows32 consol程序,只有一个.cpp文件
.cpp文件内容为:
#include <stdio.h>
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
/* Lua解释器指针 */
lua_State* L;
int luaadd ( int x, int y )
{
int sum;
/* the function name */
lua_getglobal(L, "add");
/* the first argument */
lua_pushnumber(L, x);
/* the 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 main ( int argc, char *argv[] )
{
int sum;
/* 初始化Lua */
L = lua_open();
/* 载入Lua基本库 */
luaL_openlibs(L);
/* 运行脚本 */
luaL_dofile(L, "e12.lua");
/* call the add function */
sum = luaadd( 10, 15 );
/* print the result */
printf("The sum is %d\n", sum );
/* 清除Lua */
lua_close(L);
/* 暂停 */
printf( "Press enter to exit…" );
getchar();
return 0;
}
e12.lua文件内容为
-- add two numbers
function add ( x, y )
return x + y
end
将e12.lua保存后放到C++程序执行文件的目录下,运行可执行文件即可得到结果。
注意:要得到结果只能直接运行执行文件,如果在VC中点击运行和调试运行都不能得到结果