ToLua學習筆記(二) Example 02 ScriptsFromFile

ToLua學習筆記(二) Example 02 ScriptsFromFile

轉載請註明出處四川包郵

這一篇文章主要是通過Example講解searchpath,require,dofile.

測試

通過運行Example可以發現,不管點擊多少次DoFile,每次都會在屏幕上顯示

This is a script from a utf8 file
tolua: 你好! こんにちは! 안녕하세요!

但是點擊Require只有第一次會出現,之後就無效了

This is a script from a utf8 file
tolua: 你好! こんにちは! 안녕하세요!

示例代碼

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     
        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     
        Application.logMessageReceived -= Log;
#else
        Application.RegisterLogCallback(null);
#endif 
    }
}

函數用法

AddSearchPath

AddSearchPath用來添加索引路徑,類似c++中添加庫函目錄
將需要搜索的路徑通過AddSearchPath添加之後DoFile的時候會直接去找對應的Lua文件

DoFile

執行文件中的代碼.

Require

require和dofile有點像,不過又很不一樣,require在第一次加載文件的時候,會執行裏面的代碼。
但是,第二次之後,再次加載文件,則不會重複執行了.換句話說,它會保存已經加載過的文件,不會重複加載.

發佈了32 篇原創文章 · 獲贊 87 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章