I wrote: > I've attached a parameterized stack datatype as a best-practices > template. Needs latest git HEAD, because I'm looking up the 'new' > method via the ctype. This allows invocation of 'static methods' > aka 'class methods' via the ctype. Since I've just added the __new metamethod, this template can be simplified. Please check the modified attachment. The main user-visible difference is that stack_t:new(max) can be simplified to: stack_t(max) ... and it's still properly initialized. --Mike
local ffi = require("ffi") local function stack_iter(stack) local top = stack.top if top > 0 then stack.top = top-1 return stack.slot[top-1] end end local stack_mt = { __new = function(tp, max) return ffi.new(tp, max, 0, max) end, __index = { push = function(stack, val) local top = stack.top if top >= stack.max then error("stack overflow") end stack.top = top + 1 stack.slot[top] = val end, pop = function(stack) local top = stack.top if top <= 0 then error("stack underflow") end stack.top = top-1 return stack.slot[top-1] end, iter = function(stack) return stack_iter, stack end, } } local function makestack(ct) local tp = ffi.typeof("struct { int top, max; $ slot[?]; }", ct) return ffi.metatype(tp, stack_mt) end local stack_t = makestack(ffi.typeof("double")) local stack = stack_t(100) for i=1,100 do stack:push(i) end for x in stack:iter() do io.write(x, " ") end io.write("\n")