ToLua学习笔记(三) Example 03 CallLuaFunction
2016-07-06 11:56
483 查看
ToLua学习笔记(三) Example 03 CallLuaFunction
转载请注明出处四川包邮ToLua学习笔记三 Example 03 CallLuaFunction
代码
GetFunction
两种调用方式的区别
为什么这两种调用方式会有这种区别
这一篇文章会讲解如何调用Lua中的函数
代码
//#define TEST_GC using UnityEngine; using System.Collections; using LuaInterface; using System; public class CallLuaFunction : MonoBehaviour { private string script = @" function luaFunc(num) return num + 1 end test = {} test.luaFunc = luaFunc "; LuaFunction func = null; LuaState lua = null; string tips = null; void Start () { #if !TEST_GC #if UNITY_5 Application.logMessageReceived += ShowTips; #else Application.RegisterLogCallback(ShowTips); #endif #endif lua = new LuaState(); lua.Start(); lua.DoString(script); //Get the function object func = lua.GetFunction("test.luaFunc"); if (func != null) { //有gc alloc object[] r = func.Call(123456); Debugger.Log("generic call return: {0}", r[0]); // no gc alloc int num = CallFunc(); Debugger.Log("expansion call return: {0}", num); } 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 (func != null) { func.Dispose(); func = null; } lua.Dispose(); lua = null; #if !TEST_GC #if UNITY_5 Application.logMessageReceived -= ShowTips; #else Application.RegisterLogCallback(null); #endif #endif } int CallFunc() { func.BeginPCall(); func.Push(123456); func.PCall(); int num = (int)func.CheckNumber(); func.EndPCall(); return num; } //在profiler中查看gc alloc #if TEST_GC void Update () { func.Call(123456); //CallFunc(); } #endif }
GetFunction
通过GetFunction可以获取Lua中的函数// Get the function object func = lua.GetFunction("test.luaFunc");
两种调用方式的区别
// 会有gc alloc func.Call(123456); // 没有gc alloc int CallFunc() { func.BeginPCall(); func.Push(123456); func.PCall(); int num = (int)func.CheckNumber(); func.EndPCall(); return num; }
为什么这两种调用方式会有这种区别
引用官方文档中的原文(1)有gc alloc : func.Call(123456) 之所以有gc内存分配,原因在于Call函数参数类型是object[] Call(params object[] args),为啥会有这个问题,就是引擎的问题了。但是对于tolua#来说也没有找到可变参数的替代类型,所以先用着吧。
(2)no gc alloc:这个方式没有gc内存分配,原因就是舍去了params object[] args,但是写法有些麻烦,所有的参数都要func.Push(123456);进去后,再执行func.PCall(); 调用,然后再通过num = (int)func.CheckNumber();拿到lua代码执行的返回值。
至于选择那种?是选择方便,还是高效,大家自己选择吧。
相关文章推荐
- 详解Lua中的表的概念及其相关操作方法
- Lua编程示例(二):面向对象、metatable对表进行扩展
- 把Lua编译进nginx步骤方法
- Lua脚本自动生成APK包
- Lua中的元表(metatable)、元方法(metamethod)详解
- Lua中的metatable介绍
- Lua中ipair和pair的区别
- Lua中的函数精讲笔记
- 浅谈Lua的面向对象特性
- 详解Lua中的变量相关知识点
- Lua脚本语言入门笔记
- Lua脚本调用外部脚本
- 详解Lua中的if语句的使用方法
- Lua中调用函数使用点号和冒号的区别
- Lua中的闭合函数、非全局函数与函数的尾调用详解
- Lua中强大的元方法__index详解
- Lua中调用C++函数示例
- Lua面向对象之类和继承浅析
- Lua性能优化技巧(一):前言
- Lua中获取table长度问题探讨