forked from Wiladams/LAPHLibs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathffi_stack.lua
More file actions
61 lines (49 loc) · 1.07 KB
/
ffi_stack.lua
File metadata and controls
61 lines (49 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
--[[
This code came from Mike Pall, who is the author of
the LuaJIT program.
It was written as a demonstration of how best to
implement a data structure with parameterized types.
This can be seen in the makestack() function.
--]]
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
return {
makestack = makestack,
stack_iter = stack_iter,
}