luajit ffi 构造函数参数路由
教程部分中的一个示例:“为 C 类型定义元方法” 如下所示:
local ffi = require("ffi")
ffi.cdef[[
typedef struct { double x, y; } point_t;
]]
local point
local mt = {
__add = function(a, b) return point(a.x+b.x, a.y+b.y) end,
__len = function(a) return math.sqrt(a.x*a.x + a.y*a.y) end,
__index = {
area = function(a) return a.x*a.x + a.y*a.y end,
},
}
point = ffi.metatype("point_t", mt)
local a = point(3, 4)
我对“构造函数”在哪里有点困惑,我假设是默认point(3,4)
是隐式路由3 -> x
和 5 -> y 。当我想将一些逻辑挂在构造函数上时该怎么办?换句话说..如何指定非默认构造函数?
我正在将一堆 C 库包装成面向对象的 lua 代码,并且我不关心规范 lua 的可移植性。具体来说,我需要挂钩面向对象编程的三个核心函数来进行对象生命周期管理:create
、init
、destroy
。我知道 destroy 将是我的类型的 metatable
的 __gc
方法。所以我需要知道如何创建和初始化,并希望避免 luajit 完成的默认初始化。
edit
ffi.new
和其他人有一堆管理类型创建的规则(记录在 luajit 的 ffi 语义页面中)。它在语义部分。我仍然想知道最干净的方法是将自定义创建者和初始化程序(作为 ac 库的一部分)挂到 ffi 对象创建中。
An example in the tutorial section : "Defining Metamethods for a C Type" looks as follows:
local ffi = require("ffi")
ffi.cdef[[
typedef struct { double x, y; } point_t;
]]
local point
local mt = {
__add = function(a, b) return point(a.x+b.x, a.y+b.y) end,
__len = function(a) return math.sqrt(a.x*a.x + a.y*a.y) end,
__index = {
area = function(a) return a.x*a.x + a.y*a.y end,
},
}
point = ffi.metatype("point_t", mt)
local a = point(3, 4)
I'm a bit confused about where the "constructor" is, I assume by default point(3,4)
is implicity routing 3 -> x
and 5 -> y
. What about when I want to hang some logic onto the constructor ? Put differently.. How do I specify a non-default constructor ?
I'm wrapping a bunch of c-libraries into object oriented lua code, and I do not care about portability to canonical lua. Specifically I need to hook in the three core functions of object oriented programming for object lifetime management, create
, init
, destroy
. I know destroy will be the __gc
method of my types' metatable
. So I need to know how to do create
and init
, and hopefully avoid a default initialization done by luajit.
edit
ffi.new
and others have a bunch of rules governing the creation of types (documented in the luajit's ffi semantics page). it's in the semantics section. I'd still like to know what the cleanest way would be to hang custom creators and initializers (that come as part of a c library) into ffi object creation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要包装您的
point
调用才能获得您想要的:或者您可以将您的点函数视为您的创建函数;并且只有一个 init 方法...
注意;点类型的所有对象都已经应用了元表,因此您不需要附加方法或任何东西。
这对我来说似乎有点毫无意义......为什么你想分开创建和初始化?
You'd need to wrap your
point
call to get what you desire:OR you could consider your point function as your create function; and just have an init method...
Note; all objects of the point type already have your metatable applied, so you dont need to attach methods or anything.
It does seem a bit pointless to me.... why do you want to seperate creation and initialization??