Posted on 2014-12-16 17:52
S.l.e!ep.¢% 閱讀(2588)
評論(0) 編輯 收藏 引用 所屬分類:
Lua
????????
//
????????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 的定義
最后,終于調用成功了,淚奔~~~ 三個小時不見了...