提交 0b213223 编写于 作者: 东方怂天's avatar 东方怂天

第一次学习记录

上级 ea361cc9
# 安装教程
1. 把Unity打开建个空项目;
2. 从https://github.com/topameng/tolua上把代码搞下来,可以clone或者直接下载zip并解压;
3. 把Assets下的文件复制到项目里的Assets目录下;
4. Unity会自动导入这些文件,然后弹出个确认框说是注册什么的点一下;
5. 在Assets/ToLua/Examples下有很多的例子。
# DoString()
该函数可直接调用指定的 C# 脚本中的指定字符串 lua 代码。
## 注意事项
Lua 中调用C#函数用“:”,字段用“.”
: —— map:GetEnumerator() / iter:MoveNext()
. —— iter.Current.name / map.Keys
## 代码示例
```Csharp
using UnityEngine;
using LuaInterface;
/// <summary>
/// Chinar解释-tolua官方测试案例1
/// </summary>
public class HelloWorld : MonoBehaviour
{
void Awake()
{
LuaState lua = new LuaState();
lua.Start();
string hello = //字符串书写 lua 代码
@"
print('hello tolua#')
";
lua.DoString(hello, "HelloWorld.cs"); //执行C#脚本: HelloWorld 中的 hello字符串
lua.DoString(hello); //效果等同于上面的
lua.CheckTop(); //检验
lua.Dispose(); //释放
lua = null; //质空
}
}
```
# ScriptsFromFile
C#通过文件执行lua脚本
## 注意事项
AddSearchPath() —— 该函数:添加搜索路径,将 lua 与 .Cs 脚本的路径,添加至搜索范围
***注意: 只有先添加了AddSearchPath()搜索路径,才可以保证以下2个函数的正常调用***
DoFile() —— 该函数:执行 ScriptsFromFile.lua 脚本
Require() —— 该函数:执行 引用 ScriptsFromFile lua 脚本
## 代码示例
C#代码
```Csharp
using UnityEngine;
using LuaInterface;
/// <summary>
/// Chinar解释 —— tolua官方测试案例 2
/// 展示 searchpath 使用,require 与 dofile 区别
/// </summary>
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"; //这是官方默认路径,需要自己修改为自己的
string fullPath = Application.dataPath + "\\LuaFramework/ToLua/Examples/02_ScriptsFromFile";
lua.AddSearchPath(fullPath); //添加搜索路径,将lua与.Cs脚本的搜索路径,添加至搜索范围
}
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")) //点击 DoFile 按钮
{
strLog = "";
lua.DoFile("ScriptsFromFile.lua"); //执行 ScriptsFromFile.lua 脚本
}
else if (GUI.Button(new Rect(50, 150, 120, 45), "Require")) //点击 Requre 按钮
{
strLog = "";
lua.Require("ScriptsFromFile"); //执行 引用 ScriptsFromFile 脚本
}
lua.Collect(); //收集GC
lua.CheckTop(); //检验
}
/// <summary>
/// 程序退出时
/// </summary>
void OnApplicationQuit()
{
lua.Dispose(); //释放
lua = null; //质空
#if UNITY_5 || UNITY_2017 || UNITY_2018
Application.logMessageReceived -= Log;
#else
Application.RegisterLogCallback(null);
#endif
}
}
```
Lua代码
```Lua
print("This is a script from a utf8 file")
print("tolua: 你好! こんにちは! 안녕하세요!")
```
# CallLuaFunction()
CallLuaFunction —— C#调用lua函数
## 注意事项
GetFunction() —— 该函数:获取lua中指定test类的luaFunc函数
***注意: 只有先添加了AddSearchPath()搜索路径,才可以保证以下2个函数的正常调用***
DoFile() —— 该函数:执行 ScriptsFromFile.lua 脚本
Require() —— 该函数:执行 引用 ScriptsFromFile lua 脚本
## 代码示例
```Csharp
using UnityEngine;
using LuaInterface;
using System;
/// <summary>
/// Chinar解释 —— tolua官方测试案例 3
/// C#调用lua函数
/// </summary>
public class CallLuaFunction : MonoBehaviour
{
private string script =
@" function luaFunc(num)
return num + 1
end
test = {}
test.luaFunc = luaFunc
function ChinarTest()
print('通过lua对象获取函数')
end
";
LuaFunction luaFunc = null;
LuaState lua = null;
string tips = null;
void Start()
{
#if UNITY_5 || UNITY_2017 || UNITY_2018
Application.logMessageReceived += ShowTips;
#else
Application.RegisterLogCallback(ShowTips);
#endif
new LuaResLoader();
lua = new LuaState();
lua.Start();
DelegateFactory.Init();
lua.DoString(script);
luaFunc = lua.GetFunction("test.luaFunc"); //获取test中的luaFunc函数
if (luaFunc != null)
{
//第一种方法 —— luaFunc.Invoke
int num = luaFunc.Invoke<int, int>(123456); //调用函数返回int值
Debugger.Log("generic call return: {0}", num); //123457
//第二种方法
luaFunc.BeginPCall();
luaFunc.Push(123456);
luaFunc.PCall();
num = (int) luaFunc.CheckNumber();
luaFunc.EndPCall();
Debugger.Log("expansion call return: {0}", num); //123457
//第三种方法 —— 委托调用
Func<int, int> Func = luaFunc.ToDelegate<Func<int, int>>();
num = Func(123456);
Debugger.Log("Delegate call return: {0}", num); //123457
//第四种方法 —— lua.Invoke
num = lua.Invoke<int, int>("test.luaFunc", 123456, true);
Debugger.Log("luastate call return: {0}", num); //123457
//第五种方法 —— LuaFunction . Call()
LuaFunction func = lua["ChinarTest"] as LuaFunction; //lua对象 转 lua函数
func.Call(); //调用lua TestFunc 函数
func.Dispose();
}
lua.CheckTop();
}
void ShowTips(string msg, string stackTrace, LogType type)
{
tips += msg;
tips += "\r\n";
}
#if !TEST_GC
void OnGUI()
{
GUI.Label(new Rect(Screen.width / 2 - 200, Screen.height / 2 - 150, 400, 300), tips);
}
#endif
void OnDestroy()
{
if (luaFunc != null)
{
luaFunc.Dispose();
luaFunc = null;
}
lua.Dispose();
lua = null;
#if UNITY_5 || UNITY_2017 || UNITY_2018
Application.logMessageReceived -= ShowTips;
#else
Application.RegisterLogCallback(null);
#endif
}
}
```
# AccessingLuaVariables()
C#访问lua变量
## 注意事项
***注意: lua["变量名"] —— 通过这种方式对 lua 中的变量进行访问***
lua["TestFunc"] as LuaFunction —— LuaState 对象 转 LuaFunction,调用 lua 中 TestFunc 函数
lua.GetTable("lua 中的表名") —— 获取 lua 中的表,返回类型为LuaTable
## 代码示例
```Csharp
using UnityEngine;
using LuaInterface;
/// <summary>
/// Chinar解释 —— tolua官方测试案例 4
/// C#访问lua中的变量
/// </summary>
public class AccessingLuaVariables : MonoBehaviour
{
private string script =
@"
print('Objs2Spawn is: '..Objs2Spawn)
var2read = 42
varTable = {1,2,3,4,5}
varTable.default = 1
varTable.map = {}
varTable.map.name = 'map'
print(varTable.map.name)
meta = {name = 'meta'}
setmetatable(varTable, meta)
function TestFunc(strs)
print('get func by variable')
end
"; //lua脚本
void Start()
{
#if UNITY_5 || UNITY_2017 || UNITY_2018
Application.logMessageReceived += ShowTips;
#else
Application.RegisterLogCallback(ShowTips);
#endif
new LuaResLoader();
LuaState lua = new LuaState();
lua.Start();
lua["Objs2Spawn"] = 5; //对lua脚本中 Objs2Spawn 赋值 5
lua.DoString(script);
//通过LuaState访问 —— 从lua中读取 var2read 的值
Debugger.Log("Read var from lua: {0}", lua["var2read"]); //42
//LuaState 拆串式table,读取lua表中的值
Debugger.Log("Read table var from lua: {0}", lua["varTable.default"]); //1
LuaFunction func = lua["TestFunc"] as LuaFunction; //lua对象 转 lua函数
func.Call(); //调用lua TestFunc 函数
func.Dispose();
//cache成LuaTable进行访问
LuaTable table = lua.GetTable("varTable");
Debugger.Log("Read varTable from lua, default: {0} name: {1}", table["default"], table["map.name"]);//1 和 无
table["map.name"] = "new"; //table 字符串只能是key
Debugger.Log("Modify varTable name: {0}", table["map.name"]); //打印 new
table.AddTable("newmap"); //表中添加 newmap
//这里 table["newmap"] 是Object类型,所以需要强转为 LuaTable类型
LuaTable table1 = (LuaTable) table["newmap"];
table1["name"] = "table1";
Debugger.Log("varTable.newmap name: {0}", table1["name"]); //打印table1
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_2018
Application.logMessageReceived -= ShowTips;
#else
Application.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);
}
}
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册