lua5.2 c模块

#include <stdio.h>

/* su.lua --- dofile("su.lua")
main = require("util")
print(main.add(1,2));

function add(a,b)
return main.add(a,b)
end
*/
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
};


extern "C"
{

    int add(lua_State*L)
    {
        int n = lua_gettop(L);
        lua_pushnumber(L,lua_tonumber(L,-1)+lua_tonumber(L,-2));

        return 1;
    }

    int sub(lua_State*L)
    {
        lua_pushnumber(L,lua_tonumber(L,-1)-lua_tonumber(L,-2));
        return 1;
    }


    static luaL_Reg mylibs[] =
    {
        {"add", add},
        {"sub", sub},
        {NULL, NULL}
    };
};

extern "C"
{
    
     __declspec(dllexport) int luaopen_util(lua_State*L)
     {
         // lua-v5.2
         lua_newtable(L);
         luaL_setfuncs(L,mylibs,0);

#if 0    lua_version <= 5.1
        luaL_register(L,"util",mylibs);
#endif
         return 1;
     }
};

你可能感兴趣的:(lua5.2 c模块)