|
Warning: this is an htmlized version!
The original is here, and the conversion rules are here. |
-- This file:
-- http://angg.twu.net/LUA/Stack1.lua.html
-- http://angg.twu.net/LUA/Stack1.lua
-- (find-angg "LUA/Stack1.lua")
-- Author: Eduardo Ochs <eduardoochs@gmail.com>
--
-- Used by: (find-angg "LUA/DiagForth1.lua")
-- (find-angggrep "grep --color=auto -nH --null -e Stack LUA/*.lua")
-- Based on: (find-dn6 "stacks.lua" "Stack")
-- «.Stack» (to "Stack")
-- «.Stack-tests» (to "Stack-tests")
-- «Stack» (to ".Stack")
Stack = Class {
type = "Stack",
new = function () return Stack {} end,
__tostring = function (s) return s:tostring() end,
__index = {
tostring = function (s) return mapconcat(tostring, s, " ") end,
print = function (s) print(s); return s end,
PP = function (s) PP(s); return s end,
--
push = function (s,o) table.insert(s, o); return s end,
pushs = function (s,...) for _,o in ipairs({...}) do s:push(o) end; return s end,
--
check = function (s) assert(#s>0, s.msg or "Empty stack"); return s end,
drop = function (s) s:check(); s[#s]=nil; return s end,
dropn = function (s,n) for i=1,n do s:drop() end; return s end,
dropuntil = function (s,n) while #s>n do s:drop() end; return s end,
clear = function (s) return s:dropn(#s) end,
--
dropn_ = function (s,n) s:dropn(n); return end,
pop = function (s) return s[#s], s:dropn_(1) end,
pop2 = function (s) return s[#s-1],s[#s], s:dropn_(2) end,
pop3 = function (s) return s[#s-2],s[#s-1],s[#s], s:dropn_(3) end,
pop4 = function (s) return s[#s-3],s[#s-2],s[#s-1],s[#s], s:dropn_(4) end,
--
pick = function (s,offset) return s[#s-offset] end,
pock = function (s,offset,o) s[#s-offset] = o; return s end,
--
-- Methods for "metastacks", that are stacks whose elements
-- are the depths of another stack, that is stored in `s.ds'.
meta_push = function (ms) ms:push(#(ms.ds)); return ms end,
meta_pop = function (ms) ms.ds:dropuntil(ms:pop()); return ms end,
meta_at = function (ms,offset) return ds[ms:pick(0) + offset + 1] end,
},
}
-- «Stack-tests» (to ".Stack-tests")
--[[
* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
dofile "Stack1.lua"
ds = Stack.new()
= ds
= ds:push(22):push(33):pushs(44, 55, 66) --> 22 33 44 55 66
= ds:pick(0) --> 66
= ds:pick(1) --> 55
= ds:pick(2) --> 44
= ds:dropn(3):pushs(444,555,666) --> 22 33 444 555 666
= ds:pop4() --> 33 444 555 666
= ds --> 22
ds = Stack.new()
depths = Stack {ds=ds}
= ds:pushs(11, 22, 33, 44) --> 11 22 33 44
= depths:meta_push() --> 4
= ds:pushs(55, 66) --> 11 22 33 44 55 66
= depths:meta_push() --> 4 6
= ds:pushs(77, 88, 99) --> 11 22 33 44 55 66 77 88 99
= depths:meta_at(0) --> 77
= depths:meta_at(1) --> 88
= depths:meta_at(2) --> 99
= depths --> 4 6
= ds --> 11 22 33 44 55 66 77 88 99
= depths:meta_pop() --> 4
= ds --> 11 22 33 44 55 66
= depths:meta_pop() -->
= ds --> 11 22 33 44
= ds:clear()
--]]
-- Local Variables:
-- coding: utf-8-unix
-- End: