文章目录

  • 案例一:DoString的使用
  • 案例二:展示searchpath 使用,require 与 dofile 区别
  • 案例三:CS调用lua方法
  • 案例四:读写lua的全局变量的两种方式

复习lua与C#调用做的笔记,注释大部分都写在了代码里面

案例一:DoString的使用

using UnityEngine;
using LuaInterface;
using System;public class HelloWorld : MonoBehaviour
{void Awake(){LuaState lua = new LuaState();//lua虚拟机lua.Start();//启动//lua代码string hello =@"                print('hello tolua#')                                  ";lua.DoString(hello, "HelloWorld.cs");//注解(1)lua.CheckTop();//检测堆栈是否平衡,每次都需要手动调用lua.Dispose();注解(2)lua = null;}
}

注解(1)
DoString()函数:执行字符串
注解(2)
lua.CheckTop();
检测堆栈平衡

案例二:展示searchpath 使用,require 与 dofile 区别

public class ScriptsFromFile : MonoBehaviour
{LuaState lua = null;//lua虚拟机private string strLog = "";    void Start () {
#if UNITY_5 || UNITY_2017 || UNITY_2018     Application.logMessageReceived += Log;
#elseApplication.RegisterLogCallback(Log);
#endif         lua = new LuaState();                lua.Start();        //开启虚拟机//如果移动了ToLua目录,自己手动修复吧,只是例子就不做配置了string fullPath = Application.dataPath + "\\ToLua/Examples/02_ScriptsFromFile";//lua文件路径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");       //DoFile                 }else if (GUI.Button(new Rect(50, 150, 120, 45), "Require")){strLog = "";            lua.Require("ScriptsFromFile");            //require}lua.Collect();lua.CheckTop();}void OnApplicationQuit(){lua.Dispose();lua = null;
#if UNITY_5 || UNITY_2017 || UNITY_2018 Application.logMessageReceived -= Log;
#elseApplication.RegisterLogCallback(null);
#endif }
}
lua代码:(ScriptsFromFile)
print("This is a script from a utf8 file")
print("tolua: 你好! こんにちは! 안녕하세요!")

DoFile和Require的区别
(1):经过运行发现每次调用DoFile都会输出,但是Require只会在第一次调用的时候输出。由此说明:DoFile在每次调用的时候都会对lua代码进行重新的加载。查看源码也是如此:

但是Reuire是在执行的时候先检测模块是否存在,如果不存在则加载,存在直接return,源码奉上:

(2)DoFile的参数需要带上.lua后缀,Require不需要后缀,直接名字就可。

案例三:CS调用lua方法

public class CallLuaFunction : MonoBehaviour
{private string script =@"  function luaFunc(num)                        return num + 1endtest = {}test.luaFunc = luaFunc";LuaFunction luaFunc = null;LuaState lua = null;string tips = null;void Start () {
#if UNITY_5 || UNITY_2017 || UNITY_2018Application.logMessageReceived += ShowTips;
#elseApplication.RegisterLogCallback(ShowTips);
#endifnew LuaResLoader();//注解(1)lua = new LuaState();//定义虚拟机lua.Start();//开启虚拟机DelegateFactory.Init();  //注解(2)      lua.DoString(script);//Get the function objectluaFunc = lua.GetFunction("test.luaFunc");//加载test表中的luaFuncif (luaFunc != null){int num = luaFunc.Invoke<int, int>(123456);//注解(3)Debugger.Log("generic call return: {0}", num);luaFunc.BeginPCall();                luaFunc.Push(123456);luaFunc.PCall();        num = (int)luaFunc.CheckNumber();luaFunc.EndPCall();Debugger.Log("expansion call return: {0}", num);//注解(4)Func<int, int> Func = luaFunc.ToDelegate<Func<int, int>>();//注解(5)num = Func(123456);Debugger.Log("Delegate call return: {0}", num);num = lua.Invoke<int, int>("test.luaFunc", 123456, true);//注解6Debugger.Log("luastate call return: {0}", num);}lua.CheckTop();}void ShowTips(string msg, string stackTrace, LogType type){tips += msg;tips += "\r\n";}#if !TEST_GCvoid OnGUI(){GUI.Label(new Rect(Screen.width / 2 - 200, Screen.height / 2 - 150, 400, 300), tips);}
#endifvoid OnDestroy(){if (luaFunc != null){luaFunc.Dispose();luaFunc = null;}lua.Dispose();lua = null;#if UNITY_5 || UNITY_2017 || UNITY_2018Application.logMessageReceived -= ShowTips;
#elseApplication.RegisterLogCallback(null);
#endif}
}

注解(1):new LuaResLoader();
自定义加载lua文件,优先读取persistentDataPath/系统/Lua 目录下的文件(默认下载目录)未找到文件怎读取 Resources/Lua 目录下文件(仍没有使用LuaFileUtil读取),如果不想自定义则直接new LuaResLoader。自定义可参考:自定义加载lua文件,后面也会提到。
注解(2):DelegateFactory.Init();
目前没有很好的理解,大佬们有什么高招吗?
注解(3):int num = luaFunc.Invoke<int, int>(123456)
通用的方式(有GC、慎用)

注解(4):注释3的另一种形式(个人理解),只是对返回值进行了特殊处理。无GC,注意最后的dispose,否则造成内存泄漏。
注释(5):自行理解吧。

注解(6):调用LuaState里面的函数

案例四:读写lua的全局变量的两种方式

using UnityEngine;
using System.Collections.Generic;
using LuaInterface;public class AccessingLuaVariables : MonoBehaviour
{private string script =@"print('Objs2Spawn is: '..Objs2Spawn)var2read = 42varTable = {1,2,3,4,5}varTable.default = 1varTable.map = {}varTable.map.name = 'map'meta = {name = 'meta'}setmetatable(varTable, meta)function TestFunc(strs)print('get func by variable')end";void Start () {
#if UNITY_5 || UNITY_2017 || UNITY_2018Application.logMessageReceived += ShowTips;
#elseApplication.RegisterLogCallback(ShowTips);
#endifnew LuaResLoader();//默认加载luaLuaState lua = new LuaState();//虚拟机lua.Start();//启动lua["Objs2Spawn"] = 5;//相当于在lua文件中加入【Objs2Spawn = 5】即新增一个全局变量lua.DoString(script);//略//通过LuaState访问Debugger.Log("Read var from lua: {0}", lua["var2read"]); //读取第10行的变量,看第十行Debugger.Log("Read table var from lua: {0}", lua["varTable.default"]);  //LuaState 拆串式table,12行LuaFunction func = lua["TestFunc"] as LuaFunction;//TestFunc方法func.Call();//案例3的第一种方式,注意有GC,少量call可使用func.Dispose();//cache成LuaTable进行访问,很好理解LuaTable table = lua.GetTable("varTable");//包装成LuaTableDebugger.Log("Read varTable from lua, default: {0} name: {1}", table["default"], table["map.name"]);table["map.name"] = "new";  //table 字符串只能是keyDebugger.Log("Modify varTable name: {0}", table["map.name"]);table.AddTable("newmap");LuaTable table1 = (LuaTable)table["newmap"];table1["name"] = "table1";Debugger.Log("varTable.newmap name: {0}", table1["name"]);table1.Dispose();table1 = table.GetMetaTable();if (table1 != null){Debugger.Log("varTable metatable name: {0}", table1["name"]);}object[] list = table.ToArray();for (int i = 0; i < list.Length; i++){Debugger.Log("varTable[{0}], is {1}", i, list[i]);}table.Dispose();                        lua.CheckTop();lua.Dispose();}private void OnApplicationQuit(){
#if UNITY_5 || UNITY_2017 || UNITY_2018Application.logMessageReceived -= ShowTips;
#elseApplication.RegisterLogCallback(null);
#endif}string tips = null;void ShowTips(string msg, string stackTrace, LogType type){tips += msg;tips += "\r\n";}void OnGUI(){GUI.Label(new Rect(Screen.width / 2 - 300, Screen.height / 2 - 200, 600, 400), tips);}
}

ToLua的案例学习笔记相关推荐

  1. ArcGIS案例学习笔记-找出最近距离的垂线

    ArcGIS案例学习笔记-找出最近距离的垂线 联系方式:谢老师,135-4855-4328,xiexiaokui@qq.com 目的:对于任意矢量要素类,查找最近距离并做图 数据: 方法: 0. 计算 ...

  2. ArcGIS案例学习笔记2_2_等高线生成DEM和三维景观动画

    ArcGIS案例学习笔记2_2_等高线生成DEM和三维景观动画 计划时间:第二天下午 教程:Pdf/405 数据:ch9/ex3 方法: 1. 创建DEM SA工具箱/插值分析/地形转栅格 2. 生成 ...

  3. ArcGIS模型构建器案例学习笔记-字段处理模型集

    ArcGIS模型构建器案例学习笔记-字段处理模型集 联系方式:谢老师,135-4855-4328,xiexiaokui@qq.com 由四个子模型组成 子模型1:判断字段是否存在 方法:python工 ...

  4. ArcGIS案例学习笔记2_1

    ArcGIS案例学习笔记2_1 联系方式:向日葵,135_4855_4328,xiexiaokui#qq.com 时间:第二天上午 案例1:学校选址 内容:栅格数据分析 教程:pdf page=323 ...

  5. ArcGIS案例学习笔记4_2_城乡规划容积率计算和建筑景观三维动画

    ArcGIS案例学习笔记4_2_城乡规划容积率计算和建筑景观三维动画 概述 计划时间:第4天下午 目的:城市规划容积率计算和建筑三维景观动画 教程: pdf page578 数据:实验数据\Chp13 ...

  6. Unity MVC 案例学习笔记《二》

    MVC 案例学习笔记 注册事件,就是把事件加入到事件字典 发送事件,并携带参数,就是在事件字典中遍历找到具体的 controller 进行处理 using System.Collections; us ...

  7. Hypermesh案例学习笔记

    根据我要自学网Hypermesh2017教程,1-10~1-13课程学习笔记 面板介绍 直接放教程里的图了 模型静力分析 模型导入与简化 尽量使用板壳单元,因此抽取模型中面: 点一下模型,点extra ...

  8. HTML5 案例学习笔记

    目录 1 meta标签 1.1 简介 1.2 属性及取值​ 1.3 案例 2 常用标签 2.1 标题 2.2 段落 2.3 换行 2.4 水平分隔线 2.5 删除线 2.6 下划线 2.7 加粗 2. ...

  9. wireshark取证案例学习笔记

    此文对应wireshark取证分析练习题前5道 题目来源,及PACP包下载地址 自己学习的一点笔记和心得,记录下来以免遗忘. 练习题1的任务书解答 某公司怀疑其雇员张小花是其竞争对手派来的商业间谍.张 ...

最新文章

  1. 机器人暑假班招生推文_机器人兴趣班开学季
  2. “BCH压力测试日”准备工作开启,将允许任何人参与测试
  3. sparkstreaming监听hdfs目录如何终止_Spark笔试题:Spark Streaming 反压机制
  4. springmvc报错 nested exception is org.mybatis.spring.MyBatisSystemException:
  5. 对每个小组的评论和建议
  6. Attention Model
  7. linux四剑客-grep/find/sed/awk/详解-技术流ken
  8. 会声会影背景轨中的所有效果和素材导出为html5格式导入不,如何解决会声会影导入导出的格式问题?...
  9. React 16.8.3 发布,构建用户界面的 JavaScript 库
  10. 多比图形控件教程:基于Flex/Javascript的网页绘图控件
  11. 深入搜索引擎的关键——索引
  12. 攻击银行内网,黑客只要三步
  13. vue el-tree 默认选中_Vue UI:Vue开发者必不可少的工具
  14. GitHub 的 10 分钟快速入门教程
  15. 云课堂在登陆时显示服务器错误,我的云课堂不能登陆怎么解决
  16. 个人博客毕业设计设计总结
  17. HDU 1069 Monkey and Banana(二维偏序LIS的应用)
  18. 浏览器事件模型捕获、冒泡
  19. 用友U9sv服务打开时报错内存入口检查失败,因为可用内存(371662848 字节)少于总内存的 5%
  20. 鸿蒙玺绶能升级么,属性激增 《诛仙2》强力装备大集合(三)

热门文章

  1. 你想找的HTML最全 最精美 易懂文档来了 不好你打我
  2. quartus ii安装器件库问题 you didn`t select any components to install……
  3. 重要预警 | MindLost勒索软件安全建议,安骑士可检测防御
  4. MATLAB | prim算法迷宫生成及其艺术渲染
  5. 三星承认Galaxy S10和Note 10的指纹识别模组存在漏洞
  6. 苹果隐私新政正在重塑互联网巨头的权力格局
  7. 咚咚咚,你的王国之泪已上线「GitHub 热点速览」
  8. 市界 | NFT,今年最烧脑的一场财富大冒险
  9. 维特智能六轴加速度计电子陀螺仪模块姿态角度传感器振动JY61P
  10. STM32开发实例 基于STM32单片机的老人看护系统