The Test.lua script defines the main function as follows:
function Main (SzName, NUM1, num2)
print ("Main ()", SzName, NUM1, num2);
Local Nrandmax = 10000;
Local Nrand = Math.random (Nrandmax);
Print ("Nrand =", Nrand) return
1;
End
Now I want to invoke the Getrandmax () in another Test1.lua script file in the Test.lua script, which is usually done:
function Main (SzName, NUM1, num2)
print ("Main ()", SzName, NUM1, num2);
Dofile ("Test1.lua") --load and compile run script local
Nrandmax = Getrandmax ();
Local Nrand = Math.random (Nrandmax);
Print ("Nrand =", Nrand) return
1;
End
Looks like this, very simple, through the dofile to Test1.lua file loading and compiling run, this operation will Test1.lua file functions and variables into the global virtual stack, so you can implement the Getrandmax () call. But here's the problem: the Dofile function accepts the path of an external script that needs to be referenced, and if multiple calls are annoying and inefficient. Maybe someone who says that we directly execute dofile as a global function, like this:
Dofile ("Test1.lua")
dofile ("Test2.lua")
dofile ("Test3.lua")
function Main (szName, NUM1, num2)
Print ("Main ()", SzName, NUM1, num2);
Local Nrandmax = Getrandmax (); --Call the function in Test1.lua local
Nrand = Math.random (Nrandmax);
Print ("Nrand =", Nrand) return
1;
End
This can be done, but there are still some problems:
1, if Test.lua file Dofile (Test1.lua), and Test1.lua file Dofile (Test.lua), how to do! The loop application occurs and the stack overflows after execution;
Copy Code code as follows:
Test.lua:5: Too many C levels (limit are) in function at line 5 near ' "Main ()" "
2,dofile path problem, each time you want to pass the absolute path of the file, if the path is not correct, not normal execution, this is also a very annoying thing.
Copy Code code as follows:
Cannot open \script\test.lua:no such file or directory
So what's the best way to do it? Now that dofile have these problems, we will solve them. Implement the Include script interface function in C + +, as a global function call in the script, to implement the external script file contains functionality.
Script interface Tlua_funcs g_gamefunc[] = {
{"Include", luainclude},
{"Reloadallscript", luareloadallscript },
{"SayHello", Luasayhello},
{"Stopgame", luastopgame},
};
Use set sets in the Include function to avoid duplicate inclusions, and to get the current execution path spliced into an absolute path, saving a lot of things;
Include ("\\script\\test1.lua")--include Script interface
function main (szName, NUM1, num2)
print ("Main ()", SzName, NUM1, num2);
Local Nrandmax = Getrandmax (); --Call the function in Test1.lua local
Nrand = Math.random (Nrandmax);
Print ("Nrand =", Nrand) return
1;
End