国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 開(kāi)發(fā) > 綜合 > 正文

Lua腳本調(diào)用外部腳本

2024-07-21 23:04:05
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

test.lua腳本定義main函數(shù)如下:

function main(szName, num1, num2)     print("main()", szName, num1, num2);   local nRandMax = 10000;    local nRand = math.random(nRandMax);   print("nRand =", nRand)   return 1; end

現(xiàn)在我想在test.lua腳本中調(diào)用另外一個(gè)test1.lua腳本文件中的GetRandMax(),通常的做法是這樣的:

function main(szName, num1, num2)     print("main()", szName, num1, num2);   dofile("test1.lua")   --加載并編譯運(yùn)行腳本   local nRandMax = GetRandMax();    local nRand = math.random(nRandMax);   print("nRand =", nRand)   return 1; end

看上去是這樣的,非常簡(jiǎn)單,通過(guò)dofile對(duì)test1.lua文件進(jìn)行加載并編譯運(yùn)行,這部操作會(huì)將test1.lua文件中的函數(shù)和變量壓入全局的虛擬棧中,這樣就可以實(shí)現(xiàn)對(duì)GetRandMax()調(diào)用。但是這里有個(gè)問(wèn)題:dofile函數(shù)接受的是需要引用的外部腳本的路徑,如果多次調(diào)用會(huì)不勝其煩,而且效率不高。可能有人誰(shuí)說(shuō),那我們直接把dofile作為全局函數(shù)執(zhí)行,就像這樣:

dofile("test1.lua") dofile("test2.lua") dofile("test3.lua")  function main(szName, num1, num2)     print("main()", szName, num1, num2);   local nRandMax = GetRandMax();  --調(diào)用test1.lua中的函數(shù)   local nRand = math.random(nRandMax);   print("nRand =", nRand)   return 1; end

這樣做是可以的,但是仍然有些問(wèn)題:

    1,如果test.lua文件dofile(test1.lua),而test1.lua文件dofile(test.lua),怎么辦!出現(xiàn)循環(huán)應(yīng)用,執(zhí)行后堆棧溢出;

 

復(fù)制代碼 代碼如下:

test.lua:5: too many C levels (limit is 200) in function at line 5 near '"main()"'

    2,dofile的路徑問(wèn)題,每次都要傳入文件的絕對(duì)路徑,如果路徑不正確,無(wú)法正常執(zhí)行,這也是個(gè)很煩的事。

 

 

復(fù)制代碼 代碼如下:

cannot open /script/test.lua: No such file or directory

那怎樣做才更好呢?既然dofile有這些的問(wèn)題,我們就把這些問(wèn)題解決。在C/C++中實(shí)現(xiàn)Include腳本接口函數(shù),在腳本中作為全局函數(shù)調(diào)用,實(shí)現(xiàn)外部腳本文件包含功能。

 

//腳本接口 TLua_Funcs g_GameFunc[] = {   { "Include",        LuaInclude },   { "ReloadAllScript",    LuaReloadAllScript},   { "SayHello",       LuaSayHello },   { "StopGame",       LuaStopGame }, };

在Include函數(shù)中使用set集合避免重復(fù)包含的問(wèn)題,獲取當(dāng)前的執(zhí)行路徑拼接成絕對(duì)路徑,這樣就省了不少事;)

Include("//script//test1.lua") --Include腳本接口  function main(szName, num1, num2)     print("main()", szName, num1, num2);   local nRandMax = GetRandMax();  --調(diào)用test1.lua中的函數(shù)   local nRand = math.random(nRandMax);   print("nRand =", nRand)   return 1; end

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 崇义县| 绵阳市| 镇远县| 新竹县| 伊吾县| 陇南市| 望江县| 青浦区| 托克托县| 天津市| 镇坪县| 会同县| 慈利县| 滕州市| 渭南市| 灵台县| 浦江县| 宁阳县| 扶绥县| 汝阳县| 安陆市| 永州市| 开封市| 嘉禾县| 库伦旗| 武威市| 汝南县| 平定县| 河池市| 临安市| 天气| 萨嘎县| 凤凰县| 华坪县| 土默特左旗| 兴宁市| 枣阳市| 呼玛县| 禹城市| 盐山县| 准格尔旗|