在前面一篇tolua筆記《02》- C#調用lua腳本展示了C#如何調用Lua腳本,但示例通過一個string字符串保存的簡單的Lua腳本。而實際項目中,Lua腳本要比這複雜的多,通常也都保存在單獨的腳本文件中供調用。
示例代碼
ScriptsFromFile.lua腳本文件:
print("This is a script from a utf8 file")
print("tolua: 你好! こんにちは! 안녕하세요!")
ScriptsFromFile.cs演示文件:
using UnityEngine;
using System.Collections;
using LuaInterface;
using System;
using System.IO;
//展示searchpath 使用,require 與 dofile 區別
public class ScriptsFromFile : MonoBehaviour
{
LuaState lua = null;
private string strLog = "";
void Start ()
{
#if UNITY_5 || UNITY_2017 || UNITY_2018
Application.logMessageReceived += Log;
#else
Application.RegisterLogCallback(Log);
#endif
lua = new LuaState();
lua.Start();
//如果移動了ToLua目錄,自己手動修復吧,只是例子就不做配置了
string fullPath = Application.dataPath + "\\ToLua/Examples/02_ScriptsFromFile";
lua.AddSearchPath(fullPath);
}
void Log(string msg, string stackTrace, LogType type)
{
strLog += msg;
strLog += "\r\n";
}
void OnGUI()
{
GUI.Label(new Rect(100, Screen.height / 2 - 100, 600, 400), strLog);
if (GUI.Button(new Rect(50, 50, 120, 45), "DoFile"))
{
strLog = "";
lua.DoFile("ScriptsFromFile.lua");
}
else if (GUI.Button(new Rect(50, 150, 120, 45), "Require"))
{
strLog = "";
lua.Require("ScriptsFromFile");
}
lua.Collect();
lua.CheckTop();
}
void OnApplicationQuit()
{
lua.Dispose();
lua = null;
#if UNITY_5 || UNITY_2017 || UNITY_2018
Application.logMessageReceived -= Log;
#else
Application.RegisterLogCallback(null);
#endif
}
}
演示效果
分析說明
AddSearchPath
AddSearchPath用來添加索引路徑,類似c++中添加庫函目錄
將需要搜索的路徑通過AddSearchPath添加之後DoFile的時候會直接去找對應的Lua文件
DoFile
執行文件中的代碼.
Require
require和dofile有點像,不過又很不一樣,require在第一次加載文件的時候,會執行裏面的代碼。
但是,第二次之後,再次加載文件,則不會重複執行了.換句話說,它會保存已經加載過的文件,不會重複加載.