在向Unity项目中导入SLua框架时,遇到
[string "..."]:4: expect UnityEngine is type table
stack traceback:
[C]: in function 'assert'
[string "..."]:4: in function 'import'
main:2: in main chunk
网上搜到的教程都差不多,在使用
import "UnityEngine"
的时候,报了如上错误。
从字面上的意思看,是Lua引擎不把UnityEngine看做一个table,而import需要一个table
第一步怀疑是没有将Unity的东西make成Lua可以识别的。
点了N次all-make,还是没用。
看官方demo,发现在Slua-Example-Main场景中使用了import,运行,他没有报错!
原来,他在运行lua脚本之前进行了一次init,代码如下:
using UnityEngine;
using System.Collections;
using SLua;
using UnityEngine.UI;
using System.Collections.Generic;
public class Main : MonoBehaviour
{
LuaSvr l;
public Text logText;
int progress=0;
// Use this for initialization
void Start()
{
#if UNITY_5
Application.logMessageReceived += this.log;
#else
Application.RegisterLogCallback(this.log);
#endif
l = new LuaSvr();
l.init(tick,complete,LuaSvrFlag.LSF_BASIC|LuaSvrFlag.LSF_EXTLIB);
}
void log(string cond, string trace, LogType lt)
{
logText.text += (cond + "\n");
}
//记录初始化进度,用progress变量来记录
void tick(int p)
{
progress = p;
}
//完成之后要做的事
//注意:这里是初始化完成之后才读取lua脚本,而我们之前是直接读取,所以报错了
void complete()
{
l.start("main");
object o = l.luaState.getFunction("foo").call(1, 2, 3);
object[] array = (object[])o;
for (int n = 0; n < array.Length; n++)
Debug.Log(array[n]);
string s = (string)l.luaState.getFunction("str").call(new object[0]);
Debug.Log(s);
}
void OnGUI()
{
//更新初始化的进度条
if(progress!=100)
GUI.Label(new Rect(0, 0, 100, 50), string.Format("Loading {0}%", progress));
}
}
简化过之后:
void InitLua()
{
lua_svr = new LuaSvr();
lua_svr.init(null, complete, LuaSvrFlag.LSF_BASIC | LuaSvrFlag.LSF_EXTLIB);
}
void complete()
{
lua_svr.start("hello");
}
我的lua脚本hello:
import "UnityEngine"
function test()
print("Hello LuaSvr...")
end
test()
成功