游戏开发技术人员。最走不了的就是脚本语言。而lua是游戏开发最热门的脚本语言。为此也研究过源码。lua小巧而功能强大。而luajit是lua的一个优化版本。接口完全兼容lua却有着更高的效率。google 公司都对这个开源项目非常看好。我个人喜欢的开源项目很多都是google公司的。
lua和其他语言交互靠虚拟机的堆栈。对于刚刚入门的人来说要维护堆栈还是一个比较有难度的工作。由其是使用Userdata的时候。简便的方法是使用开源的包装库来简化封装过程。luabind,luaplus,lua_tinker等等。使用这些库有个最大的问题是降低了灵活度。而且部分库比较臃肿或者对跨平台支持不好。 那么ffi库又什么作用呢? 学过python的都知道cpython库。ffi是一个可以用脚本来实现c语言定义。使脚本在不失灵活的情况下动态的定义c语言的方法。具体效率如何也还没测试过。等以后有空再测试下。先简单演示下用法。
local ffi = require("ffi") ffi.cdef[[ struct foo { int a, b; }; union bar { int i; double d; }; struct nested { int x; struct foo y; }; ]] ffi.new("int[3]", {}) --> 0, 0, 0 ffi.new("int[3]", {1}) --> 1, 1, 1 ffi.new("int[3]", {1,2}) --> 1, 2, 0 ffi.new("int[3]", {1,2,3}) --> 1, 2, 3 ffi.new("int[3]", {[0]=1}) --> 1, 1, 1 ffi.new("int[3]", {[0]=1,2}) --> 1, 2, 0 ffi.new("int[3]", {[0]=1,2,3}) --> 1, 2, 3 ffi.new("int[3]", {[0]=1,2,3,4}) --> error: too many initializers ffi.new("struct foo", {}) --> a = 0, b = 0 ffi.new("struct foo", {1}) --> a = 1, b = 0 ffi.new("struct foo", {1,2}) --> a = 1, b = 2 ffi.new("struct foo", {[0]=1,2}) --> a = 1, b = 2 ffi.new("struct foo", {b=2}) --> a = 0, b = 2 ffi.new("struct foo", {a=1,b=2,c=3}) --> a = 1, b = 2 'c' is ignored ffi.new("union bar", {}) --> i = 0, d = 0.0 ffi.new("union bar", {1}) --> i = 1, d = ? ffi.new("union bar", {[0]=1,2}) --> i = 1, d = ? '2' is ignored ffi.new("union bar", {d=2}) --> i = ?, d = 2.0 ffi.new("struct nested", {1,{2,3}}) --> x = 1, y.a = 2, y.b = 3 ffi.new("struct nested", {x=1,y={2,3}}) --> x = 1, y.a = 2, y.b = 3
是不是很帅呢!个人感觉发展的好的会比luatcc项目要好很多。至少直观了很多。以后做优化就不用那么痛苦了。
当然他还可以直接调用动态库。这里我就不介绍了。有兴趣的朋友自己到luajit的官网去下载查看吧!!
http://luajit.org/