我正在使用幻像类型来模拟堆栈的状态,作为 ocaml-lua 的包装器模块(Lua 通过堆栈与 C/OCaml 通信)。小代码示例:
type 's t
type empty
type 's table
type top
val newstate : unit -> empty t (* stack empty *)
val getglobal : empty t -> top table t (* stack: -1 => table *)
某些堆栈操作在表和数组表上都是可能的(Lua 中没有真正的数组);有些不是。所以如果我有类型
type 's table
type 's array
我想要一种类似 table-or-array 的函数,用于在这两种类型上运行的函数,但仍然能够rawgeti
在表上禁止例如(数组操作)。objlen
是一个堆栈操作,它返回堆栈顶部元素的“长度”。该元素可以是表或数组表。目前,包装函数定义如下:
val objlen : (top table) t -> int
我想要的是
val objlen : (top table-or-array) t -> int
也就是说,array
并且table
是 的子类型table-or-array
。
有任何想法吗?
问候 Olle
编辑
经过考虑,我想出了这个:
module M : sig
type ('s, 't) t
(* New Lua state with empty stack *)
val newstate : unit -> (unit, unit) t
(* Get table *)
val getglobal : ('a) t -> ([< `table | `string | `number | `fn], 'a) t
(* Get array index and put "anything" on top of stack *)
val rawgeti : ([`table], 'a) t -> ([< `table | `string | `number | `fn], [`table] * 'a) t
(* String on top of stack *)
val tostring : ([`string], _) t -> string
(* Table or array-table on top of stack *)
val objlen : ([`table], _) t -> int
val pop : ('a, 'b * 'c) t -> ('b, 'c) t
end = struct
type top
type ('s, 't) t = string (* Should really be Lua_api.Lua.state *)
(* Dummy implementations *)
let newstate () = "state"
let gettable s = s
let getarray s = s
let rawgeti s = s
let tostring s = "Hello phantom world!"
let objlen s = 10
let pop s = s
end
类型级别的堆栈现在应该知道的不比堆栈本身多或少。例如,rawgeti 将推送任何类型的堆栈。