ToLua学习笔记(二) Example 02 ScriptsFromFile

22 篇文章 0 订阅
11 篇文章 1 订阅

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在第一次加载文件的时候,会执行里面的代码。
但是,第二次之后,再次加载文件,则不会重复执行了.换句话说,它会保存已经加载过的文件,不会重复加载.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值