#include "stdafx.h"
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif) extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
lua_State* L;
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
int luaadd ( int x, int y )
![](/Images/OutliningIndicators/ExpandedBlockStart.gif) ![](/Images/OutliningIndicators/ContractedBlock.gif) {
int sum;
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) /**//* lua中的函数 */
lua_getglobal(L, "add");
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) /**//* 压入虚拟栈的第一个值 */
lua_pushnumber(L, x);
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) /**//* 第二个值 */
lua_pushnumber(L, y);
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) /**//* 调用传入的两个值,并返回一个结果 */
lua_call(L, 2, 1);
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) /**//*得到结果 ,由于返回类型不同 这里要显示的强制转换*/
sum = (int)lua_tointeger(L, -1);
lua_pop(L, 1);
return sum;
}
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
int _tmain(int argc, _TCHAR* argv[])
![](/Images/OutliningIndicators/ExpandedBlockStart.gif) ![](/Images/OutliningIndicators/ContractedBlock.gif) {
![](/Images/OutliningIndicators/InBlock.gif)
int sum;
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) /**//* Lua初始化*/
L = lua_open();
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) /**//*加载lua基本库 */
luaL_openlibs(L);
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) /**//*加载文件add.lua */
luaL_dofile(L, "add.lua");
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) /**//* 调用加法的方法 */
sum = luaadd( 200, 50 );
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) /**//*打印结果 */
printf( "The sum is %d\n", sum );
lua_close(L);
printf( "Press enter to exit " );
getchar();
return 0;
}
![](/Images/OutliningIndicators/None.gif) 5.cpp文件如下:
|