本文意在分析toLua的第二个Example:02_ScriptsFromFile
一.运行工程
点击DoFile和Require都会打印两行文本,区别是DoFile会每次打印,Require只会打印一次

二.API分析
首先
string fullPath = Application.dataPath这行需要修改,直接下载到的路径是错误的
下面是正确的路径,可以加上对fullPath的打印
cs
string fullPath = Application.dataPath + "/LuaFramework/ToLua/Examples/02_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 + "/LuaFramework/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
}
}
2.1 LuaState:AddSearchPath()
增加Lua文件的搜索目录
cs
string fullPath = Application.dataPath + "/LuaFramework/ToLua/Examples/02_ScriptsFromFile";
lua.AddSearchPath(fullPath);
2.2 LuaState:DoFile(string fileName)
每次调用都会执行fileName文件,文件名可以加后缀.lua也可以不加
2.3 LuaState:Require(string fileName)
仅执行一次fileName文件, 不会重复执行