// Win32Console.cpp : Defines the entry point for the console application. // #include "stdafx.h" extern"C" { #include "D:/Lib/Lua/lua.h" #include "D:/Lib/Lua/lualib.h" #include "D:/Lib/Lua/lauxlib.h" } #pragma comment( lib ,"D:/Lib/Lua/lua51.lib") lua_State *L; //调用lua double fun( double x, double y ) { double ret; lua_getglobal( L, "add"); // 获取全局变量f lua_pushnumber( L,x); // 操作数压栈 lua_pushnumber( L,y); // 操作数压栈 lua_call( L, 2, 1); // 执行:2个操作数,1个返回值 //lua_pcall( L, 2, 1, 0); // 保护模式的lua_call,0为错误处理码。具体应用暂时不明,在使用手册中有粗略介绍 ret = lua_tonumber( L, -1); // 将栈顶元素转换成数字并赋值给ret lua_pop( L, 1); // 从栈中弹出一个元素 return ret; } //被lua调用的方法 staticint average(lua_State *L2) { /**//* get number of arguments */ int n = lua_gettop(L2); double sum =0; int i; /**//* loop through each argument */ for (i =1; i <= n; i++) { /**//* total the arguments */ sum += lua_tonumber(L2, i); } lua_pushnumber(L, sum / n); /**//* push the sum */ lua_pushnumber(L, sum); /**//* return the number of results */ printf("average called. [ok]\n"); return2; } //============================================== // Main Functions //============================================== int main( void) { int error; L = lua_open(); // 创建Lua接口指针(借用DX的术语,本质是个堆栈指针) luaopen_base(L); // 加载Lua基本库 luaL_openlibs(L); // 加载Lua通用扩展库 /**//* 可能有的文章会采用以下写法,手工控制加载哪些库: luaopen_table(L); // 加载table库 luaopen_io(L); // 加载IO库 luaopen_string(L); // 加载string库 luaopen_math(L); // 加载math库 经过测试,luaopen_io(L);该句执行异常,可能跟Lua的IO库有关系。具体原因暂时没有追究,将来如果有机会弄清楚,再回头来阐述。 */ /**//* load the script */ lua_register(L, "average", average); error = luaL_dofile(L, "hellow.lua"); // 读取Lua源文件到内存编译 double ret = fun( 10, 3.4); // 调用模版函数f printf( "ret = %f\n", ret); // 输出结果,C语言的东西,跟Lua无关 lua_close( L); return1; }
创建一个hellow.lua文件和main.cpp放在一起,写入以下内容
function add ( x, y) file = assert(io.open("data.txt", "w")) file:write("abcde\n") file:write("ok!\n") file:close() --DataDumper(1,2,3,4) file = assert(io.open("data.txt", "r")) str = file:read("*a") io.write(str) io.write("\n") avg, sum = average(10, 200, 3000) print("The average is ", avg) print("The sum is ", sum) return x + y end