Examples:
1 HelloWorld
using UnityEngine;
using LuaInterface;
using System;
public class HelloWorld : MonoBehaviour
{
void Awake()
{
LuaState lua = new LuaState();
//lua_State 中放的是 lua 虚拟机中的环境表、注册表、运行堆栈、虚拟机的上下文等数据。
//从一个主线程(特指 lua 虚拟机中的线程,即 coroutine)中创建出来的新的 lua_State 会共享大部分数据,但会拥有一个独立的运行堆栈。所以一个线程对象拥有一个lua_State。
//Lua_State细节内容:
//https://blog.youkuaiyun.com/chenjiayi_yun/article/details/24304607
lua.Start();
string hello =
@"
print('hello tolua#')
";
lua.DoString(hello, "HelloWorld.cs");//加载并执行?
lua.CheckTop();//销毁前调用了CheckTop,用于检测LUA栈中是否还有未执行的指令
lua.Dispose();
lua = null;
}
}
2 Dofile & Require
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 + "\\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);//打印到GUI上