Lua是一个轻量级脚本语言,在C++中可以方便的调用、运行Lua脚本。下面的示例参考
http://gamedevgeek.com/2006/05/04/lua-tutorials/,在运行示例之前,需要先配置Visual C++环境,"
附加包含目录"添加"
...\Lua\5.1\include","
附加库目录"添加"
...\Lua\5.1\lib","
附加依赖项"添加"
lua5.1.lib"
第一个例子:
hello.lua文件:
1
|
|
print(
"hello,lua")
|
main.cpp文件:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
#include <iostream>
#include "lua.hpp" /* the Lua interpreter */ lua_State* L; int main ( int argc, char *argv[] ) { /* initialize Lua */ L = lua_open(); /* load Lua base libraries */ luaL_openlibs(L); /* run the script */ luaL_dofile(L, "hello.lua"); /* cleanup Lua */ lua_close(L); /* pause */ printf( "Press enter to exit..." ); getchar(); return 0; } |
运行结果如下图所示:
第二个例子:
add.lua文件:
1
2 3 |
|
function add(x, y)
return x + y end |
main.cpp文件:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
|
#include <iostream>
#include "lua.hpp" /* the Lua interpreter */ 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_tointeger(L, - 1); lua_pop(L, 1); return sum; } int main ( int argc, char *argv[] ) { int sum; /* initialize Lua */ L = lua_open(); /* load Lua base libraries */ luaL_openlibs(L); /* load the script */ luaL_dofile(L, "add.lua"); /* call the add function */ sum = luaadd( 10, 15 ); /* print the result */ printf( "The sum is %d\n", sum ); /* cleanup Lua */ lua_close(L); /* pause */ printf( "Press enter to exit..." ); getchar(); return 0; } |
运行结果如下图所示:
第三个例子:
avg.lua文件:
1
2 3 4 |
|
avg, sum = average(
10,
20,
30,
40,
50)
print( "The average is ", avg) print( "The sum is ", sum) |
main.cpp文件:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
|
#include <iostream>
#include "lua.hpp" lua_State* L; static int average(lua_State *L) { /* get number of arguments */ int n = lua_gettop(L); double sum = 0; int i; /* loop through each argument */ for (i = 1; i <= n; i++) { /* total the arguments */ sum += lua_tonumber(L, i); } /* push the average */ lua_pushnumber(L, sum / n); /* push the sum */ lua_pushnumber(L, sum); /* return the number of results */ return 2; } int main ( int argc, char *argv[] ) { /* initialize Lua */ L = lua_open(); /* load Lua base libraries */ luaL_openlibs(L); /* register our function */ lua_register(L, "average", average); /* run the script */ luaL_dofile(L, "avg.lua"); /* cleanup Lua */ lua_close(L); /* pause */ printf( "Press enter to exit..." ); getchar(); return 0; } |
运行结果如下图所示: