zoukankan      html  css  js  c++  java
  • lua添加自定义模块的步骤

    以下方法在lua 5.2.4版本下成功实现:

    1. lua.c为所有函数的主程序,参考Makefile的编译链接
    2. lua.c中
    int main (int argc, char **argv) {

    /* call 'pmain' in protected mode */
    lua_pushcfunction(L, &pmain);

    }
    static int pmain (lua_State *L) {
    ...
    luaL_openlibs(L); /* open libraries */
    ...
    }

    3. linit.c中
    static const luaL_Reg loadedlibs[] = {
    {"_G", luaopen_base},
    {LUA_LOADLIBNAME, luaopen_package},
    {LUA_COLIBNAME, luaopen_coroutine},
    {LUA_TABLIBNAME, luaopen_table},
    {LUA_IOLIBNAME, luaopen_io},
    {LUA_OSLIBNAME, luaopen_os},
    {LUA_STRLIBNAME, luaopen_string},
    {LUA_BITLIBNAME, luaopen_bit32},
    {LUA_MATHLIBNAME, luaopen_math},
    {LUA_DBLIBNAME, luaopen_debug},

    {LUA_LOADMYLIBNAME, luaopen_mypackage},

    {NULL, NULL}
    };

    4. lualib.h中
    ...
    #define LUA_LOADLIBNAME "package"
    LUAMOD_API int (luaopen_package) (lua_State *L);

    #define LUA_LOADMYLIBNAME "mypackage"
    LUAMOD_API int (luaopen_mypackage) (lua_State *L);

    /* open all previous libraries */
    LUALIB_API void (luaL_openlibs) (lua_State *L);
    ...

    5. myloadlib.c中
    ...
    static int printhelloworld (lua_State *L) {
    printf("[mypackage] hello world ");
    return 0;
    }

    static int myadd (lua_State *L) {
    printf("%d %d ", (int)luaL_checknumber(L, 1), (int)luaL_checknumber(L, 2));
    lua_pushnumber(L, (int)luaL_checknumber(L, 1) + (int)luaL_checknumber(L, 2));
    return 1;
    }


    static const luaL_Reg my_funcs[] = {
    {"printhelloworld", printhelloworld},
    {"myadd", myadd},
    {NULL, NULL}
    };


    LUAMOD_API int luaopen_mypackage (lua_State *L) {
     
    /* create `package' table */
    luaL_newlib(L, my_funcs);}
    return 1;


    }

    6. Makefile中
    ...
    LIB_O= lauxlib.o lbaselib.o lbitlib.o lcorolib.o ldblib.o liolib.o
    lmathlib.o loslib.o lstrlib.o ltablib.o loadlib.o myloadlib.o linit.o
    ...
    myloadlib.o: myloadlib.c lua.h luaconf.h lauxlib.h lualib.h
    ...

    7. lua中调用
    function helloworld()
    mypackage.printhelloworld();
    print(mypackage.myadd(11,222));
    end

  • 相关阅读:
    .NET委托与事件文章收集
    WCF简介
    设计模式之单例模式
    设计模式之工厂模式
    设计模式之简单工厂模式
    Jquery中bind和live的区别
    C#性能优化实践
    蒋金楠How ASP.NET MVC Works?[持续更新中…]
    按指定质量保存图片
    .net 获取网站根目录总结
  • 原文地址:https://www.cnblogs.com/hugb/p/6892558.html
Copyright © 2011-2022 走看看