示例工程 29-c-api

29-c-api/01-stack-model/main.lua

lua · 0.9 KB

-- @runtimes lua54 luajit
--- 演示:用 Lua 表模拟 C API 栈的正/负索引语义。
local M = {}
 
local Stack = {}
Stack.__index = Stack
function Stack.new()
	return setmetatable({ items = {} }, Stack)
end
function Stack:push(value)
	self.items[#self.items + 1] = value
	return #self.items
end
function Stack:get(index)
	local size = #self.items
	if index < 0 then
		index = size + index + 1
	end
	if index < 1 or index > size then
		error("stack index out of range", 2)
	end
	return self.items[index]
end
 
--- @return table { top = integer, first = integer, negative = integer }
function M.run(log)
	log = log or print
	local stack = Stack.new()
	stack:push(10)
	stack:push(20)
	local top = stack:get(-1)
	local first = stack:get(1)
	local negative = stack:get(-2)
	log(("top=%d first=%d negative=%d"):format(top, first, negative))
	return { top = top, first = first, negative = negative }
end
if not ... then
	M.run()
end
return M