lua require 问题小记

         //
        L  =  luaL_newstate();
        
//  link lua lib
        luaL_openlibs(L);

        
int  err  =   0 ;
        err 
=  luaL_loadfile( L,  " ./lua/test.lua "  );

        
if ( err  !=  LUA_OK )
            printf(
" Failed to load test.lua![%s] " , lua_tostring(L, - 1 ));

一开始,没有注意看错误信息,一看后
Failed to call test.lua ! [. / lua / test.lua: 7 : module  ' test_fun '  not found:
        no field package.preload[
' test_fun ' ]
        no file 
' e:\testproj\lua\test.lua '
        no file 
' e:\testproj\lua\test\init.lua '
        no file 
' e:\testproj\test_fun.lua '
        no file 
' e:\testproj\test_fun\init.lua '
        no file 
' .\test_fun.lua '
        no file 
' e:\testproj\test_fun.dll '
        no file 
' e:\testproj\loadall.dll '
        no file 
' .\test_fun.dll ' ]]]

看清楚后,发现没有,我lua文件的目录
上网一找, 原来可以设置 package.cpath 的目录, 原文在此
int  setLuaPath( lua_State *  L,  const   char *  path )
{
    lua_getglobal( L, 
" package "  );
    lua_getfield( L, 
- 1 " path "  );  //  get field "path" from table at top of stack (-1)
    std:: string  cur_path  =  lua_tostring( L,  - 1  );  //  grab path string from top of stack
    cur_path.append(  " ; "  );  //  do your path magic here
    cur_path.append( path );
    lua_pop( L, 
1  );  //  get rid of the string on the stack we just pushed on line 5
    lua_pushstring( L, cur_path.c_str() );  //  push the new one
    lua_setfield( L,  - 2 " path "  );  //  set the field "path" in table at -2 with value at top of stack
    lua_pop( L,  1  );  //  get rid of package table from top of stack
     return   0 //  all done!
}

运行后,又出现 multiple Lua VMs detected 的错误.

看回我的程序是 exe(link lua lib) --call-> test.lua --call--> ?.dll(link lua lib)

看完 这篇才记起来,lua不能link多份(不然会出问题,记得云风blog有提过)
于是乎,又把 lua 编译成 dll
结果发现 lua.dll 没有导出函数
瞎蒙一阵后,发现 LUA_API 的定义如下
#if  defined(LUA_BUILD_AS_DLL)    /* { */

#if  defined(LUA_CORE) || defined(LUA_LIB)    /* { */
#define  LUA_API __declspec(dllexport)
#else                         /* }{ */
#define  LUA_API __declspec(dllimport)
#endif                         /* } */

#else                 /* }{ */

#define  LUA_API        extern

#endif                 /* } */

然后在工程又加了 LUA_BUILD_AS_DLL 的定义
最后,终于调用成功了,泪奔~~~ 三个小时不见了...

你可能感兴趣的:(lua require 问题小记)