lua c模块

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include <windows.h>

//dll中定义抛出函数,原型要是Lua_CFunction
/*----------定义函数--------------*/
static int MyLuaDLL_HelloWorld(lua_State* L)
{
     MessageBox(NULL,"Hello","World",MB_OK);
     return 0;
}


static int MyLuaDLL_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;
}


/*-----------注册函数---------------*/
static const luaL_reg MyLuaDLLFunctions [] =
{
     {"HelloWorld",MyLuaDLL_HelloWorld},
     {"average",MyLuaDLL_average},
     {NULL, NULL}
};

int __cdecl __declspec(dllexport) luaopen_MyLuaDLL(lua_State* L)
{
     luaL_openlib(L, "MyLuaDLL", MyLuaDLLFunctions, 0);
     return 1;
}

 //编译生成DLL

-- lua脚本使用上面的DLL中的c api

local testlib = package.loadlib("Lua_Dll.dll","luaopen_MyLuaDLL");
if(testlib)then
    testlib();
else
    -- Error
end

MyLuaDLL.HelloWorld();

a,b=MyLuaDLL.average(23,33,3344);
print("average:",a,"sum:",b);

你可能感兴趣的:(lua c模块)